Wednesday, September 4, 2013

Serialize the class object into XML

Sometimes there is requirement to convert/serialize an object into the XML format so that we can do some operation and manipulation based on the XML data. Here is the simple trick to convert the object data into XML format.

This piece of code will give you the result of Serialized XML by converting an object.

void SerializeXml<T>(string filePath, object objectToSerialize)
        {
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(fs, objectToSerialize);
                fs.Flush();
                fs.Close();
                fs.Dispose();
            }
            catch (Exception ex)
            {              
            }
        }

Serialize the Class object into XElement

If you have the requirement to convert object of data into the XElement form, then here is the solution for the same. the below piece of code will give output in the form of XElement by serializing the object of the class.
This method takes input as object and cast this with the class as of type "T" and returns the output into XElement format.

XElement ToXElement<T>(object objectToSerialize)
        {
            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    using (TextWriter streamWriter = new StreamWriter(memoryStream))
                    {
                        var xmlSerializer = new XmlSerializer(typeof(T));
                        var xmlSerializerNamespace = new XmlSerializerNamespaces();
                       // To make namespace empty
                        xmlSerializerNamespace.Add(string.Empty, string.Empty);
                        xmlSerializer.Serialize(streamWriter, objectToSerialize, xmlSerializerNamespace);
                        xElement = XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));  
                    }
                }
            }
            catch (Exception ex)
            {
                xElement = null;            
            }
            return xElement;
        }

Friday, April 5, 2013

Send XML data through web service as POST (Attachment)

By this piece of code in C# we can send the data to the web service as an attachment in the POST method.


                ASCIIEncoding encoding = new ASCIIEncoding();
                string postdata = "<Root><Info>Value</Info></Root>";
                byte[] data = encoding.GetBytes(postdata);
                Uri uri = new Uri("Your service url");
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(uri);
                myRequest.Method = "POST";
                myRequest.ContentType = "text/xml;charset=utf-8";
                myRequest.Timeout = 30000;
                NetworkCredential netCredentials = new NetworkCredential("Username", "Password");
                CredentialCache crendentials = new CredentialCache();
                crendentials.Add(uri, "Basic", netCredentials);
                myRequest.Credentials = crendentials;
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
           
// Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();

                // Get response

                using (HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream
                    System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                    Stream objStream = response.GetResponseStream();
                    StreamReader objSR = new StreamReader(objStream, encode, true);
                    string sResponse = objSR.ReadToEnd();
                }

Thursday, March 7, 2013

Convert XML string into DataTable object


 public DataTable ConvertXMLIntoDataTable(string inputData)
        {
            DataTable dtDataConverted = null;
            try
            {              
                StringReader stringReader = new StringReader(inputData);
                DataSet dsData = new DataSet();
                dsData.ReadXml(stringReader);
                dtDataConverted = dsData.Tables[0];
            }
            catch (Exception ex)
            {  }
            return dtDataConverted;
        }

Convert Datatable object into XElement object


public XElement ConvertDataTableIntoXElement(DataTable dtData)
        {
            XElement xElementConverted = null;
            try
            {
                xElementConverted = new XElement("container");
                using (XmlWriter xmlWriter = xElementConverted.CreateWriter())
                { dtData.WriteXml(xmlWriter, System.Data.XmlWriteMode.WriteSchema, true); }
            }
            catch (Exception ex)
            {  }
            return xElementConverted;
        }

Wednesday, March 6, 2013

Basic RESTful service in WCF

operation contract in the interface for the WCF service

[OperationContract]
        [WebInvoke(Method = "GET",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = "/ValidateXMLData?inputData={inputData}")]
        string ValidateXMLData(string inputData);

In the .svc file do the implementation for the interface.

   public string ValidateXMLData(string inputData)
        {
            string validatedString=string.Empty;
            try
            {
                 XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(inputData);
                validatedString = inputData;
            }
            catch (Exception ex)
            { }
            return validatedString;
        }

service configuration in your web.Config file

<system.serviceModel>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="MyService.Services.RestService">
        <endpoint address="XML"
                  behaviorConfiguration="restPoxBehavior"
                  binding="webHttpBinding"
                  contract="MyService.Contracts.IRestService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restPoxBehavior">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

Motivational qoutes

पूरे विश्वास के साथ अपने सपनों की तरफ बढ़ें। वही ज़िन्दगी जियें जिसकी कल्पना आपने की है।