Converts a SOAP string to an object

image_pdfimage_print
   
 

/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Xml.Serialization;


namespace Utilities
{
    /// <summary>
    /// Helps with serializing an object to XML and back again.
    /// </summary>
    public static class Serialization
    {



        /// <summary>
        /// Converts a SOAP string to an object
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="SOAP">SOAP string</param>
        /// <returns>The object of the specified type</returns>
        public static T SOAPToObject<T>(string SOAP)
        {
            if (string.IsNullOrEmpty(SOAP))
            {
                throw new ArgumentException("SOAP can not be null/empty");
            }
            try
            {
                using (MemoryStream Stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(SOAP)))
                {
                    SoapFormatter Formatter = new SoapFormatter();
                    return (T)Formatter.Deserialize(Stream);
                }
            }
            catch { throw; }
        }

    }
}

   
     


Is Well Formed Xml

image_pdfimage_print
   
 
///////////////////////////////////////////////////////////////////////////////////////////////
//
//    This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
//    Copyright (c) 2005-2008, Jim Heising
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without modification,
//    are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright notice,
//      this list of conditions and the following disclaimer in the documentation and/or
//      other materials provided with the distribution.
//
//    * Neither the name of Jim Heising nor the names of its contributors may be
//      used to endorse or promote products derived from this software without specific prior
//      written permission.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//    IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;

namespace WOSI.Utilities
{
    public class StringUtils
    {

        public static bool IsWellFormedXml(string inputString)
        {
            XmlTextReader xmlReader = new XmlTextReader(new System.IO.StringReader(inputString));

            try
            {
                while(xmlReader.Read())
                {
                }

                xmlReader.Close();
                return true;
            }
            catch
            {
            }

            xmlReader.Close();
            return false;
        }
   }
}

   
     


Strip Non Valid XML Characters.

image_pdfimage_print

//http://facebooktoolkit.codeplex.com/
//http://facebooktoolkit.codeplex.com/license
using System.Collections.Generic;
using System.Text;

namespace Facebook.Utility
{
///

/// Helper functions for string manipulation
///

public static class StringHelper
{
///

/// Strip Non Valid XML Characters.
///

public static string StripNonValidXMLCharacters(string s)
{
StringBuilder _validXML = new StringBuilder(s.Length, s.Length); // Used to hold the output.
char[] charArray = s.ToCharArray();

if (string.IsNullOrEmpty(s)) return string.Empty; // vacancy test.

for (int i = 0; i < charArray.Length; i++) { char current = charArray[i]; if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD))) _validXML.Append(current); } return _validXML.ToString(); } } } [/csharp]

Use XmlReaderSettings to validate the Xml document

image_pdfimage_print
   
 


using System;
using System.Xml;
using System.Xml.Schema;

class ConsoleValidator {
    private bool failed;
    public bool Failed {
        get { return failed; }
    }

    public bool ValidateXml(string xmlFilename, string schemaFilename) {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;

        XmlSchemaSet schemas = new XmlSchemaSet();
        settings.Schemas = schemas;
        schemas.Add(null, schemaFilename);
        settings.ValidationEventHandler += ValidationEventHandler;
        XmlReader validator = XmlReader.Create(xmlFilename, settings);
        failed = false;
        try {
            while (validator.Read()) { }
        } catch (XmlException err) {
            Console.WriteLine(err.Message);
            failed = true;
        } finally {
            validator.Close();
        }
        return !failed;
    }
    private void ValidationEventHandler(object sender, ValidationEventArgs args) {
        failed = true;
        Console.WriteLine("Validation error: " + args.Message);
    }
}

class MainClass {
    private static void Main() {
        ConsoleValidator consoleValidator = new ConsoleValidator();
        bool success = consoleValidator.ValidateXml("ProductCatalog.xml", "ProductCatalog.xsd");
        Console.WriteLine(success);
    }
}

           
         
     


Use XML schema to validate XML documents

image_pdfimage_print
   
 
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Validate {
  public static void Main(string [] args) {

    using (Stream stream = File.OpenRead(args[0])) {
      XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(stream));
      reader.ValidationType = ValidationType.Schema;
      reader.Schemas.Add("", args[1]);
      reader.ValidationEventHandler += new ValidationEventHandler(Handler);

      while (reader.Read()) {
      }
    }
    Console.WriteLine("Document is valid.");
  }

  public static void Handler(object sender, ValidationEventArgs e) {
    Console.WriteLine(e.Message);
  }
}

           
         
     


Validate Schema

image_pdfimage_print
   
 
using System;
using System.IO;
using System.Xml.Schema;

public class ValidateSchema {
  public static void Main(string [] args) {
    ValidationEventHandler handler = new ValidationEventHandler(ValidateSchema.Handler);
    XmlSchema schema = XmlSchema.Read(File.OpenRead(args[0]),handler);
    schema.Compile(handler);
  }

  public static void Handler(object sender, ValidationEventArgs e) {
    Console.WriteLine(e.Message);
  }
}

           
         
     


Validate an XML Document Against a Schema

image_pdfimage_print
   
 
using System;
using System.Xml;
using System.Xml.Schema;

public class ConsoleValidator {
    public static void ValidateXml(string xmlFilename, string schemaFilename) {
        XmlTextReader r = new XmlTextReader(xmlFilename);
        XmlValidatingReader validator = new XmlValidatingReader(r);
        validator.ValidationType = ValidationType.Schema;

        XmlSchemaCollection schemas = new XmlSchemaCollection();
        schemas.Add(null, schemaFilename);
        validator.Schemas.Add(schemas);

        validator.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
            
        try {
            while (validator.Read())
            {}
        }catch (XmlException err) {
            Console.WriteLine(err.Message);
        }finally {
            validator.Close();
        }
    }

    private static void ValidationEventHandler(object sender, ValidationEventArgs args) {
        Console.WriteLine("Validation error: " + args.Message);
    }
    private static void Main() {
        Console.WriteLine("Validating your.xml.");
        ValidateXml("your.xml", "your.xsd");
    }    
}