SOAP stands for Simple Object Access Protocol. We use SOAP Request to access data of the third party’s api. In API’s data transfer through XML. XML stands for eXensible Markup Language. It is the fastest technique i.e. used for data transfer. It is an open source and browser independent markup language. In this article, we will discuss how we can get data by sending SOAP Request in ASP.Net First of all to get data through XML file by sending SOAP Request, you have to create the website and web service in that and from that web service you simple fetch data from database return that as an XML file.
- Create a new Website named SoapService.
- Now add Web Service named SoapService.asmx [sc name=”responsiveadsensebanner” ]
- Write the following connection string in Web Config file.
- Write the follwing Source Code in Code File named SoapService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Xml.Serialization; using System.Xml; using System.IO; using System.Net; using System.Diagnostics; /// <summary> /// Summary description for SoapService /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class SoapService : System.Web.Services.WebService { private readonly SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn1"].ConnectionString); SqlDataAdapter adap; DataSet ds; StreamWriter xmlDoc; [WebMethod] public String GetAllInvoices() { adap = new SqlDataAdapter("usp_GetAllInvoice", _con); adap.SelectCommand.CommandType = CommandType.StoredProcedure; ds = new DataSet(); adap.Fill(ds, "InvoiceList"); var _sWUnit = new StringWriter(); ds.Tables[0].WriteXml(_sWUnit); return _sWUnit.ToString(); } }
- Execute the Web Service by pressing F5 key and click on the link as shown in beloww screen.
- Click on Invoke button.
- You will get the following output i.e. an XML file.
- Create a new Website named SoapWebsite
- Right click on website name in solution explorer, then choose Add Service Refrence option.
- Click on Advanced option.
- Click on Add Web Reference button.
- Following dialogue box will display
- Copy the URL of Web Serivce of SoapService website which has been made by you firstly.
- After copying the URL, paste in the textbox of URL as shown below and then click on button
- Click on Add Reference Button
- See solution explorer, references will added to your website.
- Write following connection string in web config file.
<?xml version="1.0"?><configuration><appSettings><add key="localhost.SoapService" value="http://localhost:11167/SoapService/SoapService.asmx"/></appSettings> <system.web> <compilation debug="true" targetFramework="4.5"/> <httpRuntime targetFramework="4.5"/> </system.web> </configuration>
- Add a class file named SoapDataMembers and write the following code to add some data members.
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace SoapDataMembers { public class Invoice { public int InvoiceID{get;set;} public string InvoiceNo { get; set; } public string InvoiceDate { get; set; } public string InvoiceAmt { get; set; } public string CustName { get; set; } public string CustContact { get; set; } public string CustAddress { get; set; } public string CustEmail { get; set; } } }
- Write the following code in WebService.cs file
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Xml.Serialization; using System.Xml; using System.IO; using System.Net; using System.Diagnostics; using System.Web.Script.Services; using SoapDataMembers; using System.Collections; using System.Web.Script.Serialization; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { private DataSet _dsTempDataSet; private Invoice _objInvoice; private int _intFlag, _intTemp; private List<Invoice> _getallinvoice = new List<Invoice>(); [WebMethod(Description = "Method of called web service")] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public List<Invoice> displayInvoiceList() { localhost.SoapService obj = new localhost.SoapService(); _dsTempDataSet = new DataSet(); _dsTempDataSet.ReadXml(new XmlTextReader(new StringReader(obj.GetAllInvoices()))); if (_dsTempDataSet != null && _dsTempDataSet.Tables.Count > 0) { for (_intTemp = 0; _intTemp < _dsTempDataSet.Tables[0].Rows.Count; _intTemp++) { _objInvoice = new Invoice { InvoiceID = Convert.ToInt32(_dsTempDataSet.Tables[0].Rows[_intTemp]["iInvoiceID"]), InvoiceNo = Convert.ToString(_dsTempDataSet.Tables[0].Rows[_intTemp]["sInvoiceNumber"]), InvoiceDate = Convert.ToString(_dsTempDataSet.Tables[0].Rows[_intTemp]["sInvoiceDate"]), InvoiceAmt = Convert.ToString(_dsTempDataSet.Tables[0].Rows[_intTemp]["sAmount"]), CustName = Convert.ToString(_dsTempDataSet.Tables[0].Rows[_intTemp]["sName"]), CustEmail = Convert.ToString(_dsTempDataSet.Tables[0].Rows[_intTemp]["sContact"]), CustContact = Convert.ToString(_dsTempDataSet.Tables[0].Rows[_intTemp]["sEmail"]), CustAddress = Convert.ToString(_dsTempDataSet.Tables[0].Rows[_intTemp]["sAddress"]) }; _getallinvoice.Add(_objInvoice); } } return _getallinvoice; } }
- Write the following HTML in InvoiceList.aspx file
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InvoiceList.aspx.cs" Inherits="InvoiceList" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title></title> http://J-Scripts/jquery-1.10.2.js http://J-Scripts/jquery-ui-1.10.4.custom.js http://J-Scripts/jquery-ui-1.10.4.custom.min.js http://Invoice.js </head> <body style="background-color:#E4E4E4;"> <input type="hidden" id="hdnService" runat="server" /> </body> </html>
- Write the following code in InvoiceList.aspx.cs file
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI; using System.Web.UI.WebControls; public partial class InvoiceList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { hdnService.Value = "WebService.asmx/displayInvoiceList"; } }
- Add javascrpit file,write the following jQuery code in Invoice.js file and then add it in HTML
$(document).ready(function () {var tempHtml = "";$.ajax({type: "POST",url: $("#hdnService").val(), contentType: "application/json; charset=utf-8", dataType: "json", data: "{}", success: SuccessOccur, error: ErrorOccur }); function SuccessOccur(response, status, req) { if (status == "success" && response.d.length > 0) { var data = response.d; tempHtml += "<table style='width:100%;margin-top:15px;' ><tr><th colspan='6' style='background-color:#00FFFF;text-color:#AB452D;font-size:30px;text-align:left;'>List of Invoices :- </th></tr>"; tempHtml += "<tr>"; tempHtml += "<th style='font-size:15px;background-color:#AB452D;color:#ffffff;padding:5px 5px 5px 5px;'>Date</th>"; tempHtml += "<th style='font-size:15px;background-color:#AB452D;color:#ffffff;padding:5px 5px 5px 5px;'>Invoice No</th>"; tempHtml += "<th style='font-size:15px;background-color:#AB452D;color:#ffffff;padding:5px 5px 5px 5px;'>Customer Name</th>"; tempHtml += "<th style='font-size:15px;background-color:#AB452D;color:#ffffff;padding:5px 5px 5px 5px;'>Contact No</th>"; tempHtml += "<th style='font-size:15px;background-color:#AB452D;color:#ffffff;padding:5px 5px 5px 5px;'>Email Id</th>"; tempHtml += "<th style='font-size:15px;background-color:#AB452D;color:#ffffff;padding:5px 5px 5px 5px;'>Amount</th>"; tempHtml += "</tr>"; $.each(response.d, function (key, item) { tempHtml += "<tr>"; tempHtml += "<td style='font-size:15px;padding:5px 5px 5px 5px;text-align:center;background-color:#FDF8DF;'>" + item.InvoiceDate + "</td>"; tempHtml += "<td style='font-size:15px;padding:5px 5px 5px 5px;text-align:center;background-color:#FDF8DF;'>" + item.InvoiceNo + "</td>"; tempHtml += "<td style='font-size:15px;padding:5px 5px 5px 5px;background-color:#FDF8DF;'>" + item.CustName + "</td>"; tempHtml += "<td style='font-size:15px;padding:5px 5px 5px 5px;background-color:#FDF8DF;'>" + item.CustContact + "</td>"; tempHtml += "<td style='font-size:15px;padding:5px 5px 5px 5px;background-color:#FDF8DF;'>" + item.CustEmail + "</td>"; tempHtml += "<td style='font-size:15px;padding:5px 5px 5px 5px;text-align:right;background-color:#FDF8DF;'>Rs." + parseFloat(item.InvoiceAmt).toFixed(2) + "</td>"; tempHtml += "</tr>"; }); tempHtml += "</table>"; } else { tempHtml += "<table style='width:100%;margin-top:15px;' ><tr><th colspan='6' style='background-color:#00FFFF;color:#FF0000;font-size:30px;text-align:left;'>Sorry, No Record Found !!</th></tr></table>"; } $("#showXML").html(tempHtml); } function ErrorOccur(data, status, req) { tempHtml = ""; { tempHtml += "<table style='width:100%;margin-top:15px;' ><tr><th colspan='6' style='background-color:#00FFFF;color:#FF0000;font-size:30px;text-align:left;'>Oops Error Occurs!!</th></tr></table>"; } $("#showXML").html(tempHtml); } });
- Now Press F5, after adding javacript files, and writing source codes you will get following output.
Note:- Please keep in mind that both the websites should be in running state if you are working on localhost server.