Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

WCF WebService in Applications A Beginner guide

4.56/5 (4 votes)
27 Aug 2016CPOL3 min read 10.9K   139  
This article describe the way of writing your WCF Service in Professional Application

 

Introduction

**Before read this article please read what is WCF or why its need (for begineer)**

WCF is a framework for developing service oriented applications that can send asynchronous message to one endpoint to another endpoint. In this article i will show details development process of a WCF applications from a professional applications development view.

 

Background

There are lots of articles available in the internet to learn WCF. So here I will expand my article to show details with a professional applications development view point. That's why the user can easily use this code/article when they start their WCF services in real life Applications

Part One: WCF Service create debug and Test

SO first we create a WCF Project from Visual studio

From Visual Studio->Create New project->WCF->WCF Service Application

 

Fig: 1

So what you have created?

You have created a Service that's name Service1.svc see on your project .

C#
public class Service1 : IService1
   {
       public string GetData(int value)
       {
           return string.Format("You entered: {0}", value);
       }

       public CompositeType GetDataUsingDataContract(CompositeType composite)
       {
           if (composite == null)
           {
               throw new ArgumentNullException("composite");
           }
           if (composite.BoolValue)
           {
               composite.StringValue += "Suffix";
           }
           return composite;
       }

   }

Now the Question is How a service is accessible?

Contract

In WCF, all services expose contracts and describing what services does to the outside world. Different Type of Contract

  • Operation Contract. ...
  • Data Contract. ...
  • Message Contract. ...
  • Fault Contract.

Namespace and Names

By default, the exposed name of the contract will be the name of the interface used.

C#
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = UriTemplate.LoanCategoryById)]
        QueryResult<list<categoryresponse>> GetData(int value , string st);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
    
</list<categoryresponse>

 

Now just run it and you will see output like that.

Fig: 2

 

Now I will explain how call your service method and how to debug. After that how you will test your service that's working fine or not?

1. After runnning you will see like fig:2 in your browser.

Click on Service1.svc,  you will notice a page with heading "Service1 Service"

2.  Now to see sevice methods on your service use /help on your URL

use this http://localhost:16980/Service1.svc/help

Are you see something? If NOT

then please change your web config System.service node as below

<servicehostingenvironment multiplesitebindingsenabled="true">
   <bindings>
        <webhttpbinding>
       <binding crossdomainscriptaccessenabled="true" name="webHttpBindingWithJsonP">

       <binding closetimeout="00:01:00" maxbuffersize="10485760" maxreceivedmessagesize="10485760" name="service1Binging" opentimeout="00:01:00" receivetimeout="00:10:00" sendtimeout="00:01:00">
         <security mode="None">
       </security></binding>
       <binding closetimeout="00:01:00" maxbuffersize="31457280" maxreceivedmessagesize="31457280" name="uploadBinding" opentimeout="00:01:00" receivetimeout="00:10:00" sendtimeout="00:01:00">
         <security mode="None">
       </security></binding>

     </binding></webhttpbinding>

   </bindings>
   <services>
     <service name="MyFirstWCFProject.Service1">
       <endpoint address="" behaviorconfiguration="web" binding="webHttpBinding" bindingconfiguration="service1Binging" contract="MyFirstWCFProject.IService1">
     </endpoint></service>
   </services>
   <behaviors>
     <endpointbehaviors>
       <behavior name="web">
         <webhttp automaticformatselectionenabled="true" helpenabled="true">
       </webhttp></behavior>
       <behavior name="webUser">
         <webhttp>
       </webhttp></behavior>
     </endpointbehaviors>
     <servicebehaviors>
     </servicebehaviors>
   </behaviors>

   </servicehostingenvironment>
Now check that it's working fine. and you will see like below.
http://localhost:16980/Service1.svc/help

Part Two: Working in a Professional Application

You have done your basic structure of your service. Continue with the first part In your project you need to follow some standard to develop your applications for scalability, durability and readability.

1. URL Format

2. Error Handling and throw with your service

3. User and Session Checking

4. Paginations

5. Info Message

6. Any warning Message

7. Operational Status Message

So first You need to follow a standard URL Name that will call for your user applications.

Here I have two method GetData and GetDataUsingDataContract. So I need to assign a meaningful name without modification my existing method name.

