How To Force WCF Service To Use XmlSerializer Instead Of The DataContractSerializer



TODO:

Have you ever wanted to return Attributes, or have further control over serialization when using WCF?  By default, it uses the DataContractSerializer, but you can tell it to use the XmlSerializer.  

 

SOLUTION:

1.  Ensure you have your interface marked with [ServiceContract]

2.  Add XmlSerializerFormat to your method

 [ServiceContract]

 publicinterfaceIMyService


 [WebGet(UriTemplate = "employee")]

 [OperationContract]

 [XmlSerializerFormat]

 Response GetEmployees();

 

Now your WCF call will use the XmlSerializer rather than the DataContractSerializer.


NOTES:

There are no notes on this topic.

How To Nicely Format An XML Document



TODO:

Have you have XML in a text editor such as notepad, and the formatting is non existent.  Sometimes it is nice to have it indented for use in a PDF or Word Document.  Well, after instaling a few tools, it turns out it can be done in Visual Studio quite easily.

 

SOLUTION:

Open the document in Visual Studio (I use 2010).  Hit CTRL-A, then CTRL-K, then CTRL-F

Your XML will now look nice and indented.

 

NOTES:

There are no note on this topic.

Properties Marked As Obsolete() Are Not Serialized



TODO:

Have you ever marked a property as Obsolete(), and noticed that it is empty whe DeSerialzie occurs.

 

SOLUTION:

It appears that Obsolete() is the same as XmlIgnore().  I found this article interesting in explaining why this happens: connect.microsoft.com

 

NOTES:

There are no notes on this topic.

How To Skip The First X Nodes During foreach Loop In XSLT



TODO:

Have you ever wanted to skip the first X nodes during a foreach loop?  In my case, I was taking a flat CSV file and turning it into a generic XML document.  I was then using XSLT to transform that document into a meaningful XML document representing Customer.  The first 2 rows of my CSV file, were header and file information only, therfore I did not want to process them.  Rather than hard code the rows to skip in a pre-processor for the flat file, I can just transform the data to my final document, and then skip X rows in XSLT.  I was using XSLT anyhow to create my customer document, so it was just as easy to put the logic there.

 

SOLUTION:

 

<?xml version='1.0' ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <Customers>
      <xsl:variable name="myRootNode" select="."/>
      <xsl:for-each select="$myRootNode/MyNodes/Node">
        <xsl:variable name="myNode" select="."/>
        <xsl:if test="position() > 2">
           <Customer>
             Do Your Other XSLT Stuff Here ...
           </Customer>
        </xsl:if>
      </xsl:for-each>
    </Customers>
  </xsl:template>
</xsl:stylesheet>

 

NOTES:

This will skip the first 2 nodes I encounter, which represents the first 2 header rows that I had in my document.

How To Select The Entire Contents Of A Varchar(max) Or NVarchar(max) Column In SQL Server Management Studio



TODO:

Have you ever wanted to select a varchar(max), or nvarchar(max) column in SSMS?  You will notice that the data is truncated when you have a large amount of data stored in the column.  To get around this we will convert the string to XML, then save the results to an XML file, so you can open in your favorite XML editor / viewer.

 

SOLUTION:

 

--to select a column with NON-XML data
select convert(xml,'<xml><![CDATA[' + cast(LogData as varchar(max)) + ']]></xml>') FROM LogTable where Id = 1234

--to select a column with XML data
select convert(xml, LogData) FROM LogTable where Id = 1234

 

 

NOTES:

The first example wraps the data in CDATA tags, so that it will be well-formed XML. 

The second example does not, because I am storing well-formed XML in the column already.

How To Serialize An Object Using C#



TODO:

Have you ever wanted to Serialize an object using C#?  The method I created below, will allow you to pass in an object and turn it into an XML Document.

 

SOLUTION:

/// <summary>
/// 
/// </summary>
/// <param name="myObject"></param>
/// <returns></returns>
public static XmlDocument MakeXmlDocumentFromObject(Object myObject)
{
     UTF8Encoding encoding = new UTF8Encoding();
     XmlDocument returnObject = new XmlDocument();

     try
     {
          //create our serializer
          XmlSerializer xmlSerial = new XmlSerializer(myObject.GetType());

          //get it....
          using (MemoryStream memStream = new MemoryStream())
          {
               //serialize the object
               xmlSerial.Serialize(memStream, myObject);

               //load the XML now, and we will return it....
               returnObject.LoadXml(encoding.GetString(memStream.GetBuffer()));
          }

          return returnObject;
     }
     catch (Exception)
     {
          return null;
     }
}

 

NOTES:

There are no notes on this subject.

How to Transform XML Using XSLT And Deserialize The Result Using C#



TODO:

Have you ever wanted to load an XML Document, transform it using XSLT, and conver the result into a Class object?  This is handly so that you could take XML in various formats, use XSLT to transform it, and load it into Classes that your system knows about.

 

SOLUTION:

Dog myDog = new Dog();
XmlSerializer xmlSerial = new XmlSerializer(typeof(Dog));   //create the xmlserializer for class Dog
XmlDocument myXMLDocument = new XmlDocument();              //create the xml document
StringBuilder output = new StringBuilder();                 //create the string builder for the output
XslCompiledTransform myXslTrans = new XslCompiledTransform();  //create the xsl obj for transformation
XmlWriterSettings writerSettings = new XmlWriterSettings();    //create the writer settings object, as we want to omit XML declaration
writerSettings.OmitXmlDeclaration = true;                      //now set the omit flag to true
myXMLDocument.Load(@"c:\DogInput.xml");

//load xslt file
myXslTrans.Load(xsltfile);

//create an xmlwriter of out data
using (XmlWriter transformedData = XmlWriter.Create(output, writerSettings))
{
     //transform the document
     myXslTrans.Transform(myXMLDocument, transformedData);

     //now turn the string builder into an obj
     using (StringReader xmlString = new StringReader(output.ToString()))
     {
          myDog = (Dog)(xmlSerial.Deserialize(xmlString));
     }
}

 

NOTES:

Dog is a class i created to illustrate this task, you will put your classname in place of it.  The variable "xsltfile" is the path to your XSLT file.

How To Find a Node At Any Level In An XML Document



TODO:

Have you ever wanted to find a Node, named "CustomerName" for example anywhere in an XML Document?

 

SOLUTION:

 

XmlNodeList customerNameNodes = MyXMLDocument.SelectNodes("//CustomerName");

 

NOTES:

There are no notes on this topic.

How To Copy All Nodes And Change The Value Of Certain Nodes



TODO:

Have you ever wanted to copy an XML document, but change certain node data during the copy?

 

SOLUTION:

 

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
 
  <!-- copy your input verbatim -->
  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*" />
    </xsl:copy>
  </xsl:template>

  <!-- Now copy book id now appending the prefix to the data -->
  <xsl:template match="/Books/Book/BookID">
    <BookID>SomeValue-<xsl:apply-templates select="@*|node()"/></BookID>
  </xsl:template>

</xsl:stylesheet>

 

 

NOTES:

There are no notes on this topic.

There is an error in the document xmlns= was not expected



TODO:

Have you ever received the message "There is an error in the document (1,2) <MyElement xmlns=''> was not expected." when deserializing an XML string?

 

SOLUTION:

After much headache, it turned out that the person was sending me xml that had the proper tags, but had the incorrect case.  XML is case sensitive, so be sure to check that first, especially if it was working before.

 

NOTES:

There are no notes for this topic.