Customizing The Windows Communication Foundation (WCF)

Hello,

If you have been following the first part which is Intro To Windows Communication Foundation, it’s time for us to customize our WCF solution according to our requirements. If you seemed lost in this post, please have a quick look at the first part so that you might have an idea how to initialize the WCF solution.

For this part, we are going to display data from our database to the Service itself. This will allow us to check whether our data is being retrieved correctly. I will be using SQL Server 2012 as Database Management System.

I will skip the part of creating the database and inserting data but if you have any problem with the database, drop me a comment and I might guide you for the setup of database. In short, I have created a table named “My_TvShows” with schema “dbo” and database name “JustGetCodes” and inserted some TV shows name with its ratings.

With the following SQL Statement “SELECT * FROM JustGetCodes.dbo.My_TvShows“, the following result will be displayed:

CustomizingSQLQuery
SQL Query

We will now display the same result within the WCF Solution and  also execute same SQL Query using C# Codes.

Create a database connection in Web Config file
  • Head over Web.Config file in your solution
  • Add the following XML Tag after the </appSettings> and save the file.
  • Note: Your connection is different from mine! 
    • <connectionStrings>
      <add name=”myConnectionString” connectionString=”Data Source=HP350G1; Trusted_Connection=Yes; Initial Catalog=JustGetCodes;”/> </connectionStrings>

      CustomizingConnectionStirng
      Connection String in Web.Config
Create a Model Class named TvShows.cs

The TvShows.cs class will store the details received from the database in the model TvShows

  • Right-Click on the Project and Add new Folder as “Model
  • Right-Click on the Model Folder and Add a new class named “TvShows.cs
  • Insert the following code snippets to declare the properties of the TvShows class
    • public int[] TVID { get; set; }
      public string[] TvShowsName { get; set; }
      public int[] Ratings { get; set; }

tvShowsClass
TvShows.cs
Create the method to display in Service1.svc.cs

It’s time to dive into some codes now. We’ll create a method named as DisplayTvShows and return all TvShows just like we saw in the SQL Query

  • Head Over Service1.svc.cs and add the connection string just after the Service1 is declared
    • string connectionString = ConfigurationManager.ConnectionStrings[“myConnectionString”].ConnectionString;

      ServiceConnecction
      Connection in Service1.svc.cs
  • Create the method using the following code :
    • public TvShows DisplayTvShows() {
      TvShows AllShows = new TvShows();

      //SQL QUERY goes here

      return AllShows;
      }

      • The above method is expecting a type “TvShows” to return as result
      • An empty list named AllShows is created and is returned just to avoid Visual Studio to show any error. (Tip: If you working in team on the same file, it is better to correct all errors else your team members won’t be able to compile the file)
Configuring the method to execute the SQL Statement

Still on the same file, we are now going to write some codes that will look for the database connection and also calls the SQLClient to execute the statement.

  • Remove the Line “//SQL QUERY goes here” and enter the following:
    • //Define some variable to store data temporarily
      var tvId = new List<int>();
      var TvShows = new List<string>();
      var Ratings = new List<int>();using (SqlConnection con = new SqlConnection(connectionString))
      {
      try
      {
      con.Open();
      string Query = “SELECT * FROM JustGetCodes.dbo.My_TvShows”;
      SqlCommand cmd = new SqlCommand(Query, con);
      cmd.CommandType = System.Data.CommandType.Text;
      cmd.CommandTimeout = 0;using (SqlDataReader sdr = cmd.ExecuteReader())
      {
      while (sdr.Read())
      {
      //Make Sure that the columns heading are same as in the SQL Table

      tvId.Add(Convert.ToInt32(sdr[“TVID”]));
      TvShows.Add(sdr[“TV_Show_Name”].ToString());
      Ratings.Add(Convert.ToInt32((sdr[“Show_Ratings”])));
      }
      }

      //Attach the Lists to the Model

      AllShows.TVID = tvId.ToArray();
      AllShows.TvShowsName = TvShows.ToArray();
      AllShows.Ratings = Ratings.ToArray();
      }

      catch (Exception ex)
      {
      throw ex;

      }

      //Close the database connection
      con.Close();
      }

  • As you might have noticed, the string Query is written directly as SQL Statement, well for now we’ll leave it as it is. We’ll improve later on using parameters and stored procedure. 😛
  • The codes above will execute the SQL Statement and as long as the SQLDataReader is retrieving data, it will attach them to the different small lists. At the end the small list will be attached the Model. I prefer to do this way so that in the future we can do some manipulation before adding to the model.
  • The final codes should appeared as below:
FinalCodes
Codes for DisplayTvShows()
Making our method public to the service

The final part is to inform the service that this method is available to connect to any client.

  • Head over to IService1.cs and enter the following code:
    • [OperationContract]
      TvShows DisplayTvShows();

      DeclaringMethod
      Declaring Method in IService.cs
  • The [OperationContract] attribute tells the service that the method “TvShows DisplayTvShows()” is a part of the service now. Guess you managed to know the term of OperationContract now. 😀

 

Time To Test

After we make sure that there is no error on any file after building the solution, it’s time for the verdict :D. Don’t worry, WCF provide an interface for test client so that you can view your results directly in a console.

  • Right-Click on the “Service1.svc” and set as Start Page
  • Run your solution by pressing on the small play icon
  • You will see your method “DisplayTvShows()” in the console, if so, well you are on 50% on completion 😀
TestClient
WCF Test Client
  • Double click on the method and click invoke and then Ok
  • Watch the Magic 😀
WCFClient
Magic
  • You will now be able to view same data from the SQL Statement in the console by expanding the different properties.
Results
Final Results

Note: Your result might be different from mine depending the records inserted in the table

This is pretty much as starting to understand the WCF. For my next post we’ll try to make service more accessible by adding some properties.

Good Luck 😀

Best Wishes 

Harshu Kumar Gaonjur 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s