About Me

My photo
I am a senior MEAN/MERN stack consultant for United Nations. With 7 years of experience.

Monday, January 20, 2020

using SOAP service in c#



client app

consuming soap service , console application 


using System;
using System.IO;
using System.Net;
using System.Xml;

namespace UsingSOAPRequest
{
    class Program
    {
        static void Main(string[] args)
        {
            //creating object of program class to access methods 
            Program obj = new Program();
            Console.WriteLine("Please Enter Input values..");
            //Reading input values from console 
            int a = Convert.ToInt32(Console.ReadLine());
            int b = Convert.ToInt32(Console.ReadLine());
            //Calling InvokeService method 
            obj.InvokeService(a, b);
        }
        public void InvokeService(int a, int b)
        {
            //Calling CreateSOAPWebRequest method 
            HttpWebRequest request = CreateSOAPWebRequest();

            XmlDocument SOAPReqBody = new XmlDocument();
            //SOAP Body Request 
            SOAPReqBody.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?> 
            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-   instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> 
             <soap:Body> 
                <Addition xmlns=""http://tempuri.org/""> 
                  <a>" + a + @"</a> 
                  <b>" + b + @"</b> 
                </Addition> 
              </soap:Body> 
            </soap:Envelope>");


            using (Stream stream = request.GetRequestStream())
            {
                SOAPReqBody.Save(stream);
            }
            //Geting response from request 
            using (WebResponse Serviceres = request.GetResponse())
            {
                using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))
                {
                    //reading stream 
                    var ServiceResult = rd.ReadToEnd();
                    //writting stream result on console 
                    Console.WriteLine(ServiceResult);
                    Console.ReadLine();
                }
            }
        }

        public HttpWebRequest CreateSOAPWebRequest()
        {
            //Making Web Request 
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost:52168/Service.asmx");
            //SOAPAction 
            Req.Headers.Add(@"SOAPAction:http://tempuri.org/subtract");
            //Content_type 
            Req.ContentType = "text/xml;charset=\"utf-8\"";
            Req.Accept = "text/xml";
            //HTTP method 
            Req.Method = "POST";
            //return HttpWebRequest 
            return Req;
        }
    }
}




server side 
dot net 3.5  web site -> asp.net web service 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[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 Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

    [WebMethod]
    
    public string sum(int a, int b)
    {
        return (a + b).ToString();
    }
    [WebMethod]
    public int subtract(int a, int b)
    {
        return a - b;
    }
    [WebMethod]
    public int multiply(int a, int b)
    {
        return a * b;
    }
    [WebMethod]
    public int divide(int a, int b)
    {
        return a / b;
    }

}

ASP.net forms - connect to a ms sql db and use CRUD operations.


Create a table called customer to store customer information.


USE [cypad]
GO

/****** Object:  Table [dbo].[customer]    Script Date: 20-Jan-20 3:03:53 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[customer](
[customerid] [numeric](18, 0) NULL,
[name] [nvarchar](50) NULL,
[country] [nvarchar](50) NULL
) ON [PRIMARY]
GO


insert few records to it. 

USE [cypad]
GO

INSERT INTO [dbo].[customer]
           ([customerid]
           ,[name]
           ,[country])
     VALUES
           (<customerid, numeric(18,0),>
           ,<name, nvarchar(50),>
           ,<country, nvarchar(50),>)
GO


add a asp.net web form 


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace cypad
{
    public partial class customerList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!this.IsPostBack)
                {
                    this.loadCustomerList();
                }
            }catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        private void loadCustomerList()
        {
            try
            {
                string consting = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
                string query = "SELECT * FROM customer";
                using (SqlConnection con = new SqlConnection(consting))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            gvCustomerList.DataSource = dt;
                            gvCustomerList.DataBind();
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
        }
    }
}


Conections string should be stored in web.config file 

  <connectionStrings>
    <add name ="MyConnection"
    connectionString ="Data Source=DENISP\SQLEXPRESS;Initial Catalog=cypad;Integrated Security=true"/>
  </connectionStrings>


add the newly created form to site master.  


use the page notation to add the created form to the master page 

<%@ Page Title="Customer List" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" 
    CodeBehind="customerList.aspx.cs" Inherits="cypad.customerList" %>


<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    <asp:GridView ID="gvCustomerList" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="customerid" HeaderText="Customer ID" />
            <asp:BoundField DataField="name" HeaderText="Customer Name" />
            <asp:BoundField DataField="country" HeaderText="Country" />
        </Columns>
    </asp:GridView>

</asp:Content>





        private void loadCustomerList()
        {
            try
            {
                DBconnections DBconnet = new DBconnections();
                string consting = DBconnet.getConnectionString().consting;
                string query = string.Concat( "insert into customer (name,country) values('{0}',{1})",txt;
                using (SqlConnection con = new SqlConnection(consting))
                {
                    SqlDataAdapter adapter = new SqlDataAdapter();
                    sql = 
                        connection.Open();
                        adapter.InsertCommand = new SqlCommand(sql, connection);
                        adapter.InsertCommand.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
            catch
            {
                throw;
            }
        }