Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

Creating and Consuming Your First WCF Service

Rate me:
Please Sign up or sign in to vote.
4.21/5 (57 votes)
25 Sep 2009CPOL2 min read 657.6K   18.3K   88   42
In this article, I will examine how to create and consume a WCF service. WCF is next-generation programming platform and runtime system for building, configuring and deploying service-oriented applications.

Introduction

In this article, I will examine how to create and consume a WCF service. WCF is a next-generation programming platform and runtime system for building, configuring and deploying service-oriented applications. For more details, please see here.

Creating a WCF Service

I will create a stock service to demonstrate a WCF service. To create a WCF service, please follow these steps:

  1. Launch Visual Studio 2008.
  2. Click on File -> new -> project, then select WCF service application.
  3. It will create a WCF service application template.

I will delete the default contract and then create an IStock contract as shown below.

Using the Code

C#
[ServiceContract]
    public interface IStock
    {
        [OperationContract]
        Stock GetStock(string Symbol);   
    }

The above contract has one method that returns a stock object for a given symbol. Here is our Stock class that has Symbol, Date, Company and Close properties respectively.

C#
[DataContract]
    public class Stock
    {
        [DataMember]
        public string Symbol { get; set; }
        [DataMember]
        public DateTime Date { get; set; }
        [DataMember]
        public string Company { get; set; }
        [DataMember]
        public decimal Close { get; set; }
    }

Next, I will delete the default service and create a Stock service that will implement the Istock contract as shown below:

C#
public class Stocks : IStock
   {
       #region IStock Members
       public Stock GetStock(string Symbol)
       {
           Stock st = null;
           switch (Symbol.ToUpper())
           {
               case "GOOG":
                   st = new Stock { Symbol = Symbol, Date = DateTime.Now,
           Company = "Google Inc.", Close = 495 };
                   break;
               case "MSFT":
                   st = new Stock { Symbol = Symbol, Date = DateTime.Now,
           Company = "Microsoft Corporation", Close = 25 };
                   break;
               case "YHOO":
                   st = new Stock { Symbol = Symbol, Date = DateTime.Now,
           Company = "Yahoo! Inc.", Close = 17 };
                   break;
               case "AMZN":
                   st = new Stock { Symbol = Symbol, Date = DateTime.Now,
           Company = "Amazon.com, Inc.", Close = 92 };
                   break;
           }
           return st;
       }
       #endregion
   }

In the above service, I implemented IStock contract that has a GetStock method which returns stock object for a given Symbol.

Now, I will have the following endpoints in my web.config:

XML
<service behaviorConfiguration="WcfSample.Service1Behavior" name="WcfSample.Stocks">
<endpoint address="" binding="wsHttpBinding" contract="WcfSample.IStock">
<identity>
 <dns value="localhost"/>
 </identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>

In the above configuration, we have address="" which is localhost, binding="wsHttpBinding" and contract="WcfSample.IStock".

Now I will compile the service and build a client to consume the service.

Creating a Client to Consume Service

To create a client, I will create a web application. Please follow these steps.

  1. Right Click on Solution -> Add -> new project, then select ASP.NET web application.
  2. It will create a web application template.
  3. Now, I will add the service reference. To add a service reference, select client application, then add a service reference. Since our client is in a same solution, I will click discover and service in the solution as shown below:

    Image 1

  4. In default.aspx, I will create a simple UI, a textbox to enter the stock symbol and a button to call the service to get stock information. Here is our code behind:

    C#
    ServiceReference2.StockClient sc = new ServiceReference2.StockClient();
    ServiceReference2.Stock st = sc.GetStock(TextBox1.Text.Trim());
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("<B>Company:</B> {0}<br />", st.Company);
    sb.AppendFormat("<B>Date: </B>{0}<br />", st.Date);
    sb.AppendFormat("<B>Close: </B>{0}<br />", st.Close);
    sb.AppendFormat("<B>Symbol: </B>{0}<br />", st.Symbol); 
    Label1.Text = sb.ToString(); 
  5. Here are a few screenshots from our final application:

    Image 2

    Image 3