So I create a Class to write URL Name globally

C#
public static class UriTemplate
{
    public const string LoanCategoryById = "LoanCategoryById";
    public const string LoadAllCategory = "LoadAllCategory";
}

and change in Iservice1 as like below

C#
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = UriTemplate.LoanCategoryById)]

Secondly You need to return a standard message format for your every Response Result.

Base Result Class

C#
 public class BaseResult
    {
        private bool operationSuccessful = false;
        public bool IsOperationSuccessful
        {
            get { return this.operationSuccessful; }
            set { this.operationSuccessful = value; }
        }

        private bool isresult = false;
        public bool IsResult
        {
            get { return this.isresult; }
            set { this.isresult = value; }
        }

        private List<message> statusMessages;
        public List<message> StatusMessages
        {
            get { return statusMessages; }
            set { statusMessages = value; }
        }

        private List<message> errorMessages;
        public List<message> ErrorMessages
        {
            get { return errorMessages; }
            set { errorMessages = value; }
        }

        private List<message> infoMessages;
        public List<message> InfoMessages
        {
            get { return infoMessages; }
            set { infoMessages = value; }
        }

        private List<string> warnMessages;
        public List<string> WarnMessages
        {
            get { return warnMessages; }
            set { warnMessages = value; }
        }
    }

    public class Message
    {
        public string Code { get; set; }
        public string Text { get; set; }
    }
    
</string></string></message></message></message></message></message></message>

And Below Query Result Class

C#
    public class QueryResult<t> : BaseResult
    {
        private T result;
        public T Result
        {
            get { return result; }
            set { result = value; }
        }
        public int Total { get; set; }
    }
    
</t>

So using this Query Result class you will handle result, how much result contain in the response list, an error message, operation status etc.

 Now  I Have implemented this in GetData Method

C#
      public QueryResult<list<categoryresponse>> GetData(int value,string st)
        {
            QueryResult<list<categoryresponse>> result = new QueryResult<list<categoryresponse>>();
            List<categoryresponse> responseList = new List<categoryresponse>();

            try
            {

                if (String.IsNullOrEmpty(st))
                {
                    var err = new List<message>();
                    err.Add(new Message { Code = "1", Text = "Session Token is missing" });
                    result.ErrorMessages = err;
                    return result;
                }

                else
                {
                    List<categoryresponse> categories = new List<categoryresponse>() { new CategoryResponse(){Code="001",Name="Test 1"}, new CategoryResponse(){Code="002", Name="Test 2"}};
                   //if need any conditional changes
                    foreach (var item in categories)
                    {
                        responseList.Add(item);
                    }
                    result.Total = categories.Count;
                }

                result.Result = responseList;
                result.IsOperationSuccessful = true;
                return result;
            }
            catch (Exception ex)
            {
                result.IsOperationSuccessful = false;
                result.IsResult = false;

                var err = new List<message>();
                err.Add(new Message { Code = "5", Text = ex.Message });
                result.ErrorMessages = err;
                return result;
            }

        }
    
</message></categoryresponse></categoryresponse></message></categoryresponse></categoryresponse></list<categoryresponse></list<categoryresponse></list<categoryresponse>

Also Please change IService Method Return Type like Below

C#
     [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = UriTemplate.LoanCategoryById)]
      QueryResult<list<categoryresponse>> GetData(int value , string st);
</list<categoryresponse>

So you have done service. Now how to test it. How to see result.

Personally i use POSTMAN a plugin for google chrome browser

https://www.getpostman.com/

Install it from this link.

Open it

 

Paste your URL on URL

Write Body [That you pass with parameter]

Data Type JSON and run you will see your result.

    {
    "ErrorMessages": null,
    "InfoMessages": null,
    "IsOperationSuccessful": true,
    "IsResult": true,
    "StatusMessages": null,
    "WarnMessages": null,
    "Result": [
        {
            "Code": "001",
            "Name": "Test 1",
            "ParentGroupId": 0
        },
        {
            "Code": "002",
            "Name": "Test 2",
            "ParentGroupId": 0
        }
    ],
    "Total": 2
}

Points of Interest

This article for beginner who face problem when developing service based applications. I think its help them better.

History

Keep a running update of any changes or improvements you've made here.

License

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