Step 1) Create a WCF Service Application using C# 4.5
Delete IService1.cs and IService1.svc
Step 2) Add WCF Service .name it as"ProfileService"
We need 2 operation contracts
[ServiceContract(Namespace="SP")]
public interface IProfileService
{
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Xml)]
List<Profile> GetAllProfilesAsXML();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
List<Profile> GetAllProfilesAsJSON();
}
ProfileService.cs Implementation file for above 2 contracts
public class ProfileService : IProfileService
{
private List<Profile> profiles = new List<Profile>();
public List<Profile> GetAllProfilesAsXML()
{
BuildProfile();
return profiles;
}
public List<Profile> GetAllProfilesAsJSON()
{
BuildProfile(); return profiles;
}
private void BuildProfile()
{
if (profiles.Count == 0)
{
profiles.Add(new Profile { Age = 21, Country = "USA", EmailID = "jhon@gmail.com", FirstName = "jhon", LastName = "Peter", ProfileID = 1, ZIPCode = "94086-2422", JoinedDate = new System.DateTime(1998, 1, 12) });
profiles.Add(new Profile { Age = 18, Country = "USA", EmailID = "macy@yahoo.com", FirstName = "macy", LastName = "William", ProfileID = 2, ZIPCode = "67897-2422", JoinedDate = new System.DateTime(2000, 11, 1) });
profiles.Add(new Profile { Age = 28, Country = "UK", EmailID = "alex@gmail.com", FirstName = "alex", LastName = "Samuel", ProfileID = 3, ZIPCode = "STHL 1ZZ", JoinedDate = new System.DateTime(2002, 10, 9) });
profiles.Add(new Profile { Age = 35, Country = "UK", EmailID = "bearns@gmail.com", FirstName = "beans", LastName = "Jessica", ProfileID = 4, ZIPCode = "AA9A 9AA", JoinedDate = new System.DateTime(2004, 10, 12) });
profiles.Add(new Profile { Age = 36, Country = "INDIA", EmailID = "prasad@gmail.com", FirstName = "prasad", LastName = "kanuturi", ProfileID = 5, ZIPCode = "110011", JoinedDate = new System.DateTime(1990, 1, 2) });
}
}
}
[DataContract]
public class Profile
{
[DataMember]
public int ProfileID { get; set; }
[DataMember]
public String FirstName { get; set; }
[DataMember]
public String LastName { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public DateTime JoinedDate { get; set; }
[DataMember]
public String EmailID { get; set; }
[DataMember]
public String ZIPCode { get; set; }
[DataMember]
public String Country { get; set; }
}
ProfileService.svc here we specify hosting Factory name. This is very important
<%@ ServiceHost
Language="C#"
Debug="true"
Service="WcfService1.ProfileService"
CodeBehind="ProfileService.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
Web.config file we need to enable crosssitescripting=true and help page.
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<!-- for help page -->
<endpointBehaviors>
<behavior name="myServiceEndPoint">
<webHttp helpEnabled="true" defaultBodyStyle="Bare" faultExceptionEnabled="true"/>
<enableWebScript/>
</behavior> </endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="WcfService1.ProfileService">
<endpoint address="" contract="WcfService1.IProfileService" binding="webHttpBinding" behaviorConfiguration="myServiceEndPoint"></endpoint>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="myrestBinding" crossDomainScriptAccessEnabled="true">
</binding>
</webHttpBinding>
</bindings>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="True">
<security mode="None"></security>
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Help Page located at http://localhost:26678/ProfileService.svc/help
Click on GET for GetAllProfilesAsJSON, u will get as shown below
Click on GET for GetAllProfilesAsXML, u will get as shown below
for cross domain WCF service, Binding Should be WebHttpBinding. Hosting Factory must be System.ServiceModel.Activation.WebScriptServiceHostFactory.
Once WCF Service creation is done.
Create A Empty Web Site using ASP.NET C#
Select .NET 4.5 and Empty Web Site
Add new item -> select Web form name it as Default.aspx
Add ScriptManager and reference the Service Path in that
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
<Services>
<asp:ServiceReference Path="http://localhost:26678/ProfileService.svc" />
</Services>
</asp:ScriptManager>
Add 2 button controls(1 for xml another one for json)
Add 2 div/table elements for display xml and json data.
as shown below
for XML DATA
<asp:Button CssClass="buttonStyle" ID="Button1" runat="server" Text="Call Cross Domain WCF Service XML" title="Call Cross Domain WCF Service XML returning complex object"
OnClientClick="javascript:calling_WCF_in_JavascriptXML()" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
<div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
id="wcf_ajax_response"
runat="server">
(POX) Plain Old XML Response from WCF Service
<table border="1">
<thead style="font-weight: bold;">
<tr>
<td>Age</td>
<td>Contry</td>
<td>EmailID</td>
<td>FirstName</td>
<td>LastName</td>
<td>ProfileID</td>
<td>ZIPCode</td>
<td>JoinedDate</td>
</tr>
</thead>
<tbody id="resTable"></tbody>
</table>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
for JSON Data
<asp:Button CssClass="buttonStyle" ID="Button2" runat="server" Text="Call Cross Domain WCF Service JSON" title="Call Cross Domain WCF Service JSON returning complex object"
OnClientClick="javascript:calling_WCF_in_JavascriptJSON()" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
JSON Response from WCF Service
<table border="1px">
<thead style="color:green;font-size:1.6em;border-width:thick;border-color:red;">
<tr>
<td>ProfileID</td>
<td>FirstName</td>
<td>LastName</td>
<td>Age</td>
<td>JoinedDate</td>
<td>EmailID</td>
<td>ZIPCode</td>
<td>Contry</td>
</tr>
</thead>
<tbody id="x"></tbody>
</table>
<div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
id="resTableJSON"
runat="server">
No JSON Response
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Now we need to creating WCF Rest Service in javascript. Note. ScriptManager will generate proxy class in OnPrerender itself.
Here we need to create ServiceContract in javascript.
Calling cross domain WCF service for XML Response
function calling_WCF_in_JavascriptXML() {
try {
//Create a WCF Service in javascript
var proxy = new SP.IProfileService();
//note NameSpace is Empty.
//Calling WCF methods in javascript.
proxy.GetAllProfilesAsXML(onSuccessXML, OnFailedXML, null);
}
catch (error) {
alert(error.message);
}
}
function onSuccessXML(result) {
var dom = new DOMParser();
var xmldoc=dom.parseFromString(result,'text/xml');
var childNodes = xmldoc.childNodes[0];
var ProfileNodes = childNodes.childNodes;
for (i = 0; i < ProfileNodes.length; i++)
if (ProfileNodes[i].tagName == "Profile") {
var j = 0;
var resTable = document.getElementById("resTable");
resTable.insertRow(i);
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Age")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Country")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("EmailID")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ProfileID")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ZIPCode")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("JoinedDate")[i].childNodes[0].nodeValue;
}
return;
}
function OnFailedXML(result) {
alert(result+'Failed');
}
Calling cross domain WCF service for JSON Response
function calling_WCF_in_JavascriptJSON() {
try {
//Create a WCF Service in javascript
var proxy = new SP.IProfileService();
//note NameSpace is Empty.
//Calling WCF methods in javascript.
// proxy.s
proxy.GetAllProfilesAsJSON(onSuccessJSON, OnFailedJSON, null);
}
catch (error) {
alert(error.message);
}
}
function onSuccessJSON(result) {
var str = "<table border='2'>";
if (Array.isArray(result)) {
for (var i = 0; i < result.length; i++) {
var dt = new Date(result[i].JoinedDate.toString());
str += "<tr>";
str += "<td>" + result[i].ProfileID + "</td>";
str += "<td>" + result[i].FirstName + "</td>";
str += "<td>" + result[i].LastName + "</td>";
str += "<td>" + result[i].Age + "</td>";
str += "<td>" + dt.getFullYear() + "/" + dt.getDate() + "/" + dt.getDay() + "</td>";
str += "<td>" + result[i].EmailID + "</td>";
str += "<td>" + result[i].ZIPCode + "</td>";
str += "<td>" + result[i].Country + "</td>";
}
str += "</tr>";
str += "</table>";
document.getElementById('resTableJSON').innerHTML = str;
}
}
function OnFailedJSON(result) {
alert(result+'failed');
}
Run the Application.
OUTPUT
Click on "Call Cross Domain WCF Service XML"
Click on "Call Cross Domain WCF Service JSON"
This example explains how to consume complex object returned by WCF Rest Service as XML and JSON, and also How to parse XML in javascript & How to parse JSON object in javascript. and display as formatted HTML content.
Complete Source Code
Delete IService1.cs and IService1.svc
Step 2) Add WCF Service .name it as"ProfileService"
- IProfileService.cs(Service Contract file)
- ProfileService.cs(Service Implementation file)
- ProfileService.svc(Link between above 2 , & Here we specify Hosting Factory for creating ScriptEnabled WCF Service).
- GetAllProfilesAsXML
- GetAllProfilesAsJSON
[ServiceContract(Namespace="SP")]
public interface IProfileService
{
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Xml)]
List<Profile> GetAllProfilesAsXML();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
List<Profile> GetAllProfilesAsJSON();
}
ProfileService.cs Implementation file for above 2 contracts
public class ProfileService : IProfileService
{
private List<Profile> profiles = new List<Profile>();
public List<Profile> GetAllProfilesAsXML()
{
BuildProfile();
return profiles;
}
public List<Profile> GetAllProfilesAsJSON()
{
BuildProfile(); return profiles;
}
private void BuildProfile()
{
if (profiles.Count == 0)
{
profiles.Add(new Profile { Age = 21, Country = "USA", EmailID = "jhon@gmail.com", FirstName = "jhon", LastName = "Peter", ProfileID = 1, ZIPCode = "94086-2422", JoinedDate = new System.DateTime(1998, 1, 12) });
profiles.Add(new Profile { Age = 18, Country = "USA", EmailID = "macy@yahoo.com", FirstName = "macy", LastName = "William", ProfileID = 2, ZIPCode = "67897-2422", JoinedDate = new System.DateTime(2000, 11, 1) });
profiles.Add(new Profile { Age = 28, Country = "UK", EmailID = "alex@gmail.com", FirstName = "alex", LastName = "Samuel", ProfileID = 3, ZIPCode = "STHL 1ZZ", JoinedDate = new System.DateTime(2002, 10, 9) });
profiles.Add(new Profile { Age = 35, Country = "UK", EmailID = "bearns@gmail.com", FirstName = "beans", LastName = "Jessica", ProfileID = 4, ZIPCode = "AA9A 9AA", JoinedDate = new System.DateTime(2004, 10, 12) });
profiles.Add(new Profile { Age = 36, Country = "INDIA", EmailID = "prasad@gmail.com", FirstName = "prasad", LastName = "kanuturi", ProfileID = 5, ZIPCode = "110011", JoinedDate = new System.DateTime(1990, 1, 2) });
}
}
}
[DataContract]
public class Profile
{
[DataMember]
public int ProfileID { get; set; }
[DataMember]
public String FirstName { get; set; }
[DataMember]
public String LastName { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public DateTime JoinedDate { get; set; }
[DataMember]
public String EmailID { get; set; }
[DataMember]
public String ZIPCode { get; set; }
[DataMember]
public String Country { get; set; }
}
ProfileService.svc here we specify hosting Factory name. This is very important
<%@ ServiceHost
Language="C#"
Debug="true"
Service="WcfService1.ProfileService"
CodeBehind="ProfileService.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
Web.config file we need to enable crosssitescripting=true and help page.
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<!-- for help page -->
<endpointBehaviors>
<behavior name="myServiceEndPoint">
<webHttp helpEnabled="true" defaultBodyStyle="Bare" faultExceptionEnabled="true"/>
<enableWebScript/>
</behavior> </endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="WcfService1.ProfileService">
<endpoint address="" contract="WcfService1.IProfileService" binding="webHttpBinding" behaviorConfiguration="myServiceEndPoint"></endpoint>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="myrestBinding" crossDomainScriptAccessEnabled="true">
</binding>
</webHttpBinding>
</bindings>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="True">
<security mode="None"></security>
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Help Page located at http://localhost:26678/ProfileService.svc/help
Click on GET for GetAllProfilesAsJSON, u will get as shown below
Click on GET for GetAllProfilesAsXML, u will get as shown below
for cross domain WCF service, Binding Should be WebHttpBinding. Hosting Factory must be System.ServiceModel.Activation.WebScriptServiceHostFactory.
Once WCF Service creation is done.
Create A Empty Web Site using ASP.NET C#
Select .NET 4.5 and Empty Web Site
Add new item -> select Web form name it as Default.aspx
Add ScriptManager and reference the Service Path in that
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
<Services>
<asp:ServiceReference Path="http://localhost:26678/ProfileService.svc" />
</Services>
</asp:ScriptManager>
Add 2 button controls(1 for xml another one for json)
Add 2 div/table elements for display xml and json data.
as shown below
for XML DATA
<asp:Button CssClass="buttonStyle" ID="Button1" runat="server" Text="Call Cross Domain WCF Service XML" title="Call Cross Domain WCF Service XML returning complex object"
OnClientClick="javascript:calling_WCF_in_JavascriptXML()" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
<div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
id="wcf_ajax_response"
runat="server">
(POX) Plain Old XML Response from WCF Service
<table border="1">
<thead style="font-weight: bold;">
<tr>
<td>Age</td>
<td>Contry</td>
<td>EmailID</td>
<td>FirstName</td>
<td>LastName</td>
<td>ProfileID</td>
<td>ZIPCode</td>
<td>JoinedDate</td>
</tr>
</thead>
<tbody id="resTable"></tbody>
</table>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
for JSON Data
<asp:Button CssClass="buttonStyle" ID="Button2" runat="server" Text="Call Cross Domain WCF Service JSON" title="Call Cross Domain WCF Service JSON returning complex object"
OnClientClick="javascript:calling_WCF_in_JavascriptJSON()" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
JSON Response from WCF Service
<table border="1px">
<thead style="color:green;font-size:1.6em;border-width:thick;border-color:red;">
<tr>
<td>ProfileID</td>
<td>FirstName</td>
<td>LastName</td>
<td>Age</td>
<td>JoinedDate</td>
<td>EmailID</td>
<td>ZIPCode</td>
<td>Contry</td>
</tr>
</thead>
<tbody id="x"></tbody>
</table>
<div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
id="resTableJSON"
runat="server">
No JSON Response
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Now we need to creating WCF Rest Service in javascript. Note. ScriptManager will generate proxy class in OnPrerender itself.
Here we need to create ServiceContract in javascript.
Calling cross domain WCF service for XML Response
function calling_WCF_in_JavascriptXML() {
try {
//Create a WCF Service in javascript
var proxy = new SP.IProfileService();
//note NameSpace is Empty.
//Calling WCF methods in javascript.
proxy.GetAllProfilesAsXML(onSuccessXML, OnFailedXML, null);
}
catch (error) {
alert(error.message);
}
}
function onSuccessXML(result) {
var dom = new DOMParser();
var xmldoc=dom.parseFromString(result,'text/xml');
var childNodes = xmldoc.childNodes[0];
var ProfileNodes = childNodes.childNodes;
for (i = 0; i < ProfileNodes.length; i++)
if (ProfileNodes[i].tagName == "Profile") {
var j = 0;
var resTable = document.getElementById("resTable");
resTable.insertRow(i);
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Age")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Country")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("EmailID")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ProfileID")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ZIPCode")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("JoinedDate")[i].childNodes[0].nodeValue;
}
return;
}
function OnFailedXML(result) {
alert(result+'Failed');
}
Calling cross domain WCF service for JSON Response
function calling_WCF_in_JavascriptJSON() {
try {
//Create a WCF Service in javascript
var proxy = new SP.IProfileService();
//note NameSpace is Empty.
//Calling WCF methods in javascript.
// proxy.s
proxy.GetAllProfilesAsJSON(onSuccessJSON, OnFailedJSON, null);
}
catch (error) {
alert(error.message);
}
}
function onSuccessJSON(result) {
var str = "<table border='2'>";
if (Array.isArray(result)) {
for (var i = 0; i < result.length; i++) {
var dt = new Date(result[i].JoinedDate.toString());
str += "<tr>";
str += "<td>" + result[i].ProfileID + "</td>";
str += "<td>" + result[i].FirstName + "</td>";
str += "<td>" + result[i].LastName + "</td>";
str += "<td>" + result[i].Age + "</td>";
str += "<td>" + dt.getFullYear() + "/" + dt.getDate() + "/" + dt.getDay() + "</td>";
str += "<td>" + result[i].EmailID + "</td>";
str += "<td>" + result[i].ZIPCode + "</td>";
str += "<td>" + result[i].Country + "</td>";
}
str += "</tr>";
str += "</table>";
document.getElementById('resTableJSON').innerHTML = str;
}
}
function OnFailedJSON(result) {
alert(result+'failed');
}
Run the Application.
OUTPUT
Click on "Call Cross Domain WCF Service XML"
Click on "Call Cross Domain WCF Service JSON"
This example explains how to consume complex object returned by WCF Rest Service as XML and JSON, and also How to parse XML in javascript & How to parse JSON object in javascript. and display as formatted HTML content.
Complete Source Code
Cross Domain WCF service
IProfileService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IProfileService" in both code and config file together.
[ServiceContract(Namespace="SP")]
public interface IProfileService
{
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Xml)]
List<Profile> GetAllProfilesAsXML();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
List<Profile> GetAllProfilesAsJSON();
}
}
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IProfileService" in both code and config file together.
[ServiceContract(Namespace="SP")]
public interface IProfileService
{
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Xml)]
List<Profile> GetAllProfilesAsXML();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
List<Profile> GetAllProfilesAsJSON();
}
}
ProfileService.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ProfileService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select ProfileService.svc or ProfileService.svc.cs at the Solution Explorer and start debugging.
public class ProfileService : IProfileService
{
private List<Profile> profiles = new List<Profile>();
public List<Profile> GetAllProfilesAsXML()
{
BuildProfile();
return profiles;
}
public List<Profile> GetAllProfilesAsJSON()
{
BuildProfile();
//WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
//String strDatatable = Newtonsoft.Json.JsonConvert.SerializeObject(profiles);
//return WebOperationContext.Current.CreateTextResponse(strDatatable, "application/json;charset=utf-8", System.Text.Encoding.UTF8);// Message.CreateMessage(MessageVersion.Default, "json datatable", message);profiles;
return profiles;
}
private void BuildProfile()
{
if (profiles.Count == 0)
{
profiles.Add(new Profile { Age = 21, Country = "USA", EmailID = "jhon@gmail.com", FirstName = "jhon", LastName = "Peter", ProfileID = 1, ZIPCode = "94086-2422", JoinedDate = new System.DateTime(1998, 1, 12) });
profiles.Add(new Profile { Age = 18, Country = "USA", EmailID = "macy@yahoo.com", FirstName = "macy", LastName = "William", ProfileID = 2, ZIPCode = "67897-2422", JoinedDate = new System.DateTime(2000, 11, 1) });
profiles.Add(new Profile { Age = 28, Country = "UK", EmailID = "alex@gmail.com", FirstName = "alex", LastName = "Samuel", ProfileID = 3, ZIPCode = "STHL 1ZZ", JoinedDate = new System.DateTime(2002, 10, 9) });
profiles.Add(new Profile { Age = 35, Country = "UK", EmailID = "bearns@gmail.com", FirstName = "beans", LastName = "Jessica", ProfileID = 4, ZIPCode = "AA9A 9AA", JoinedDate = new System.DateTime(2004, 10, 12) });
profiles.Add(new Profile { Age = 36, Country = "INDIA", EmailID = "prasad@gmail.com", FirstName = "prasad", LastName = "kanuturi", ProfileID = 5, ZIPCode = "110011", JoinedDate = new System.DateTime(1990, 1, 2) });
}
}
}
[DataContract]
public class Profile
{
[DataMember]
public int ProfileID { get; set; }
[DataMember]
public String FirstName { get; set; }
[DataMember]
public String LastName { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public DateTime JoinedDate { get; set; }
[DataMember]
public String EmailID { get; set; }
[DataMember]
public String ZIPCode { get; set; }
[DataMember]
public String Country { get; set; }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ProfileService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select ProfileService.svc or ProfileService.svc.cs at the Solution Explorer and start debugging.
public class ProfileService : IProfileService
{
private List<Profile> profiles = new List<Profile>();
public List<Profile> GetAllProfilesAsXML()
{
BuildProfile();
return profiles;
}
public List<Profile> GetAllProfilesAsJSON()
{
BuildProfile();
//WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
//String strDatatable = Newtonsoft.Json.JsonConvert.SerializeObject(profiles);
//return WebOperationContext.Current.CreateTextResponse(strDatatable, "application/json;charset=utf-8", System.Text.Encoding.UTF8);// Message.CreateMessage(MessageVersion.Default, "json datatable", message);profiles;
return profiles;
}
private void BuildProfile()
{
if (profiles.Count == 0)
{
profiles.Add(new Profile { Age = 21, Country = "USA", EmailID = "jhon@gmail.com", FirstName = "jhon", LastName = "Peter", ProfileID = 1, ZIPCode = "94086-2422", JoinedDate = new System.DateTime(1998, 1, 12) });
profiles.Add(new Profile { Age = 18, Country = "USA", EmailID = "macy@yahoo.com", FirstName = "macy", LastName = "William", ProfileID = 2, ZIPCode = "67897-2422", JoinedDate = new System.DateTime(2000, 11, 1) });
profiles.Add(new Profile { Age = 28, Country = "UK", EmailID = "alex@gmail.com", FirstName = "alex", LastName = "Samuel", ProfileID = 3, ZIPCode = "STHL 1ZZ", JoinedDate = new System.DateTime(2002, 10, 9) });
profiles.Add(new Profile { Age = 35, Country = "UK", EmailID = "bearns@gmail.com", FirstName = "beans", LastName = "Jessica", ProfileID = 4, ZIPCode = "AA9A 9AA", JoinedDate = new System.DateTime(2004, 10, 12) });
profiles.Add(new Profile { Age = 36, Country = "INDIA", EmailID = "prasad@gmail.com", FirstName = "prasad", LastName = "kanuturi", ProfileID = 5, ZIPCode = "110011", JoinedDate = new System.DateTime(1990, 1, 2) });
}
}
}
[DataContract]
public class Profile
{
[DataMember]
public int ProfileID { get; set; }
[DataMember]
public String FirstName { get; set; }
[DataMember]
public String LastName { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public DateTime JoinedDate { get; set; }
[DataMember]
public String EmailID { get; set; }
[DataMember]
public String ZIPCode { get; set; }
[DataMember]
public String Country { get; set; }
}
}
ProfileService.svc
<%@ ServiceHost
Language="C#"
Debug="true"
Service="WcfService1.ProfileService"
CodeBehind="ProfileService.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
Language="C#"
Debug="true"
Service="WcfService1.ProfileService"
CodeBehind="ProfileService.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
WCF web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="myServiceEndPoint">
<webHttp helpEnabled="true" defaultBodyStyle="Bare" faultExceptionEnabled="true"/>
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="WcfService1.ProfileService">
<endpoint address="" contract="WcfService1.IProfileService"
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="myServiceEndPoint">
<webHttp helpEnabled="true" defaultBodyStyle="Bare" faultExceptionEnabled="true"/>
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="WcfService1.ProfileService">
<endpoint address="" contract="WcfService1.IProfileService"
binding="webHttpBinding" behaviorConfiguration="myServiceEndPoint"></endpoint>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="myrestBinding" crossDomainScriptAccessEnabled="true">
</binding>
</webHttpBinding>
</bindings>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="True">
<security mode="None"></security>
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="myrestBinding" crossDomainScriptAccessEnabled="true">
</binding>
</webHttpBinding>
</bindings>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="True">
<security mode="None"></security>
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
</system.webServer>
</configuration>
ASP.NET WEBSITE
DEFAULT.ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Calling Cross Domain WCF service using Javascript Example</title>
<style type="text/css">
.buttonStyle
{
color:white;
background-color:darkblue;
border-radius:10px;
font-size:1.6em;
}
</style>
<script type="text/javascript">
function calling_WCF_in_JavascriptJSON() {
try {
//Create a WCF Service in javascript
var proxy = new SP.IProfileService();
//note NameSpace is Empty.
//Calling WCF methods in javascript.
// proxy.s
proxy.GetAllProfilesAsJSON(onSuccessJSON, OnFailedJSON, null);
}
catch (error) {
alert(error.message);
}
}
function onSuccessJSON(result) {
var str = "<table border='2'>";
if (Array.isArray(result)) {
for (var i = 0; i < result.length; i++) {
var dt = new Date(result[i].JoinedDate.toString());
str += "<tr>";
str += "<td>" + result[i].ProfileID + "</td>";
str += "<td>" + result[i].FirstName + "</td>";
str += "<td>" + result[i].LastName + "</td>";
str += "<td>" + result[i].Age + "</td>";
str += "<td>" + dt.getFullYear() + "/" + dt.getDate() + "/" + dt.getDay() + "</td>";
str += "<td>" + result[i].EmailID + "</td>";
str += "<td>" + result[i].ZIPCode + "</td>";
str += "<td>" + result[i].Country + "</td>";
}
str += "</tr>";
str += "</table>";
document.getElementById('resTableJSON').innerHTML = str;
}
}
function OnFailedJSON(result) {
alert(result+'failed');
}
function calling_WCF_in_JavascriptXML() {
try {
//Create a WCF Service in javascript
var proxy = new SP.IProfileService();
//note NameSpace is Empty.
//Calling WCF methods in javascript.
proxy.GetAllProfilesAsXML(onSuccessXML, OnFailedXML, null);
}
catch (error) {
alert(error.message);
}
}
function onSuccessXML(result) {
var dom = new DOMParser();
var xmldoc=dom.parseFromString(result,'text/xml');
var childNodes = xmldoc.childNodes[0];
var ProfileNodes = childNodes.childNodes;
for (i = 0; i < ProfileNodes.length; i++)
if (ProfileNodes[i].tagName == "Profile") {
var j = 0;
var resTable = document.getElementById("resTable");
resTable.insertRow(i);
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Age")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Country")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("EmailID")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ProfileID")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ZIPCode")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("JoinedDate")[i].childNodes[0].nodeValue;
}
return;
}
function OnFailedXML(result) {
alert(result+'Failed');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
<Services>
<asp:ServiceReference Path="http://localhost:26678/ProfileService.svc" />
</Services>
</asp:ScriptManager>
<asp:Button CssClass="buttonStyle" ID="Button1" runat="server" Text="Call Cross Domain WCF Service XML" title="Call Cross Domain WCF Service XML returning complex object"
OnClientClick="javascript:calling_WCF_in_JavascriptXML()" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
<div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
id="wcf_ajax_response"
runat="server">
(POX) Plain Old XML Response from WCF Service
<table border="1">
<thead style="font-weight: bold;">
<tr>
<td>Age</td>
<td>Contry</td>
<td>EmailID</td>
<td>FirstName</td>
<td>LastName</td>
<td>ProfileID</td>
<td>ZIPCode</td>
<td>JoinedDate</td>
</tr>
</thead>
<tbody id="resTable"></tbody>
</table>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button CssClass="buttonStyle" ID="Button2" runat="server" Text="Call Cross Domain WCF Service JSON" title="Call Cross Domain WCF Service JSON returning complex object"
OnClientClick="javascript:calling_WCF_in_JavascriptJSON()" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
JSON Response from WCF Service
<table border="1px">
<thead style="color:green;font-size:1.6em;border-width:thick;border-color:red;">
<tr>
<td>ProfileID</td>
<td>FirstName</td>
<td>LastName</td>
<td>Age</td>
<td>JoinedDate</td>
<td>EmailID</td>
<td>ZIPCode</td>
<td>Contry</td>
</tr>
</thead>
<tbody id="x"></tbody>
</table>
<div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
id="resTableJSON"
runat="server">
No JSON Response
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Calling Cross Domain WCF service using Javascript Example</title>
<style type="text/css">
.buttonStyle
{
color:white;
background-color:darkblue;
border-radius:10px;
font-size:1.6em;
}
</style>
<script type="text/javascript">
function calling_WCF_in_JavascriptJSON() {
try {
//Create a WCF Service in javascript
var proxy = new SP.IProfileService();
//note NameSpace is Empty.
//Calling WCF methods in javascript.
// proxy.s
proxy.GetAllProfilesAsJSON(onSuccessJSON, OnFailedJSON, null);
}
catch (error) {
alert(error.message);
}
}
function onSuccessJSON(result) {
var str = "<table border='2'>";
if (Array.isArray(result)) {
for (var i = 0; i < result.length; i++) {
var dt = new Date(result[i].JoinedDate.toString());
str += "<tr>";
str += "<td>" + result[i].ProfileID + "</td>";
str += "<td>" + result[i].FirstName + "</td>";
str += "<td>" + result[i].LastName + "</td>";
str += "<td>" + result[i].Age + "</td>";
str += "<td>" + dt.getFullYear() + "/" + dt.getDate() + "/" + dt.getDay() + "</td>";
str += "<td>" + result[i].EmailID + "</td>";
str += "<td>" + result[i].ZIPCode + "</td>";
str += "<td>" + result[i].Country + "</td>";
}
str += "</tr>";
str += "</table>";
document.getElementById('resTableJSON').innerHTML = str;
}
}
function OnFailedJSON(result) {
alert(result+'failed');
}
function calling_WCF_in_JavascriptXML() {
try {
//Create a WCF Service in javascript
var proxy = new SP.IProfileService();
//note NameSpace is Empty.
//Calling WCF methods in javascript.
proxy.GetAllProfilesAsXML(onSuccessXML, OnFailedXML, null);
}
catch (error) {
alert(error.message);
}
}
function onSuccessXML(result) {
var dom = new DOMParser();
var xmldoc=dom.parseFromString(result,'text/xml');
var childNodes = xmldoc.childNodes[0];
var ProfileNodes = childNodes.childNodes;
for (i = 0; i < ProfileNodes.length; i++)
if (ProfileNodes[i].tagName == "Profile") {
var j = 0;
var resTable = document.getElementById("resTable");
resTable.insertRow(i);
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Age")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("Country")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("EmailID")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ProfileID")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("ZIPCode")[i].childNodes[0].nodeValue;
resTable.rows[i].insertCell(j);
resTable.rows[i].cells[j++].innerHTML = xmldoc.getElementsByTagName("JoinedDate")[i].childNodes[0].nodeValue;
}
return;
}
function OnFailedXML(result) {
alert(result+'Failed');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
<Services>
<asp:ServiceReference Path="http://localhost:26678/ProfileService.svc" />
</Services>
</asp:ScriptManager>
<asp:Button CssClass="buttonStyle" ID="Button1" runat="server" Text="Call Cross Domain WCF Service XML" title="Call Cross Domain WCF Service XML returning complex object"
OnClientClick="javascript:calling_WCF_in_JavascriptXML()" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
<div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
id="wcf_ajax_response"
runat="server">
(POX) Plain Old XML Response from WCF Service
<table border="1">
<thead style="font-weight: bold;">
<tr>
<td>Age</td>
<td>Contry</td>
<td>EmailID</td>
<td>FirstName</td>
<td>LastName</td>
<td>ProfileID</td>
<td>ZIPCode</td>
<td>JoinedDate</td>
</tr>
</thead>
<tbody id="resTable"></tbody>
</table>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button CssClass="buttonStyle" ID="Button2" runat="server" Text="Call Cross Domain WCF Service JSON" title="Call Cross Domain WCF Service JSON returning complex object"
OnClientClick="javascript:calling_WCF_in_JavascriptJSON()" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Block" UpdateMode="Conditional">
<ContentTemplate>
JSON Response from WCF Service
<table border="1px">
<thead style="color:green;font-size:1.6em;border-width:thick;border-color:red;">
<tr>
<td>ProfileID</td>
<td>FirstName</td>
<td>LastName</td>
<td>Age</td>
<td>JoinedDate</td>
<td>EmailID</td>
<td>ZIPCode</td>
<td>Contry</td>
</tr>
</thead>
<tbody id="x"></tbody>
</table>
<div style="color:green;font-size:1.6em;border-width:thick;border-color:red;"
id="resTableJSON"
runat="server">
No JSON Response
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
Happy Coding ...
No comments:
Post a Comment