WCF Basics: Part 3


Introduction:

In my previous two articles, you read some basic of WCF and a simple program to develop and consume the WCF service. In this article we will develop a WCF service using the template provided by Visual Studio 2010 and consuming the service by a WPF client. So let's start step-by-step.

Step 1: Create a Database

In this example we have to create the database, so let's create one database with a  table called Jobs with following scheme.

JobId Int Primary Key Identity,
[Desc]Varchar(100),
MinVal int,
MaxVal int

As stated above, our database with jobs table is ready; now it's time to start the service application.

Step 2: Create WCF Service Application

Open Visual Studio -> New -> WCF Service Application which will create an Iservice interface,Service.svc and Service.cs Classes but we don't want to use the default service so just delete it. Now Add -> New Item -> WCF Service Provide the name as JobService it will create IjobService.cs,JobService.cs and JobService.svc for you.

Step 3: Defining Interface

As per my last article on WCF the standerd way to work with WCF is define the interface first and then implement it in the classes. So after adding new service we have IjobService interface lest's defin it like bellow.

[ServiceContract]
    public interface IJobService
    {
        [OperationContract]
        void DoWork();
        [OperationContract]
        ClsJobs ReturnJobs(int _jobid);
        [OperationContract]
        string AddToJob(string _desc, int _min, int _max);
        [OperationContract]
        string UpdateJob(int _jobid,string _desc,int _min,int _max);
        [OperationContract]
        DataSet ReturnAllJobs();
    }

In the above code you can see the interface defined with complex types also called ClsJobs so just go to solution explorer and add new class called ClsJobs where we are storing some values and returning to client on request.

Step 4: Prepare Complex type

In the above step we have added the new class called ClsJobs now it's time to first implement this class so just create the simple properties for our database field in clsjobs like bellow.

[DataContract]
   public class ClsJobs
    {
        [DataMember]
        public int JobId { get; set; }
        [DataMember]
        public string Desc { get; set; }
        [DataMember]
        public int MinVal { get; set; }
        [DataMember]
        public int MaxVal { get; set; }
    }

Now our complex type is also ready. Now it's time to prepare our JobService.cs class which will implement the inteface IjobService i.e. Contract for our service.

Step 5:

Now we will implement the JobService.cs class which is implementation of our service contract IjobService. This class normally contain database operation in our case.

public ClsJobs ReturnJobs(int _jobid)
        {
            ClsJobs obj = new ClsJobs();
            SqlConnection cn = new SqlConnection("Data Source=Server2;User Id=sa;Password=123;DataBase=PUBS1");
            cn.Open();
            string _sql = "Select * From Jobs Where JobId=" + _jobid;
            SqlCommand cmd = new SqlCommand(_sql, cn);
            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                obj.Desc = dr["Desc"].ToString();
                obj.MinVal = int.Parse(dr["MinVal"].ToString());
                obj.MaxVal = int.Parse(dr["MaxVal"].ToString());
                obj.JobId = int.Parse(dr["JobId"].ToString());
            }
            else
                obj.JobId = -1;
            return obj;
        }

        public DataSet ReturnAllJobs()
        {
            SqlConnection cn = new SqlConnection("Data Source=Server2;User Id=sa;Password=123;DataBase=PUBS1");
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter("Select * From Jobs", cn);
            da.Fill(ds);
            return ds;
        }

      public  string AddToJob(string _desc, int _min, int _max)
        {
            SqlConnection cn = new SqlConnection("Data Source=Server2;User Id=sa;Password=123;DataBase=PUBS1");
            cn.Open();
            string _sql = "Insert Into Jobs Values('" + _desc + "'," + _min + "," + _max + ")";
            SqlCommand cmd = new SqlCommand(_sql, cn);
            int _record = cmd.ExecuteNonQuery();
            if (_record > 0)
                return "Record Inserted";
            else
                return "Failed To Insert The Record";
        }
      public string UpdateJob(int _jobid, string _desc, int _min, int _max)
      {
          SqlConnection cn = new SqlConnection("Data Source=Server2;User Id=sa;Password=123;DataBase=PUBS1");
          cn.Open();
          string _sql = "Update Jobs Set [Desc]='" + _desc + "',MinVal=" + _min + ",MaxVal=" + _max+" Where JobId="+_jobid;
          SqlCommand cmd = new SqlCommand(_sql, cn);
          int _record = cmd.ExecuteNonQuery();
          if (_record > 0)
              return "Record Updated";
          else
              return "Failed To Update The Record";
      }

