Tuesday, August 6, 2013

Web Service in C# with XML return format

I am writing here a web service in C# for xml output. please check the below example. this will surely help you.

[WebMethod(Description = "User Authentication")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
    public List LoginAuthentication(string struserID, string strPassword)
    {
        SqlConnection objConnection = new SqlConnection(strconnectionString);
        SqlCommand objCommand = new SqlCommand("SELECT * FROM UserInformation where UserID='" + struserID + "' and Password='" + strPassword + "' ", objConnection);
        DataSet objDataSet = new DataSet();
        SqlDataAdapter objDataAdapter = new SqlDataAdapter(objCommand);
        objDataAdapter.Fill(objDataSet, "reading");
        objConnection.Close();
        List colLatestUpdate = new List();

        foreach (DataRow rs in objDataSet.Tables[0].Rows)
        {
            LoginAuth objLU = new LoginAuth();
            objLU.Status = 1;
            colLatestUpdate.Add(objLU);          
        }

        if (objDataSet.Tables[0].Rows.Count == 0)
        {
            LoginAuth objLU = new LoginAuth();
            objLU.Status = 0;
            colLatestUpdate.Add(objLU);
        }
        XmlSerializer LatestUpdateserialize = new XmlSerializer(typeof(List));

        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        LatestUpdateserialize.Serialize(ms, colLatestUpdate);
        ms.Position = 0;
        List LatestUpdateElement = (List)LatestUpdateserialize.Deserialize(ms);
        return LatestUpdateElement;
    }



///Entity Class

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

///
/// Summary description for LatestUpdate
///

public class LoginAuth
{
    public LoginAuth()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    private int _Status = 0;
    private string _userid;
    private string _mobile;
   
    public int Status
    {
        get
        {
            return _Status;
        }
        set
        {
            _Status = value;
        }
    }
    public string UserID
    {
        get
        {
            return _userid;
        }
        set
        {
            _userid = value;
        }
    }
    public string Mobile
    {
        get
        {
            return _mobile;
        }
        set
        {
            _mobile = value;
        }
    } 
}



No comments: