In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

ASP.NET Web Service receiving XML as input parameter using POST method


What is a Web Service?

A Web service is a method of communication between two electronic devices over the web.
The W3C defines a "Web service" as "a software system designed to support interoperable machine-to-machine interaction over a network". It has an interface described in a machine-processable format (specifically Web Services Description Language, known by the acronym WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards."

What is XML?

  • XML stands for Extensible Markup Language
  • XML is a markup language much like HTML
  • XML was designed to carry data, not to display data
  • XML tags are not predefined. You must define your own tags
  • XML is designed to be self-descriptive
  • XML is a W3C Recommendation

 

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.
HTTP functions as a request-response protocol in the client-server computing model. In HTTP, a web browser, for example, acts as a client, while an application running on a computer hosting a web site functions as a server. The client submits an HTTP request message to the server. The server, which stores content, or provides resources, such as HTML files, or performs other functions on behalf of the client, returns a response message to the client. A response contains completion status information about the request and may contain any content requested by the client in its message body.
A web browser (or client) is often referred to as a user agent (UA). Other user agents can include the indexing software used by search providers, known as web crawlers, or variations of the web browser such as voice browsers, which present an interactive voice user interface.
The HTTP protocol is designed to permit intermediate network elements to improve or enable communications between clients and servers. High-traffic websites often benefit from web cache servers that deliver content on behalf of the original, so-called origin server, to improve response time. HTTP proxy servers at network boundaries facilitate communication when clients without a globally routable address are located in private networks by relaying the requests and responses between clients and servers.
HTTP is an Application Layer protocol designed within the framework of the Internet Protocol Suite. The protocol definitions presume a reliable Transport Layer protocol for host-to-host data transfer.The Transmission Control Protocol (TCP) is the dominant protocol in use for this purpose. However, HTTP has found application even with unreliable protocols, such as the User Datagram Protocol(UDP) in methods such as the Simple Service Discovery Protocol (SSDP).
HTTP Resources are identified and located on the network by Uniform Resource Identifiers (URIs)—or, more specifically, Uniform Resource Locators (URLs)—using the http or https URI schemes. URIs and the Hypertext Markup Language (HTML), form a system of inter-linked resources, called hypertext documents, on the Internet, that led to the establishment of the World Wide Web in 1990 by English computer scientist and innovator Tim Berners-Lee.
The original version of HTTP (HTTP/1.0) was revised in HTTP/1.1. HTTP/1.0 uses a separate connection to the same server for every request-response transaction, while HTTP/1.1 can reuse a connection multiple times, to download, for instance, images for a just delivered page. Hence HTTP/1.1 communications experience less latency as the establishment of TCP connections presents considerable overhead.

 

What are POST and GET methods?

GET
The Get is one the simplest Http method. Its main job is to ask the server for the resource. If the resource is  available then then it will given back to the user on your browser. That resource may be a HTML page, a sound file, a picture file (JPEG) etc. We can say that get method is for getting something from the server. It doesn't mean that you can't send parameters to the server. But the total amount of characters in a GET is really limited. In get method the data we send get appended to the URL so whatever you will send will be seen by other user so can say that it is not even secure.
POST
The Post method is more powerful request. By using Post we can request as well as send some data to the server. We use post method when we have to send a big chunk of data to the server, like when we have to send a long enquiry form then we can send it by using the post method. 
 

Creating a ASP.NET WEB SERVICE

Open Visual Studio (go to run-> type devenv.exe and press enter).
Select new empty website.
Set the location to HTTP, give the address as http://localhost/SampleWS (if your IIS running on port 80)
Add new item to website select web service give name MyService.asmx, it will open code window.
Delete the Default HelloWorld() method and create a new webmethod PatientEncounter(string xmlString) method set return type to XmlDocument, this method duty is to take the xml string given by any application and parse the xml document, based on the xml this method has to insert or update or query the database table to the calling application.
Example Code:
[WebMethod]
public XmlDocument PatientEncounter(string xml)
    {
       
    }
The Acceptable XML format for this method is
           //create encounter Query
            <Request action='insert'><requestObject Id='12345' reason='Testing successful'  userId='TEST12' startTime='10/10/2011' comments='' /> </Request>

            //update encounter Query
            <Request action='update'><requestObject Id='12345' encounterId='14001' reason='Testing successful'  userId='TEST12' startTime='10/10/2011' comments='' /> </Request>

            //Query encounter query
            <Request action='query'><requestObject Id='12345' /> </Request>
If we don’t get this xml format we have to give an error message
Before doing anything we need to set our service to accept XML input, by default we can not post the xml to the webserver. For this we have to add some tags in web.config file
Under system.web tag add two new tags like
<system.web>
<httpRuntime requestValidationMode="2.0"/>
<pages validateRequest="false"/>
</system.web>
This step is very important because with out this you cannot send xml to web service. By adding this our service is ready to accept the xml given by any application.
Now add the fallowing code to your PatientEncounter method
        try
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(xml + Environment.NewLine);
            switch (xdoc["Request"].Attributes["action"].Value)
            {
                case "insert": return createEncounter(xdoc);

                case "query": return queryEncounter(xdoc);
                case "update": return updateEncounter(xdoc);
                default: throw new Exception("invalid action value");
            }
           
        }
        catch(Exception e)
        {
            XmlDocument xdoc = new XmlDocument();
           
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version='1.0' encoding='utf-8' ?>");
            sb.Append("<DocumentElement>");
            sb.Append("<Response><Error message='error.error' ");
            sb.AppendFormat("value='{0}' />",e.Message);
            sb.Append("</Response>");
            sb.Append("</DocumentElement>");

            xdoc.LoadXml(sb.ToString());
            return xdoc;
        }

       
Now write 3 methods which are used for insert,update,query the data from database table and return the XmlDocument
Add some helper methods
private XmlDocument createEncounter(XmlDocument xdoc)
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
       
        cmd = new SqlCommand();
        cmd.CommandText = "select count(*) from Encounter";
        cmd.Connection = con;

        if (!(con.State == ConnectionState.Open))
            con.Open();

        int encounterId = 1400 + (int)cmd.ExecuteScalar() + 1;
        cmd.Dispose();
        con.Close();
       
        string partyId = xdoc["Request"].FirstChild.Attributes["Id"].Value;
        string userId = xdoc["Request"].FirstChild.Attributes["userId"].Value;
        string createdTime = DateTime.Now.ToString();
        string startTime = Convert.ToDateTime(xdoc["Request"].FirstChild.Attributes["startTime"].Value).ToString();
        string reason = xdoc["Request"].FirstChild.Attributes["reason"].Value;
        string comments = xdoc["Request"].FirstChild.Attributes["comments"].Value;
       
        cmd = new SqlCommand();
        cmd.Parameters.Add(new SqlParameter("encounterId",encounterId.ToString()));
        cmd.Parameters.Add(new SqlParameter("partyId", partyId));
        cmd.Parameters.Add(new SqlParameter("userId", userId));
        cmd.Parameters.Add(new SqlParameter("reason", reason));
        cmd.Parameters.Add(new SqlParameter("createdTime", createdTime));
        cmd.Parameters.Add(new SqlParameter("startTime", startTime));
        cmd.Parameters.Add(new SqlParameter("comments", comments));

        cmd.CommandText = "insert into Encounter values(@encounterId, @partyId, @userId, @createdTime, @startTime, @reason, @comments)";
        cmd.Connection = con;
        if (!(con.State == ConnectionState.Open))
            con.Open();
        int i = cmd.ExecuteNonQuery();
        cmd.Dispose();
        con.Close();

        if (i == 1)
        {
            return DataTableToXML(getEncounterDetails(encounterId.ToString()));
        }
        else
            throw new Exception("Some error occured");
       
    }

    //Query the data table
    private XmlDocument queryEncounter(XmlDocument xdoc)
    {
        string partyId = xdoc["Request"].FirstChild.Attributes["Id"].Value;
        return DataTableToXML(queryEncounterDetails(partyId));
    }

     //Update the encounter      private XmlDocument updateEncounter(XmlDocument xdoc)
      {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

        string encounterId = xdoc["Request"].FirstChild.Attributes["encounterId"].Value;
        string partyId = xdoc["Request"].FirstChild.Attributes["Id"].Value;
        string userId = xdoc["Request"].FirstChild.Attributes["userId"].Value;
        string startTime = Convert.ToDateTime(xdoc["Request"].FirstChild.Attributes["startTime"].Value).ToString();
        string reason = xdoc["Request"].FirstChild.Attributes["reason"].Value;
        string comments = xdoc["Request"].FirstChild.Attributes["comments"].Value;

        cmd = new SqlCommand();
        cmd.Parameters.Add(new SqlParameter("encounterId", encounterId.ToString()));
        cmd.Parameters.Add(new SqlParameter("userId", userId));
        cmd.Parameters.Add(new SqlParameter("reason", reason));
        cmd.Parameters.Add(new SqlParameter("startTime", startTime));
        cmd.Parameters.Add(new SqlParameter("comments", comments));
       
        cmd.Connection = con;
        cmd.CommandText = "UPDATE Encounter SET [userId] = @userId, [startTime] = @startTime, [reason] = @reason, [comments] = @comments WHERE [encounterId] = @encounterId";
      
        if (!(con.State == ConnectionState.Open))
            con.Open();

        int i = cmd.ExecuteNonQuery();
        cmd.Dispose();
        con.Close();

        if (i == 1)
        {
            return DataTableToXML(getEncounterDetails(encounterId.ToString()));
        }
        else
            throw new Exception("No encounter with given details");

    }
//Helper Methods
//This method is used to generate XmlDocument from a DataTable
private XmlDocument DataTableToXML(DataTable dt)
    {
        XmlDocument xml = new XmlDocument();
        StringBuilder sb = new StringBuilder();

        sb.Append("<?xml version='1.0' encoding='utf-8' ?>");
        sb.Append("<DocumentElement>");

        foreach (DataRow dr in dt.Rows)
        {
            sb.Append("<" + dt.TableName + ">");

            foreach (DataColumn dc in dt.Columns)
                sb.Append("<" + dc.ColumnName + ">" +
                        dr[dc].ToString() +
                     "</" + dc.ColumnName + ">");

            sb.Append("</" + dt.TableName + ">");
        }

        sb.Append("</DocumentElement>");
        xml.LoadXml(sb.ToString());

        return xml;
    }

    private DataTable getEncounterDetails(string encounterId)
    {
       
        string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        string commandText = string.Format("select * from Encounter where encounterId = '{0}'",encounterId);
       
        SqlDataAdapter da = new SqlDataAdapter(commandText,connectionString);

        DataTable dt = new DataTable("EncounterDetails");
        da.Fill(dt);

        return dt;
    }
    private DataTable queryEncounterDetails(string partyId)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        string commandText = string.Format("select * from Encounter");

        SqlDataAdapter da = new SqlDataAdapter(commandText, connectionString);
        DataTable dt = new DataTable("EncounterDetails");
        da.Fill(dt);

        return dt;
    }
Download the full source code from fallowing link
Password: Raghuveer


Link for ServerAPP
Click Here
Link for ClientAPP
Click Here

Thank you………………