Click here to Skip to main content
Click here to Skip to main content

Creating and Consuming Your First WCF Service

By , 25 Sep 2009
 

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

[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.

[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:

 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:

<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:

  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:

    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:

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)

About the Author

Farooq Kaiser
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
Member
12+ years of complete software development life cycle experience for web based applications and multi-tier client-server desktop, primarily using LINQ, WCF, WWF, C#, ASP.NET, XML, XSLT, AJAX, Winforms,Visual Basic, JavaScript, JQuery, Google APIs, C++, VB.NET, C, ATL/COM, Open XML. Extensively involved in the requirement analysis, feasibility study, conceptualization, planning, architecture/design, configuration, development, quality assurance, implementation and release of the software products.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralEasiest way to create and consume WCF Services in asp.netmemberLalit24rocks14 May '13 - 21:14 
Easiest way to create and consume WCF Services in asp.net
http://www.webcodeexpert.com/2013/04/how-to-create-and-consume-wcf-services.html
QuestionEasiest way to create and consume WCF Services in asp.net ?memberLalit24rocks14 May '13 - 21:00 
Easiest way to create and consume WCF Services in asp.net ?
http://www.webcodeexpert.com/2013/04/how-to-create-and-consume-wcf-services.html[^]
Lalit Raghuvanshi
http://www.webcodeexpert.com/

GeneralMy vote of 2memberMember 980908511 Mar '13 - 21:21 
quite difficult to understand... no more detail explation.
QuestionMy Vote 4membermadhan430 Jan '13 - 6:21 
Easy to understand for the new WCF developers Wink | ;)
GeneralMy vote of 5memberWeerayut Teja11 Jan '13 - 16:39 
Easy to understand Smile | :)
GeneralMy vote of 4memberkaramusti22 Nov '12 - 21:13 
Helpful article.
GeneralMy vote of 5memberkishormahale7 Nov '12 - 23:37 
its good to understand.. thax...
GeneralMy vote of 5memberAmol Borkar, Pune, India9 Oct '12 - 23:20 
Thanks...
GeneralMy vote of 3memberAnirudha_baba16 Aug '12 - 20:46 
good but needed more explanation
GeneralMy vote of 5memberChristian Amado10 Aug '12 - 7:42 
Excellent! Really interesting for beginners =)

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 25 Sep 2009
Article Copyright 2009 by Farooq Kaiser
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid