Test-Drive SQL Server Data Services: C# 3.0, LINQ to XML: Autogenerate REST XML Entity Templates: Listing 1

A SqlDataReader instance and LINQ to XML functional construction combine to enable autogenerating the XML payload for the help file's sample CreateEntity() function from table metadata. Much of the code in this snippet, which is excerpted from the sample app's CreateEntitySet( ) method for the REST protocol, is devoted to replacing .NET data type designations with SSDS's more limited XML Schema type repertoire.

string setXml = null;
SqlConnection connNwind = new SqlConnection(strNwind)
SqlCommand cmdNwind = new SqlCommand("SELECT * 
   FROM [" + tableName + "]", connNwind)
SqlDataReader sdrNwind = cmdNwind.ExecuteReader(
while (sdrNwind.Read())
   // Create an XElement with XAttributes for each column
   var entElement = new XElement(new XElement(entityType,
         new XAttribute(XNamespace.Xmlns + "s", 
         new XAttribute(XNamespace.Xmlns + "xsi", 
         new XAttribute(XNamespace.Xmlns + "x", 
      from col in Enumerable.Range(0, sdrNwind.FieldCount)
      select new XElement(sdrNwind.GetName(col),
         new XAttribute("xsi:type", "x:" + 
   setXml = setElement.ToString();
   // String identifier change
   setXml = setXml.Replace('\"', '\'');
   // Type fixups with "x:system." prefix for specificity
   setXml = setXml.Replace("x:system.uint64", 
   setXml = setXml.Replace("x:system.uint32", 
   setXml = setXml.Replace("x:system.uint16", 
   setXml = setXml.Replace("x:system.int64", 
   setXml = setXml.Replace("x:system.int32", 
   setXml = setXml.Replace("x:system.int16", 
   setXml = setXml.Replace("x:system.byte[]",
   setXml = setXml.Replace("x:system.byte", 
   setXml = setXml.Replace("x:system.sbyte", 
   setXml = setXml.Replace("x:system.single", 
   setXml = setXml.Replace("x:system.double", 
   setXml = setXml.Replace("x:system.decimal", 
   setXml = setXml.Replace("x:system.datetime", 
   setXml = setXml.Replace("x:system.boolean",
   setXml = setXml.Replace("x:system.char", "x:string");
   setXml = setXml.Replace("x:system.guid", "x:string");
   setXml = setXml.Replace("x:system.string", 
   // Special case: Temporarily remove elements 
   // with nil values
   setXml = setXml.Replace("<ShippedDate 
      xsi:type='x:decimal'></ShippedDate>", "");
// Code to remove empty elements for value types goes here
// ...
// POST the entity using sample code from SSDS help file

CreateEntity(containerUri, setXml);
comments powered by Disqus
Most   Popular
Upcoming Events

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.