How to Create a basic web service


Shikha Gupta
SharePoint Developer
Published On :   20 Apr 2016
Visit Count
Today :  1    Total :   2347



It is the service provided over the web from one application to the other and helps one application to read and consume data from the other application. This article will help you to create a basic web service which will display the data from the data and save the data in the database.

1. Create a database and use it for that run the following commands.

create database DbEmployee

use DbEmployee

2. Create a table.

create table tblEmployee

(

EmployeeId int identity primary key,

Name varchar(50),

Salary int

)

3. Insert data into the table.

insert into tblEmployee values('Shikha',1000)

insert into tblEmployee values('Tarun',2000)

insert into tblEmployee values ('Sathish',3000)

4. Create a proc which retrives data based on the id

Create Proc getEmployeeByID

@Id int

as

begin

select EmployeeId,Name,Salary

from tblEmployee

where EmployeeId=@Id

end

5. If you want to execute the proc you can run

exec getEmployeeByID 1

6. Create a Proc which saves the employee data into EmployeeTable

Create proc SaveEmployee

@Name varchar(50),

@Sal varchar(50)

as

begin

insert tblEmployee(Name,Salary)

values(@Name,@Sal)

end

7. If you want to execute the proc you can run this will add a new row to your table.

exec SaveEmployee 4, 'abc', 10000

8. Open a visual studio and take a Asp.Net Web Applications.

image

9. Select the empty template.

image

10. Open the web.config file and paste the following code after closing tag of system.web for establish the connection to the dataset created above.

<connectionStrings>

<add name ="EmpDBCS" connectionString="data source = GBRDCSPSDEV05; Initial Catalog=DbEmployee;Integrated Security =True" providerName="System.Data.SqlClient" />

</connectionStrings>

11. Add a class name Employee

image

12. Copy and paste the following code in Employee class.

public int EmployeeId { get; set; }

public string Name { get; set; }

public int Salary { get; set; }

13. Add a Webservice which would be available under web in the installed templates and name it as EmployeeService.asmx.

image

The following could would be generated after adding the webservice.

Explanation: - This webservice is nothing but a class and this class is decorated with WebService attribute which tells that this class is a web service and the namespace attribute under is differentiate one web service from other in the real world. The methods under this are decorated with webmethod in order to expose the method to the client and if we don’t want to expose it to client then we don’t have to decorate it with web method attribute.

image

14. Include the following classes.

 

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

15. Delete the hello world web method and we will create two web methods one getEmployeeByID method and other Save Employee and the code for creating it is given below:

[WebMethod]

public Employee GetEmployeeById(int Id)

{

string cs = ConfigurationManager.ConnectionStrings["EmpCS"].ConnectionString;

using (SqlConnection con = new SqlConnection(cs))

{

SqlCommand cmd = new SqlCommand("getEmployeeByID", con);

cmd.CommandType = CommandType.StoredProcedure;

SqlParameter parameter = new SqlParameter("@Id", Id);

cmd.Parameters.Add(parameter);

Employee emp = new Employee();

cmd.Connection = con;

con.Open();

SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())

{

emp.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);

emp.Name = reader["Name"].ToString();

emp.Salary = Convert.ToInt32(reader["Salary"]);

}

return emp;

}

}

[WebMethod]

public void SaveEmployee(Employee emp)

{

using (SqlConnection con = new SqlConnection(cs))

{

SqlCommand cmd = new SqlCommand("SaveEmployee", con);

cmd.CommandType = CommandType.StoredProcedure;

SqlParameter ParameterName = new SqlParameter

{

ParameterName = "@Name",

Value = emp.Name

};

cmd.Parameters.Add(ParameterName);

SqlParameter ParameterSal = new SqlParameter

{

ParameterName="@Sal",

Value=emp.Salary

};

cmd.Parameters.Add(ParameterSal);

con.Open();

cmd.ExecuteNonQuery();

}

}

16. Open the EmployeeService.asmx. in browser and you would see your GetEmployeeById method, Save Employee method and service description link, click on service description link and it will take you to the wsdl document (http://localhost:54302/EmployeeService.asmx?WSDL) which is used by the client to generate the proxy class and consume this web service. Make a note of this wsdl url as later it will be used while creating the client application

image

17. Now go back to the previous screen and click on GetEmployeeById method.

image

Once you click on GetEmployeeById method you could pass the id and click on invoke

image

This will give you the following result:

image

Now the web service is created and we can invoke the method as well and wsdl document is also generated so we have to create a client application which will consume this web service.

1. Create another project in this solution and take an empty .net web application

image

image

2. Right click on the references of client application and add a service reference in the address specify the wsdl url (http://localhost:54302/EmployeeService.asmx) and click go and you would see your web service and give a proper namespace name as well. This should generate the proxy class.

image

3. Add a Web Form and name it EmployyeForm.aspx

4. Now we have to add the controls so copy and paste the following code for that or you can drag and drop the controls as well.

<table class="auto-style1">

<tr>

<td class="auto-style2">Name</td>

<td class="auto-style3">

<asp:TextBox ID="NameTxtBox" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td class="auto-style2">Salary</td>

<td class="auto-style3">

<asp:TextBox ID="SalTxtBox" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td colspan="2">

asp:Button ID="SubmitBtn" runat="server" Text="Save Employee" OnClick="SubmitBtn_Click" />

</td>

</tr>

<tr>

<td class="auto-style3">

<asp:Button ID="GetBtn" runat="server" Text="Get Employee By ID" OnClick="GetBtn_Click" />

</td>

<td class="auto-style3">

ID: <asp:TextBox ID="IDTxtBox" runat="server"></asp:TextBox>

&nbsp;</td>

</tr>

</table>

<p>

<asp:Label ID="MsgLabel" runat="server" Font-Bold="True" Font-Size="XX-Large"></asp:Label>

</p>

After copying the code or if you want to drag and drop the controls the screen should look like below:

image

5. Now copy the below code in SaveEmployee button click event which will take the values from the control and save it in the database.

protected void SubmitBtn_Click(object sender, EventArgs e)

{

EmployeeWebService.EmployeeServiceSoapClient client = new EmployeeWebService.EmployeeServiceSoapClient();

EmployeeWebService.Employee emp = new EmployeeWebService.Employee();

emp.Name = NameTxtBox.Text;

emp.Salary = Convert.ToInt32(SalTxtBox.Text);

client.SaveEmployee(emp);

MsgLabel.Text = "Employee Saved";

}

6. Copy the below code in GetEmployeeById button click event which will take the id and depending on that it will display the value.

protected void GetBtn_Click(object sender, EventArgs e)

{

EmployeeWebService.EmployeeServiceSoapClient client = new EmployeeWebService.EmployeeServiceSoapClient();

EmployeeWebService.Employee emp = client.GetEmployeeById(Convert.ToInt32(IDTxtBox.Text));

NameTxtBox.Text = emp.Name;

SalTxtBox.Text = emp.Salary.ToString();

MsgLabel.Text = "Employee Retreived";

}

Now view the Employee WebFrom in browser and test both of the functionality.

 

Save Employee:

image

Get Employee:

image

This is how we create a basic web service and make the asp .net client consume it.

But there are lots of limitations with Web Service like if the same service is needed by two different clients but the protocol and message format used are different. Then we will have to create the same service in two different ways as the protocol and message format used are different. So to overcome this we have WCF. The next article will be on WCF.

Categories