Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

May 27, 2011

Implement AJAX & Backend Services

Way to implement Ajax:
  • use Sys.Net.WebRequest to call backend service (ASPX, ASMX or ASHX)
  •  server side ajax enabled WCF service
    • use asp:servicereference to emit script proxy for client script to call WCF service
  • client side Ajax Library:  http://microsoftpdc.com/Sessions/FT29
  • Ajax Toolkit (server side Ajax controls)


What backend services to call?






WCF or ASMX?
  • WCF/REST: Async friendly, abstract complexity (serialization/deserialization etc) web friendly, Binary, format of choice (Json/xml/image etc.), end to end
  • Session Http cookies
  • SOAP based web service asmx: overhead, xml only, computing distribution

Mar 25, 2010

WCF and SharePoint (index)

Recently I have posted a serial blogs on WCF services and their integration with SharePoint 2010. They are not step by step type "How to", but instead they assume at least some basic understandings on WCF and SharePoint as well as Visual Studio 2010.

Host WCF Services in SharePoint 2010

As a completion of my post, how to Host WCF Data Service in SharePoint 2010  I am here to show how to host WCF services and WCF RESTful services inside SharePonit 2010.

Create a empty SharePoint project and add an ISAPI mapped folder

Add "new item" and select "WCF Service"
when creating WCF service inside a SharePoint Project, you won't get .svc file, only one interface and one class file:
  • Add this attribute to implemntation class:
    • [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
  • specify Namespace in the interface, otherwise your proxy script class will get a namespace like org.ui
    • [ServiceContract(Namespace="")]
Create a service.svc file under ISAPI folder
  • As it is hosted in SharePoint, we have to use non-configuation approach (Factory) to define endpoint (see here for details). In other word, no web.config modification, in stead use Factory in .svc file as follows:
  • <%@ServiceHost Language="C#" Debug="true" Service="SharePointHostWCF.WCFService, SharePointHostWCF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d82e2e229c90dd3e" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"% >
  • WebScriptServiceHostFactory will define a endpoint callable from Javascript.
create a sharepoint ajax enabled application page to test your WCF service
  • see my other post on how to make ajax enabled sharepoint page;
  • use asp:servicereference to load a service proxy class in runtime;
  • in javascript,you should be able to get a IWCFService object and use it to call service methods;
  • you can't call it from another iis web application, since it is treated as a cross site scripting (CSS);

What if you want to implement a RESTful Service?
  • add this attribute to interface method:
    • [WebGet(UriTemplate = "Hello", ResponseFormat = WebMessageFormat.Xml)]
  • change Factory in service.svc to WebServiceHostFactory. otherwise you get the following errors:
  •   Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'.
  • you can now test service from browser in a RESTful way;
  • if you choose Json for ResponseFormat instead, browser won;t be able to display, instead asking you to download. You should test it in Fiddler;
  • still want to consume this RESTful service from script, see my other post for detail;

Mar 24, 2010

Enable WCF services consumable for Ajax JavaScript

In the previous post, I show how to call ajax-enabled WCF from Javascript, and how to consume WCF RESTful service from Ajax JavaScript. What if you already created a WCF service using WCF Service template, and want it to be consumed in a JavaScript? It turns out the only change is in web.config:

When you create a WCF service in Visual Studio, its endpoint in web.config is defined as:

<endpoint address="" binding="wsHttpBinding" contract="AjaxWcFService.IWCFSoapService" >
<identity > <dns value="localhost" > </identity >
</endpoint >

replace it with the followings:

< endpoint address="" binding="webHttpBinding"
behaviorConfiguration="ScriptFriendly"
contract="AjaxWcFService.IWCFSoapService" >
< /endpoint >

and define endpoint behavior as follows:

<behavior name="ScriptFriendly" >
<enableWebScript / >
</behavior >

This WCF service now becomes ajax-enabled.

Call Ajax-enabled WCF Services from Ajax JavaScript

After Creating an Ajax-enabled WCF service in Visual Studio 2010, the following endpoint behavior is specified for this service:

<behavior name="AjaxWcFService.AjaxWCFSVCAspNetAjaxBehavior"><enableWebScript/>
</behavior >

which will allow ajax library (see here to register ajax library)  to inject a proxy at runtime for script client to use and call this service once it is referred in an ASP:Service:
<Services > <asp:ServiceReference Path="~/AjaxWCFSVC.svc" / >
</Services >



So the script can just make a call like the follwoings.
                  var svc = new AjaxWCFSVC();
                  svc.DoWork(onSuccess, onFail, null)

Related Post: Call WCF RESTful service from Ajax JavaScript
                     Call WCF service from Ajax JavaScript

Mar 22, 2010

Consume SharePoint 2010 RESTful service from Ajax JavaScript

I ever post on how to Consume REST in SilverLight to bind SharePoint 2010 List Data. In this post, I will show how to consume SharePoint RESTful service in AJAX Javascript for databinding in a sharepoint application page (no authenticaion needed in this scenario).

First create an application page:

this should be easy to do by using Visual Studio 2010 sharepoint template, or you can simple manually creat one (see here).

Add AJAX library support into the application page:

This should be done simply by linking AJAX library from CDN. But as AJAX libray currently still in beta, you have to download MicrosoftAjax.js (this is needed only for dataview control used in the code) from here , add this file into your project file and then use ScriptManagerProxy to load it to the page (I think this should be a bug in beta). You can't use ScriptManger since sharepoint master page already has one.

The script should look like:


Invoke Ajax Call by using WebRequest, a traditional way

by default, RESTful service response with ATOM feed (XML formated). In order for AJAX to work, the request header should be specified as accepting application/json. This is important otherwise deserialization will fail.



In Callback, bind data with control:


with HTML makeup looks like this:


A even more elegant way, but not working yet... and it works!

In PDC 2009, a very elegant way was demoed by Stephen Walther to achieve this data binding with WCF service, but I can't make it work with listdata.svc. I think the fact that listdata.svc returns by default XML data rather than JSON might be the reason behind. I don;t know how to change it when create a dataview in the following code: Actually Ajax dataview Call use Json format as I discover this from Fiddler.



In fiddler, I can see listdata.svc get called, but it returns code 400, implying bad data format?
The problem was, url for fetchOperation in the code above ws illegal, and unfortunately this illegal url is tolerated in IE broswer.  Fiddle gave a misleading error code 400 due to whitespace.See Lessons learned from using Fiddler.

With this approach, http markup is clean without custom elements, and this is achieved by a custom item render as follow:









Related Posts:

Call Ajax-enabled WCF Service from Ajax JavaScript
Call WCF Service from Ajax JavaScript


Great Resources:

http://blogs.pointbridge.com/Blogs/monnette_jeff/Pages/Post.aspx?_ID=24

http://blogs.visoftinc.com/archive/2009/04/28/ASP.NET-4.0-AJAX-Preview-4-Client-Templates.aspx

Mar 4, 2010

REST Service, Json and XML

REST support 2 native data formats: Json and XML. XML is default and is browser friendly with Atom feed. Json is programming friendly, particularly Ajax friendly because of its small dataload and easy deseralization. Either way, REST is very web friendly as it uses http like syntax which is easy for script to make call or for user to browse.

A common misconcept is Json is required for Ajax. Ajax can work with any format, but Json has significant advantage over XML. When making an Ajax call to a REST service, the request header can be specified with an "Accept:" format, but it is just a "wish", and will be granted only when the service has a capability for the requested format. So the following code will return error when the service doesn't response with Json data:


var data = response.get_responseData();
data = eval("(" + data + ")")

Also keep in mind, Visual Studio (2010 RC) doesn't provide java script intellisense for REST response data. In contrast, Ajax-enabled WCF service can emit a script proxy (via asp:serviceRefernce), so it has full intellisense support, and has built-in serialization/deserialization support with default Json format.

Create a WCF RESTful service in Visual Studio 2010

Visual Studio 2010 (RC) doesn't have a template specifically for RESTful service. The WCF service template will create a WCF SOAP service, but it can be converted into REST service as follow:



Edit web.config:



The web.config entities for REST is quite different from those for SOAP, but very similar to those for Ajax-enabled WCF Service, the only difference is, Ajax-enabled WCF has "enableWebScript":








Add WebGet attribute to all methods in contract interface, like:


[WebGet(UriTemplate = "Hello", ResponseFormat = WebMessageFormat.Json)]



Add this attribute for REST implementation class:


[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]


Test in Fiddler:

By now, it is a functioning WCF RESTful service, and response json format data. You can test it in Fiddler.


Great References:
http://www.ajaxlines.com/ajax/stuff/article/return_json_from_ajaxenabled_wcf_service.php
http://www.robbagby.com/rest/rest-in-wcf-blog-series-index/

Feb 26, 2010

ScriptManager & Scripts from CDN such as AJAX Library

With roll out of ASP .Net AJAX Library, adding ajax capabilities in scripts is nothing but a link to CDN:


<script src="http://ajax.microsoft.com/ajax/beta/0911/Start.debug.js" type="text/javascript" > </script >

It will load all scripts needed for ajax development regardless of .Net Framework. However if asp:ScriptManager is also used, it will load script from framework. That will cause some visioning problems, and it is the case for sharepoint pages(this seemingly only happens if usng dataview control). SharePoint 2010 master page has ScriptManager embedded and is used by both site pages and application pages . As currently in beta, the workaround is to locally include MicrosoftAjax.js (see here for details).

Another cool thing about ScriptManage or ScripManagerProxy is its asp:serviceReference, it will inject a proxy script class on fly to allow client script to call backend ajax enabled WCF service.