Summary

In this article, we examined how to create and consume a WCF service. As you can see, creating and consuming WCF service with Visual studio 2008 is pretty simple.

History

  • 25th September, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy Vote of 4 Pin
Member 190665923-Apr-15 14:14
Member 190665923-Apr-15 14:14 
GeneralMy vote of 3 Pin
manish71022-Jul-14 19:10
manish71022-Jul-14 19:10 
QuestionStill cant get this to work. Pin
naijateddy16-Jun-14 1:38
naijateddy16-Jun-14 1:38 
GeneralMy Vote of 4 Pin
Jared Beach13-Feb-14 2:15
Jared Beach13-Feb-14 2:15 
Questioncomment for code Pin
manjiri 20127-Jan-14 23:07
manjiri 20127-Jan-14 23:07 
QuestionGot an error Pin
DiegoSalvatore26-Nov-13 8:30
DiegoSalvatore26-Nov-13 8:30 
AnswerRe: Got an error Pin
Chandrasekhar Guruvayoorappan14-Apr-15 3:36
Chandrasekhar Guruvayoorappan14-Apr-15 3:36 
Questionuse xamarin android Pin
beyazcennet4-Nov-13 12:50
beyazcennet4-Nov-13 12:50 
GeneralEasiest way to create and consume WCF Services in asp.net Pin
Lalit24rocks14-May-13 21:14
Lalit24rocks14-May-13 21:14 
QuestionEasiest way to create and consume WCF Services in asp.net ? Pin
Lalit24rocks14-May-13 21:00
Lalit24rocks14-May-13 21:00 
GeneralMy vote of 2 Pin
Member 980908511-Mar-13 21:21
Member 980908511-Mar-13 21:21 
QuestionMy Vote 4 Pin
madhan430-Jan-13 6:21
madhan430-Jan-13 6:21 
GeneralMy vote of 5 Pin
Weerayut Teja11-Jan-13 16:39
Weerayut Teja11-Jan-13 16:39 
GeneralMy vote of 4 Pin
californiacoder22-Nov-12 21:13
californiacoder22-Nov-12 21:13 
GeneralMy vote of 5 Pin
Kishor_Mahale7-Nov-12 23:37
Kishor_Mahale7-Nov-12 23:37 
GeneralMy vote of 5 Pin
Amol_27101982, India9-Oct-12 23:20
Amol_27101982, India9-Oct-12 23:20 
GeneralMy vote of 3 Pin
Anirudha_Gohokar16-Aug-12 20:46
Anirudha_Gohokar16-Aug-12 20:46 
GeneralMy vote of 5 Pin
Christian Amado10-Aug-12 7:42
professionalChristian Amado10-Aug-12 7:42 
Excellent! Really interesting for beginners =)
Questionthankq Pin
jareenkumar27-Jul-12 0:48
jareenkumar27-Jul-12 0:48 
SuggestionMy Vote 4 -How Host WCF service on IIS and Consume it From WPF Pin
Shailesh vora8-Jul-12 20:06
Shailesh vora8-Jul-12 20:06 
GeneralRe: My Vote 4 -How Host WCF service on IIS and Consume it From WPF Pin
Faizan Mubashar25-Dec-13 22:17
Faizan Mubashar25-Dec-13 22:17 
GeneralMy vote of 4 Pin
Shailesh vora8-Jul-12 20:04
Shailesh vora8-Jul-12 20:04 
GeneralMy vote of 4 Pin
ashriv4-Jun-12 19:14
ashriv4-Jun-12 19:14 
Questionnongkhanhk5b@gmail.com Pin
nongkhanhk5b25-Mar-12 23:38
nongkhanhk5b25-Mar-12 23:38 
GeneralMy vote of 2 Pin
cuneyd7611-Nov-11 5:36
cuneyd7611-Nov-11 5:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.