About WCF :
WCF services in enterprises are used for developing distributed enterprise application. There are lots of advantages of using WCF services.WCF 3.5 had introduced support for Representational State Transfer (REST) using which the response from the service can be directly send using Plain Old Xml form (POX). If the WCF service is using REST/POX, then it is not necessary for the client to consume the WCF service proxy.For REST, WCF introduced a new binding i.e. WebHttpBinding. A client application that can do HTTP communication and can process XML, could now directly make a call to the WCF service and perform operations using XML.
My service.svc file looks as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public Employee[] getEmployee()
{
return new Employee[]
{
new Employee() {Firstname="Manjunath",LastName="Gaanji"},
new Employee() {Firstname="Shreekanth", LastName="Gaanji"},
new Employee() {Firstname="Mahantesh",LastName="Kendhuli"},
new Employee() {Firstname="Ravi",LastName="Patil"}
};
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
Interface looks as below.
My interface looks as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getShreekData", RequestFormat = WebMessageFormat.Xml)]
Employee[] getEmployee();
}
// 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; }
}
}
[DataContract]
public class Employee
{
private string _firstname;
private string _lastName;
[DataMember]
public string Firstname
{
get { return _firstname; }
set { _firstname = value; }
}
[DataMember]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
}
Note - Don't forget to include the below line
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service1 : IService1
{
The attribute AspNetCompabilityRequirements is used for specifying an ASP.NET compatible environment for WCF service execution.
and my config file looks as below
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="ServerBehave">
<endpoint address="soapService" binding="basicHttpBinding" contract="WcfService1.IService1"></endpoint>
<endpoint address="XMLService" binding="webHttpBinding" behaviorConfiguration="restPoxBehaviour" contract="WcfService1.IService1"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServerBehave">
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restPoxBehaviour">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</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>
Using JQuery,We can read the JSonResponse from WCF service and below is the client side code for reading RESTful wcf in JQuery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html src="http://code.jquery.com/jquery-1.7.js">
<head>
<script src="http://code.jquery.com/jquery-1.7.js"></script>
<title>jQuery calling RESTful Services</title>
<meta xmlns="http://www.w3.org/1999/xhtml" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getDataFromWCF() {
$.ajax(
{
type: "GET",
url: "http://localhost:58408/Service1.svc/XMLService/getShreekData",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var output = "<ul>";
for (var i in response) {
output += "<li>" + response[i].Firstname + " " + response[i].LastName;
}
output += "</ul>";
document.getElementById("Div1").innerHTML = output;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
alert(JSON.stringify(XMLHttpRequest) + "\n" + textStatus + "\n" + errorThrown);
}
catch (ex) { }
finally { }
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" onclick="getDataFromWCF()" name="Button1" value="Button2" />
<div id="Div1"></div>
</div>
</form>
</body>
</html>
Output looks as below
WCF services in enterprises are used for developing distributed enterprise application. There are lots of advantages of using WCF services.WCF 3.5 had introduced support for Representational State Transfer (REST) using which the response from the service can be directly send using Plain Old Xml form (POX). If the WCF service is using REST/POX, then it is not necessary for the client to consume the WCF service proxy.For REST, WCF introduced a new binding i.e. WebHttpBinding. A client application that can do HTTP communication and can process XML, could now directly make a call to the WCF service and perform operations using XML.
My service.svc file looks as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public Employee[] getEmployee()
{
return new Employee[]
{
new Employee() {Firstname="Manjunath",LastName="Gaanji"},
new Employee() {Firstname="Shreekanth", LastName="Gaanji"},
new Employee() {Firstname="Mahantesh",LastName="Kendhuli"},
new Employee() {Firstname="Ravi",LastName="Patil"}
};
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
Interface looks as below.
My interface looks as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/getShreekData", RequestFormat = WebMessageFormat.Xml)]
Employee[] getEmployee();
}
// 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; }
}
}
[DataContract]
public class Employee
{
private string _firstname;
private string _lastName;
[DataMember]
public string Firstname
{
get { return _firstname; }
set { _firstname = value; }
}
[DataMember]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
}
Note - Don't forget to include the below line
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service1 : IService1
{
The attribute AspNetCompabilityRequirements is used for specifying an ASP.NET compatible environment for WCF service execution.
and my config file looks as below
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="ServerBehave">
<endpoint address="soapService" binding="basicHttpBinding" contract="WcfService1.IService1"></endpoint>
<endpoint address="XMLService" binding="webHttpBinding" behaviorConfiguration="restPoxBehaviour" contract="WcfService1.IService1"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServerBehave">
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restPoxBehaviour">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</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>
Using JQuery,We can read the JSonResponse from WCF service and below is the client side code for reading RESTful wcf in JQuery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html src="http://code.jquery.com/jquery-1.7.js">
<head>
<script src="http://code.jquery.com/jquery-1.7.js"></script>
<title>jQuery calling RESTful Services</title>
<meta xmlns="http://www.w3.org/1999/xhtml" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getDataFromWCF() {
$.ajax(
{
type: "GET",
url: "http://localhost:58408/Service1.svc/XMLService/getShreekData",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var output = "<ul>";
for (var i in response) {
output += "<li>" + response[i].Firstname + " " + response[i].LastName;
}
output += "</ul>";
document.getElementById("Div1").innerHTML = output;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
alert(JSON.stringify(XMLHttpRequest) + "\n" + textStatus + "\n" + errorThrown);
}
catch (ex) { }
finally { }
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" onclick="getDataFromWCF()" name="Button1" value="Button2" />
<div id="Div1"></div>
</div>
</form>
</body>
</html>
Output looks as below
No comments:
Post a Comment