Now with the above code you can see our service is ready now. Just compile it and run it.

Creating a WPF Client:

Our service is ready to be consumed by the client.  In this article to consume our service we will create a windows presentation application i.e. WPF application so just follow the steps.

Step 1:

Start Visual Studio -> File New Project -> WPF application which will create one default window i.e MainWindow.xaml and the MainWindow.xaml.cs. Design this MainWindow with 4 textboxes for showing values, 3 buttons for Getting Specified JobId details as getdetails, For Adding New record Add New and For Updating record Update. And one gridview to show all the job details in it.

Step 2:

Now our design part is ready it's time to call the service so go to service application and from Wcf service Client will be opened over there open it and copy the metadata address from there and in our Wpf client go to solution explorer and Add Service Reference which will ask you the service address paste the copied address in it which will show the Contract Available in the service. Provide name to reference Here I'm giving ServiceClient.

Step 3:

In Window_Loaded event write the following code to populate the grid first.

ServiceClient.JobServiceClient sc = new ServiceClient.JobServiceClient();
            DataSet ds = sc.ReturnAllJobs();
            dataGrid1.ItemsSource = ds.Tables[0].DefaultView;

When the window will get loaded you can view the record loded in datagrid.

Step 4:

GetDetails by Job Id: For getting the details of JobId in GetDetails Button Write the code.

ServiceClient.JobServiceClient sc = new ServiceClient.JobServiceClient();
            ServiceClient.ClsJobs x = sc.ReturnJobs(int.Parse(txtjobid.Text));
            if (x.JobId>-1)
            {
                txtjobid.Text = x.JobId.ToString();
                txtdesc.Text = x.Desc;
                txtmax.Text = x.MaxVal.ToString();
                txtmin.Text = x.MinVal.ToString();
            }
            else
            {
                MessageBoxResult result = MessageBox.Show("No Record");
                txtmin.Text = "";
                txtmax.Text = "";
                txtjobid.Text = "";
                txtdesc.Text = "";
            }

In the above code you can see we are getting the details from the class ClsJobs which we created with DataContract attribute. Just access the values and show in textboxes.

Step 5:

Add New Record To Job: For adding new record write the following code in Add New button click event

ServiceClient.JobServiceClient sc = new ServiceClient.JobServiceClient();
                string _message = sc.AddToJob(txtdesc.Text, int.Parse(txtmin.Text), int.Parse(txtmax.Text));
                MessageBoxResult result = MessageBox.Show(_message);
                txtdesc.Text = "";
                txtjobid.Text = "";
                txtmax.Text = "";
                txtmin.Text = "";

                DataSet ds = sc.ReturnAllJobs();
                dataGrid1.ItemsSource = ds.Tables[0].DefaultView;

Step 6:

Update Record:

For updating record write the code in update_click event to update the record.

if (txtjobid.Text != String.Empty)
            {
                ServiceClient.JobServiceClient sc = new ServiceClient.JobServiceClient();
                string _mess = sc.UpdateJob(int.Parse(txtjobid.Text), txtdesc.Text, int.Parse(txtmin.Text), int.Parse(txtmax.Text));
                MessageBoxResult res = MessageBox.Show(_mess);
                txtdesc.Text = "";
                txtjobid.Text = "";
                txtmax.Text = "";
                txtmin.Text = "";
                DataSet ds = sc.ReturnAllJobs();
                dataGrid1.ItemsSource = ds.Tables[0].DefaultView;

            }
            else
            {
                MessageBoxResult res1 = MessageBox.Show("Pls Fill The Job Id");
            }

Conclusion:

In this way we have created insert update and select with simple methods as well as complex types using visual studio provided template.