Friday, January 18, 2013

Create basic web-service (SOAP) using C#.net.

This tutorial explains how we can create basic SOAP Web-Services using  Visual Studio 2010 or 2012.
In Visual Studio 2008, we can create service directly but in VS10 and VS12 that feature was removed.

How to create SOAP Web-Service in VS10 or VS12.

First create new project and select "ASP.NET Web Application" and I'm naming "SampleWebApplication_for_Web-service Demo" to my sample service.

Now Web-Application created like below screen......

Now add web-service to your web-application....

RightClick on Project-> Add->New Item.

Then select Web Service in list. Click Add.


Service added successfully to your application and you can create your own methods now.

And execute it..




SAMPLE METHOD:

First, Create the connection string for your service.

 string Con = ConfigurationManager.ConnectionStrings["SampleWEBConnection"].ToString();
        string sP_Name = string.Empty;
        SqlConnection sqlCon = null;
        SqlCommand sqlCmd; 

Make sure that the same connection string 'name' should be appear in web.config file like below

<add name="SampleWEBConnection" connectionString="Data Source=sample.db.10xxxxx3.hostedresource.com; Initial Catalog=DatabaseName; User ID=DBName; Password=DbPasswd"/>

And you have to add one more thing in web.config file. Web-service won't work without this step. It helps to get and post the data from client to server and vice-versa.
Add it in <system.web/>

<webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>

Here I have written one sample Web-Method for Login.
WebMethod Attribute is used to expose the method publicly or enabling method to use. It has some properties like
-Description
-CacheDuration
-MessageName
-TransactionOption
-EnableSession
-BufferResponse

 [WebMethod (Description=" Describe your method name")] 
        public bool SampleLoginMethod(string _mailId, string _passWord)
        {
            DataSet DsCheckLogin = new DataSet();
            sP_Name = "Proc_CheckLogin";  //Your Stored Procedure Name
            SqlConnection sqlCon = new SqlConnection(Con); //setting DB connection here.
            SqlCommand sqlCmd = new SqlCommand(sP_Name, sqlCon);
            sqlCmd.CommandType = CommandType.StoredProcedure;
           //Passing Required parameters.
           sqlCmd.Parameters.Add("@EmailId", _mailId);
            sqlCmd.Parameters.Add("@password", _passWord);
            
            SqlDataAdapter sqlda = new SqlDataAdapter(sqlCmd);
            sqlda.Fill(DsCheckLogin);
         //Getting Back result from your DB.
            if (DsCheckLogin.Tables[0].Rows.Count > 0)
                return true;
            else
                return false;

        }
Execute it. Now you will get 'SampleLoginMethod' and click on it.

Click on 'Invoke' button.


Finally, you will get your result here.



No comments:

Post a Comment