In this article we will discuss about the basics of WCF. What Is WCF ? What is Contract?


In this article we will discuss about the basics of WCF. What Is WCF ? What is Contract? How can we create a service and then how to consime it. We will see all these things with the help of an example.

WCF(Windows Communication Foundation) is a Programming model with the help of which
we write services and can unify the technologies like COM+ , MSMQ , .Net remoting ,
Web servies etc.

WCF has 3 main components:

1. Address
2. Binding
3. Contract

Address: It is actually the URL which denoted the location of the service. i.e. where
the service is located. Aservice can have more than one address and each of which is unique.

Binding: It defines the way of communication of service. Service communicate with the help
of protocols like TCP, HTTP ,MSMQ etc.

Contract: It specifies the interface between client and the server. Interface contains
just attributes.

Communication takes to and from endpoints. Endpoints defines the location to which messages
are sent and received. These location contains the address, binding and contract.

There are 4 types of contracts

1. Service Contract: It is used to define the interface.
2. Operation Contract: It defines the method inside the interface.


[ServiceContract]
interface IHelloContract
{
[OperationContract]
string HelloMethod( );
}
class MyService : IHelloContract
{
public string HelloMethod( )
{
return "Hello World";
}
}

3. Data Contract: It mark the types like classes,structures that can participate in the
serialization.

[DataContract]
class Contact
{

}

4. Data Member: It mark the fields and the properties that we want to serialize.

[DataContract]
class Contact
{
[DataMember]
public string Name;
[DataMember]
public string Address;
}

Now we will see steps to create the WCF Service and then consuming it.
1. Create a new website and name it Employee.
2. Now we create a new WCF Service by Right clicking project -> add new item -> WCF Service . And
Name it EmployeService.


Creating WCF Service

Three files will be created EmployeeService.svc, IEmployeeService.cs, EmployeeService.cs

3. Now we add the connectionstring in the web.config file to connect to the database.

<connectionStrings>
<add name="Databaseconnstring" connectionString="Data Source=DELL-PC\SQLEXPRESS;InitialCatalog=Database;Integrated Security = true;" providerName="System.Data.SqlClient"/>
</connectionStrings>


4. Now we Open the IEmployeeService.cs file and write below code:

[DataContract]
publicclassEmployee
{
[DataMember]
publicint Id { get; set; }

[DataMember]
publicstringEmployeeName { get; set; }

}

5. Now we define the interface Employee class and create the method for getting the employee detail and saving the employee detail.

[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
EmployeeGetEmployee(intEmployeeId);

[OperationContract]
voidSaveEmployee(Employeeemployee);
}


6. Now in the EmployeeService.cs class we will add below code to connect to the databse for reading and adding record to the table:

privatestringcnnString =
ConfigurationManager.ConnectionStrings["Databaseconnstring"].ToString();

publicEmployeeGetEmployee(intEmployeeId)
{
StringBuildersql = newStringBuilder();
sql.Append("SELECT Id, EmployeeName from Employee where EmployeeId = @EmployeeId");
SqlConnectioncnn = newSqlConnection(cnnString);

SqlCommandcmd = newSqlCommand(sql.ToString(), cnn);
cmd.Parameters.Add("EmployeeId", SqlDbType.Int, 0).Value = EmployeeId;

SqlDataAdapteradp = newSqlDataAdapter(cmd);
DataSet ds = newDataSet();

adp.Fill(ds);

Employee e = newEmployee();
e.Id = EmployeeId;
e.EmployeeName = ds.Tables[0].Rows[0]["EmployeeName"].ToString();

return e;
}

publicvoidSaveEmployee(Employee employee)
{
StringBuildersql = newStringBuilder();
sql.Append("UPDATE Employee set EmployeeName = @EmployeeName WHERE Id = @EmployeeId");

SqlConnectioncnn = newSqlConnection(cnnString);
SqlCommandcmd = newSqlCommand(sql.ToString(), cnn);
cmd.Parameters.Add("EmployeeName", SqlDbType.NVarChar, 200).Value = employee.EmployeeName;
cmd.Parameters.Add("EmployeeId", SqlDbType.Int, 4).Value = employee.Id;

cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
}



Our service is created. Now we create the client to use that consume that service.

7. Now we create a new website inside the same solution and name it EmployeeClient. And set is Asstartupproject.
8. Now click the website created and select Add Service reference. Then a window will open we will click Discover services in solution and the windows will show the service like:

Adding Service Reference

9. Now in the .aspx page we will create controls to get and show the details of the employee. The desing will look like:

Design Page

10. Now on the button clicks event we will write the code to read the value from the database and updating the records:

protectedvoidbtnid_Click(object sender, EventArgs e)
{
intempId = int.Parse(txtempid.Text);

NewServices.EmployeeServiceClient n = newNewServices.EmployeeServiceClient();
NewServices.Employee employee = newNewServices.Employee();
employee = n.GetEmployee(empId);
txtid.Text = employee.Id.ToString();
txtname.Text = employee.EmployeeName;

}
protectedvoidbtnsave_Click(object sender, EventArgs e)
{
NewServices.Employee employee = newNewServices.Employee();
employee.Id = int.Parse(txtid.Text);
employee.EmployeeName = txtname.Text;

NewServices.EmployeeServiceClient n = newNewServices.EmployeeServiceClient();
n.SaveEmployee(employee);

}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: