Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Thursday, July 11, 2013

WCF Method Overloading Example in c#.net | Implementing method overloading in WCF

hi in post i will show how to implement method overloading in WCF using c#.net.

Example :

Take a new WCF Service Application Project.

1. IService1.cs --> Interface code

 [ServiceContract]
    public interface IService1
    {
        [OperationContract(Name="GetDataValue1")] //Method overloading
        string GetData(int value);

        [OperationContract(Name = "GetDataValue2")] //Method overloading
        string GetData(string value);
    }

2. Service.svc.cs 

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

        public string GetData(string value)
        {
            return string.Format("You entered: {0}", value);
        }
       
    }

3. Result :




Tuesday, June 4, 2013

Fault contract in WCF | Example of using fault contract in WCF asp.net | Handle Exceptions in WCF | Custom Error handling in WCF

Hi in this post i will show how to use fault contract in WCF to handle exceptions and how we can display a custom error message to client for the exception has occurred.

Taking a scenario where we have a divide by zero exception getting occurred . To that exception we can show a custom error message to the client as "Application Error has occurred. Please try again later" or we can also show the actual error generated by the .net application. To handle such an scenario we use Fault Contract.

Sample Code of WCF Service using Fault Contract to handle Exceptions:

1. Service Interface i.e IService2.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

[ServiceContract]
public interface IService2
{
    [OperationContract]
    [FaultContract(typeof(HandleException))]
    int GetData(int value, int value2);
}

[DataContract]
public class HandleException
{
    [DataMember]
    public string CustomExceptionMessage { get; set; }
    [DataMember]
    public string ErrorDesc { get; set; }
}


2. Consuming Interface into WCF .svc page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

public class Service2 : IService2
{
    public int GetData(int value, int value2)
    {
        HandleException Obj = new HandleException();
        try
        {
            return (value / value2);
        }
        catch (Exception ex)
        {
            Obj.CustomExceptionMessage = "An Application Error has occurred";
            Obj.ErrorDesc = ex.ToString();
            throw new FaultException<HandleException>(Obj, ex.ToString());
        }
    }
}


3. Consuming Service in my Client Application :
Here for the exception occurred in the service i will be showing the custom message in my client application which i have handled in the WCF Service catch block for every exception caused.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.ServiceModel;

public partial class FaultExceptionClient : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ServiceReference1.Service2Client s2 = new ServiceReference1.Service2Client();
            int Z = s2.GetData(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text));
            Response.Write("<script language='javascript'>alert('Result: " + Z + "');</script>");
        }
        catch (FaultException<ServiceReference1.HandleException> ex1)
        {
            lblErrorMessage.Visible = true;
            lblErrorMessage.Text = ex1.Detail.CustomExceptionMessage + "<br/>" + ex1.Detail.ErrorDesc;    
        }
    }
}

Result:



Saturday, May 25, 2013

using wsHttpBinding endpoint with transport security for a WCF Service in asp.net

hi in this post i will show how to use wsHttpBinding endpoint  with transport security for a WCF Service in Asp.net.

Go to the webconfig file of the WCF application:

1. After defining the implementation of the methods which are going to be exposed by the service, we will go to the web.config file here will define the service behavior, endpoint(wsHttpBinding) and transport security.


<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    
    <bindings>
      <wsHttpBinding>
        <binding name="SecurityByTransport">
          <security mode="Transport">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>


    <services>
      <service behaviorConfiguration="ServiceBehavior" name="WcfService5.Service1">
        <endpoint binding="wsHttpBinding" contract="WcfService5.IService1"/>
        <endpoint address="mex" binding="mexHttpBinding"
              name="MetadataBinding" contract="IMetadataExchange"/>
      </service>

    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

2. Run the project to check the desired output

1



2

Thursday, May 23, 2013

call a asp.net wcf service using jquery | Ajax Json Call to WCF using Jquery

Hi in post i will show how to call a asp.net wcf service using jquery.

1. Take a new website empty template add aspx page and wcf service page.

2. Go to App_Code --> IService.cs to define the method signature.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
    string GetDate(string Date);    
}


3. Go to App_Code --> Service.cs to write the implementation for the declared method signature.

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web.Script.Serialization;
using System.ServiceModel.Activation;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    public string GetDate(string Date)
    {
        return "'Hello World' Todays Date is : " + Date.ToString();
    }
}


4. Now in the Web.config file i will define the address, binding, contract and service behaviours for the WCF Service

Under the configuration tag add this:

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
        <endpointBehaviors>
            <behavior name="ServiceAspNetAjaxBehavior">
                <enableWebScript />
            </behavior>
        </endpointBehaviors>
</behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceAspNetAjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel> 

5. Now writing the jquery ajax code to call the wcf service.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.8.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        var d = new Date();

        function CallWCF() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '<%=ResolveUrl("~/Service.svc/GetDate") %>',
                data: '{"Date": "' + d.toDateString() + '"}',
                processData: true,
                dataType: "json",
                success: ServiceSucceeded,
                error: ServiceFailed
            });
        }

        function ServiceFailed(output) {
            Log('Service call failed: ' + output.status + ' ' + output.statusText);
        }

        function ServiceSucceeded(output) {
            var outputValue = output.d;
            Log("Service call Success: <br/> " + outputValue);
        }

        function Log(displayValueFromService) {
            $("#DisplayOutput").append('<br/>' + displayValueFromService);
        }
    </script>
</head>
<body>
    <input id="Button1" type="button" value="Call WCF Service" onclick="CallWCF();" />
    <div id="DisplayOutput">
    </div>
</body>
</html>


6. Result: