Bunch's Blog

One day I'll have a catchy subtitle, one day
posts - 87 , comments - 126 , trackbacks - 0

Using WCF Service With a Class

This post is an example of how to write a WCF Service using a class. The example uses Visual Studio 2010, written in C#,  SQL Server 2008 and hosted in IIS. So lets have at it.

The table is pretty simple just three columns, an TestID (int), Value1 (varchar(50)) and Value2 (varchar(50)). The stored procedure used will return one record from the table using the TestID as a parameter.

Table SQL:

CREATE TABLE [dbo].[Table_1](
 [TestID] [int] IDENTITY(1,1) NOT NULL,
 [Value1] [varchar](50) NOT NULL,
 [Value2] [varchar](50) NOT NULL,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
 [TestID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Stored Procedure:

CREATE PROCEDURE [dbo].[spGetValuesForTestID]
 -- Add the parameters for the stored procedure here
 @TestID int
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

-- Insert statements for procedure here
 SELECT TestID, Value1, Value2
 FROM Table_1
 WHERE TestID = @TestID
END

Once that is setup and some test values are inserted into the table we can start on the service itself. In VS click on File/New/Project then WCF under the Installed Templates. Then pick WCF Service Application. For the example keep the other settings as they are. This will create a new project with some default items already built. At this point have   IService1.cs and Service1.svc.cs files open in the IDE.

In Service1.svc.cs you will see a note about renaming. For the example Service1 is renamed to TestValues and IService1 is renamed to TestService. The Refactor\Rename is handy to use here just like the note says.

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class TestValues : TestService

Go back to IService1.cs and remove the code in the public interface TestService and replace it with:

[ServiceContract]
public interface TestService
{
     [OperationContract]
     TestValuesClass ReturnData(int testID);
}

Now change the default CompositeType class to:

[DataContract]
public class TestValuesClass
{
     [DataMember]
     public int TestID { get; set; }

     [DataMember]
     public string Value1 { get; set; }

     [DataMember]
     public string Value2 { get; set; }
}

The ReturnData is what will be exposed to call and run everything to get the data. The TestValuesClass just sets up the properties for the data.

Next we focus on the Service1.svc.cs file. This is where you will do the actual connection to the database and return the data. This is just like in other applications you may have written. The code for this file is how I wrote it up but there are variations so you can change it up as you see fit. The first item is the public ReturnData function.

 public TestValuesClass ReturnData(int testID)
{
     TestValuesClass tvc = new TestValuesClass();
     tvc = GetData(testID);
     return tvc;
}

Here you create a new TestValuesClass to hold the data. Then you call the function that returns the data, GetData. The class you created is what gets returned from the service. The GetData function is:

private TestValuesClass GetData(int testID)
{
     TestValuesClass tvc2 = new TestValuesClass();
     string cnStr = ConfigurationManager.ConnectionStrings["Test_ConnectionString"].ConnectionString;
     using (SqlConnection conn = new SqlConnection(cnStr))
     {
          SqlCommand cmd = new SqlCommand("spGetValuesForTestID", conn);
          cmd.CommandType = System.Data.CommandType.StoredProcedure;
          cmd.Parameters.AddWithValue("@TestID", testID);
          conn.Open();
          SqlDataReader dr;
          dr = cmd.ExecuteReader();
          while (dr.Read())
          {
               tvc2.TestID = int.Parse(dr["TestID"].ToString());
               tvc2.Value1 = dr["Value1"].ToString();
               tvc2.Value2 = dr["Value2"].ToString();
          }
     }
     return tvc2;
}

This is where you can change things up if you have different ways of connecting to databases and returning the data. For this example this works well. It grabs one record from Table_1 that has a TestID of the testID parameter passed to it. One note you do need to add two using statements to the top of the class for this example to work the System.Configuration and System.Data.SqlClient. Configuration is for grabbing the connection string in the web.config file and SqlClient for the various SQL objects.

That is all the coding that is needed for the example. To test out the service it first needs to be added to IIS as an Application. You can publish it straight from VS to the location you setup in IIS using Build/Publish in VS. Once the service is added to IIS you can browse to it and it will look like:

However you can not test the service in a browser like you can with a web service built using asmx files. A testing tool to use is WcfTestClient.exe. It can be found under Program Files\Microsoft Visual Studio 10.0\Common7\IDE. Once you launch the application you can use the same URL you used in a browser under Add Service. Once you expand TestService you can double click on ReturnData and you will see:

From here you can add a TestID value to the Value column and click on Invoke. The results the service would return to an application will be visible in the Response pane.

Tags: ,

Print | posted on Wednesday, January 18, 2012 9:19 AM |

Feedback

Gravatar

# re: Using WCF Service With a Class

In this example, when you call the webService from de client.. how do you get an instance of TestValuesClass class?
11/26/2013 1:10 PM | DIego
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: