Archive

Archive for May, 2012

Rename xml tag name in C#

May 3, 2012 2 comments

XmlTextReader reader = new XmlTextReader(“Report.xml”);
XmlTextWriter tw = new XmlTextWriter(“NewReport.xml”, null);//null represents encoding
tw.Formatting = Formatting.Indented;  //for xml tags to be indented//
tw.WriteStartDocument();

while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
if (reader.Name == “NewDataSet”)
{
tw.WriteStartElement(“root”);
}
else if (reader.Name == “Table”)
{
tw.WriteStartElement(“user”);
}

else

{

tw.WriteStartElement(reader.Name);

}

break;;
case XmlNodeType.Text: //Display the text in each element.
tw.WriteValue(reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
tw.WriteEndElement();
break;
}
}

tw.Flush();
tw.Close();

Categories: ASP.NET

Convert objects to JSON in C# using JavaScriptSerializer

Create a simple Product class

class Product

{

public string pId;

public string pName;

public int pQuantity;

}

Product p=new Product();

p.pId=”ID989″;

p.pName=”Item1″;

p.pQuantity=5;

System.Web.Script.Serialization.JavaScriptSerializer serl=new System.Web.Script.Serialization.JavaScriptSerializer();

string jsonString=serl.Serialize(p);

Categories: ASP.NET

Adding Web Service to Websites – Visual Studio 2010

File -> New -> Websites -> <name your website>

Go Solution Explorer

Right Button Solution  -> Add New Item -> Web Service -> <name your webservice>

Add a new WebMethod in webservice page as

[WebMethod]
public int Add(int a,int b)
{
return a + b;
}

Run this webservice and copy the url of this page from browser.

Select Menu  Website -> Add Service Reference

Paste the address in Address field and click Go

Edit the namespace.

Click OK

In Default.aspx.cs …

protected void Page_Load(object sender, EventArgs e)
{
YourServiceReferenceName.WebServiceSoapClient pp = new YourServiceReferenceName.WebServiceSoapClient();
int sum=pp.Add(6, 8);
Response.Write(sum);
}

Run Default.aspx

Categories: ASP.NET