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>

Thursday, February 16, 2012

Write XML Data Dynamically

public void WriteDataToXML(string filePath, string[] fieldsList, string[] fieldsValue)
{
try
{
if (fieldsList.Length.Equals(fieldsValue.Length))
{
int arrayLength = fieldsList.Length;
if (File.Exists(filePath))
{
XDocument xDocument;
xDocument = XDocument.Load(filePath);
XElement rootElement = new XElement("Details");
XElement dataElement = new XElement("Data");
for (int count = 0; count < arrayLength; count++)
{
XElement element = new XElement(fieldsList[count], fieldsValue[count]);
dataElement.Add(element);
}
xDocument.Element("Details").Add(dataElement);
xDocument.Save(filePath);
}
else
{
XElement rootElement = new XElement("Details");
XElement dataElement = new XElement("Data");
for (int count = 0; count < arrayLength; count++)
{
XElement element = new XElement(fieldsList[count], fieldsValue[count]);
dataElement.Add(element);
}
rootElement.Add(dataElement);
rootElement.Save(filePath);
}
}
}
catch (Exception ex) { }
}

Wednesday, April 27, 2011

Create XML file using LINQ

public void AddProductCategory(string filePath, string productCategory)
{
XDocument oXDoc;
try
{
if (File.Exists(filePath))
{
oXDoc = XDocument.Load(filePath);
oXDoc.Element("DataContent").Add(
new XElement("Data",
new XElement("ID", Guid.NewGuid().ToString()),
new XElement("CategoryName", productCategory)
));
oXDoc.Save(filePath);
}
else
{
XElement oXElmnt = new XElement("DataContent",
new XElement("Data",
new XElement("ID", Guid.NewGuid().ToString()),
new XElement("CategoryName", productCategory)
));
oXElmnt.Save(filePath);
}
}
catch (Exception ex) { }
}

Wednesday, June 30, 2010

Create Excel file with save Dialog in ASP.Net

DataTable will have the data to write into Excel file
fileName will be Excel file name with extension(.xls/.xlsx)

public void SaveExcelFile(string fileName, DataTable dtData)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + "");
HttpContext.Current.Response.Flush();
for (int colCount = 0; colCount < dtData.Columns.Count; colCount++)
{
HttpContext.Current.Response.Write(dtData.Columns[colCount].ColumnName.ToString());
HttpContext.Current.Response.Write("\t");
}
for (int rowCount = 0; rowCount < dtData.Rows.Count; rowCount++)
{
HttpContext.Current.Response.Write("\n");
for (int colCount = 0; colCount < dtData.Columns.Count; colCount++)
{
HttpContext.Current.Response.Write(dtData.Rows[rowCount][colCount].ToString());
HttpContext.Current.Response.Write("\t");
}

}
HttpContext.Current.Response.End();
}
catch (Exception ex)
{ }
}

Motivational qoutes

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