HTML5 and JQUERY with .NET c# WCF Servcies


If your a .NET Developer like me and you are looking to transition into the wonderful world of mobile development. There is a quick way for you to start your journey towards developing HTML5 applications supported on IOS and Android without having to develop in Java or CoCoa (Objective C). First things first, lets look at what you already know or what your familar with. Data/Content is king, so if your developing an app that is not dyanamically bringing some data to your user, just stop now and close this post.

Lets look at WCF Serves for .NET 4.0. you want starting using these if you are not currently. My suggestion is to set up a DAL (Data Access Layer) for all of your communications to your datasource then consume it through your services. In Visual Studios what you want to do is create a WCF web service, let just start off with the configuration this will kill you if it is not configured right. I know i definetly bit the bullet on this one. List below is an example of mission critical configuration elements, that need to be present in your web.config file to enable JSONP communcations in your webservice:

<system.serviceModel>

    <behaviors>

      <serviceBehaviors>

        <behavior name=ServiceBehavior>

          <serviceMetadata httpGetEnabled=true/>

          <serviceDebug includeExceptionDetailInFaults=true/>

        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>

        <behavior name=EndpBehavior>

          <webHttp helpEnabled=true/>

        </behavior>

      </endpointBehaviors>

    </behaviors>

    <services>

      <service behaviorConfiguration=ServiceBehavior name=thenews>

          <endpoint address=“” binding=webHttpBinding

                    bindingConfiguration=webHttpBindingJsonP

                   contract=“Ithenews

                   behaviorConfiguration=EndpBehavior/>

      </service>

    </services>

    <bindings>

      <webHttpBinding>

        <binding name=webBinding>

          <security mode=Transport>

          </security>

        </binding>

        <binding name=webHttpBindingJsonP crossDomainScriptAccessEnabled=true/>

      </webHttpBinding>

    </bindings>

  </system.serviceModel>

The items that are highlighted are essential for making this all work for you.  The “crossDomainScriptAccessEnabled” will bite you hard if you are trying to have your UI connect to your services.  So make sure you enable it.

Next move over to your Interface  “Ithenews.cs”.  This will be created when you create your service. You will have two files.  The interface which is what is called from application, and the actual class “thenews.cs”.  This i where all your magic is happening.

Your interface should be configured like this:

 

[OperationContract]
[WebInvoke(Method=”GET”,BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = “getNews“)]

List<newsItem> getNews();  (Use List<> or Obervable Collections.  Simple create a class with your return properties in a format that you want deliver, then use the List<> or Observable to create and array of that object.  You can use DataTables and Datasets to create these collections, within your SqldataAdapter or whatever your using to populate the data from its source.)

The WebMessageFormat.Json specifies the format your service is going to give back.  And the UriTemplate is what your url call will be from  your jquery client.  E.G. (http://api.myservices.com/news.svc/getNews)

Writting your method for the  “thenews.cs” is up to you.  (good luck)

Moving to the JQUERY side.   If you dont have it go get it.  Its just a javascript library full of awesomeness to help you develop faster.  You can link to it or you can download it to include in your project.  If I am developing an app, I download it and include it in the project.  Just my preference.  You can get it it here:

http://jquery.com/ (Simple Right ^_^)

After you have the file add it to your html file.

E.G.

<script type=”text/javascript” src=”js/jquery-1.6.4.js”></script>

Final part:

here is your div on your page

<html>

<head>

<title></title>

</head>

<body>

<div id=”myresults”>

</div>

<script type=”application/javascript”>

var webpath=”http://api.myservices.com/news.svc/getNews“;

function loadNews()
{
$.ajax({
url: webpath,
context: this,
crossdomin: true,
dataType: ‘jsonp‘,
success: loadevents,
error:OnError
});
}

var loadevents=function(data)
{

var e=$(“#myresults”);
$(e).html(“<ul>”);

$.each(data, function(i,item)
{
//$(e).append(“<h3>” + item.title+ “</h3>”);

$(e).append(“<li>” + item.url+ “</li>”);

});
$(e).append(“</ul>”);

}

loadNews();  //Go out to get the news on the page reload  If you would like to do this on a frequency, you can wrap it with a setTimeout(“loadNews()”,30000);

</script>

</body>

</html>

Make sure you set your dataType to jsonp and set your success:  is the callback function after it retrieves the data.  After the data is retrieved your can use a jQuery function to iterate throuth the collection like listed above.  By using the classes in your WCF Webservice it ill make it easier for you to grab the field names from the results.

If you have any quetions you can find me at: 

Art Hicks

Chief Executive Officer

Get Connected:

Email:ahicks@ViviScape.com

Web Site: http://www.ViviScape.com

LinkedIn: http://www.linkedin.com/in/arthicks

Advertisements

About Art Hicks

I am Business Owner/Applications Engineer that specializes in providing rich solutions to my clients and colleagues.
This entry was posted in .NET WCF Services, C#, HTML5, jQuery. Bookmark the permalink.

5 Responses to HTML5 and JQUERY with .NET c# WCF Servcies

  1. anup says:

    Its a very nice article.. but how to access a POST (web invoke) method of WCF webservice.

    thanx.

  2. This is can be accomplished by changing your method in the WCF service from GET to POST. This will change service to a POST behavior.

    E.G. :
    [WebInvoke(Method=”POST”,BodyStyle = WebMessageBodyStyle.WrappedRequest,
    ResponseFormat = WebMessageFormat.Json,
    UriTemplate = “getNews”)]

    It really depends on your application, on what you want to allow. This examples was basically created to show how to allow data to be consumed via JSON. it is excellent for delivering feeds.

  3. Rich Chang says:

    Hey Dan,

    I’m trying to get motivated for my first Mobile app using my existing Asp.Net Web Forms Site which also uses jQuery and WCF.
    So, I’m thinking I can create a few HTML5 mobile pages and use my WCF backend.

    Gonna give it a try.

    Thanks, LA Guy

  4. Aps says:

    Hi
    Nice concise article there. I’ve a question. What changes will be needed to the WCF service contracts if i have two clients – one that uses JSON and the other regular windows app?
    thanks

    • Art Hicks says:

      I would recommend setting up a separate endpoint in your WCF, and creating a separate service to handle your JSON responses. This will allow you to apply the appropriate security necessary for your windows app.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s