This blog is to have the tutorial on creating WCF web services and connecting the web services in Jquery Mobile application.
Pre-Requisite
- Download and install the WCF restful services template , from online template screen from VS2010 ( Search for WCF restful template inside the visual studio).
- Create the database “EmployeeDB”
- create a table with the name , below is the query to create the table
CREATE TABLE [dbo].[Employees]( [EmployeeId] [int] IDENTITY(1,1) NOT NULL, [EmployeeName] [varchar](150) NOT NULL, [EmployeeEmail] [varchar](150) NOT NULL, [EmployeePhone] [varchar](50) NOT NULL ) ON [PRIMARY]
- Insert the data into the table
WCF Service Part
Create a Restful web service by selecting the REST template
Delete the SampleItem.cs and Services.1 CS file which are generated automatically
Create a new SVC file and name it EmployeeServices.svc
Create a new Class file ClsEmployeeListing.cs
This is the section to create the getter and setters for the data members
using System.Runtime.Serialization; using System; [DataContract] public class ClsEmployeeListing { //string varClinicID; //string varClinicName; //string varClinicAddress; //string varclinicOperatingHours; [DataMember] public string EmployeePhone { get; set; } [DataMember] public string EmployeeEmail { get; set; } [DataMember] public string EmployeeName { get; set; } [DataMember] public string EmployeeID { get; set; } public ClsEmployeeListing(Int32 Eid, string Ename, string Eemail, string Ephone) { EmployeeID = Eid.ToString(); ; EmployeeName = Ename; EmployeeEmail = Eemail; EmployeePhone = Ephone; } }
EmployeeServices.svc
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Data.SqlClient; namespace EmployeeDemo { [System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)] // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "EmployeeServices" in code, svc and config file together. public class EmployeeServices : IEmployeeServices { public List<ClsEmployeeListing> GetEmployeeListing() { List<ClsEmployeeListing> mylist = new List<ClsEmployeeListing>(); using (SqlConnection conn = new SqlConnection("server=WINDOWS7PC\\SQLEXPRESS;database=EmployeeDB;Persist Security Info=True;User ID=Appuser;Password=Prasad78;")) { conn.Open(); string cmdStr = String.Format("Select EmployeeID,EmployeeName,EmployeeEmail,EmployeePhone from Employees"); SqlCommand cmd = new SqlCommand(cmdStr, conn); SqlDataReader rd = cmd.ExecuteReader(); if (rd.HasRows) { while (rd.Read()) { mylist.Add(new ClsEmployeeListing(rd.GetInt32(0), rd.GetString(1), rd.GetString(2), rd.GetString(3))); } } conn.Close(); } return mylist; } } }
Interface part
IEmployeeServices.cs
This is the section to add the web service method and URITemplate ( this is the name which we will be calling in web service URL)
EG:
URITemplate : EmployeeList
Service name : EmployeeServices.svc
Web service call would be :http://localhost:8008/EmployeeServices.svc/EmployeeList
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.ServiceModel.Web; namespace EmployeeDemo { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IEmployeeServices" in both code and config file together. [ServiceContract] public interface IEmployeeServices { [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "EmployeeList")] List<ClsEmployeeListing> GetEmployeeListing(); } }
Web Config Part
Add the necessary configuration in web.config on the cross domain and service definition
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0"/> <customErrors mode="Off"/> </system.web> <system.serviceModel> <services> <service name="EmployeeDemo.EmployeeServices" behaviorConfiguration="EmpServiceBehaviour"> <endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpBindingJsonP" contract="EmployeeDemo.IEmployeeServices" behaviorConfiguration="web"/> <host> <baseAddresses> <add baseAddress="http://localhost:4671"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="EmpServiceBehaviour"> <serviceMetadata httpGetEnabled="true"/> <dataContractSerializer ignoreExtensionDataObject="true" maxItemsInObjectGraph="123456"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="web"> <dataContractSerializer ignoreExtensionDataObject="true" maxItemsInObjectGraph="123456"/> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <bindings> <webHttpBinding> <binding name="webHttpBindingJsonP" crossDomainScriptAccessEnabled="true"/> </webHttpBinding> </bindings> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <!--<httpErrors errorMode="Detailed"></httpErrors>--> </system.webServer> </configuration>
Build the solution and deploy the web service in the IIS .
Jquery Mobile Part
Create a new filename Index.html
Add the Jquery mobile library reference , reference can be in local or can be referenced to the jquery mobile library from CDN
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" /> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
In this tutorial i have a created three section header , content , footer. In the jquery mobile each section is identified by the attribute “data-role” in the DIV tag.
<div data-role="page"> <div data-role="header"> <h1>Header</h1> </div><!-- /header --> <div data-role="content"> <ul data-role="listview" data-inset="true" data-theme="b"id="EmployeeList"> </ul> </div><!-- /content --> <div data-role="footer"> <h4>Footer</h4> </div><!-- /footer --> </div><!-- /page --> </body>
Create a Ajax call to call our web services
$.ajax("http://localhost:8008/EmployeeServices.svc/EmployeeList",
Add the Ajax call in the document ready function
<script> $(document).ready(function () { $.ajax("http://localhost:8008/EmployeeServices.svc/EmployeeList", { beforeSend: function (xhr) { // $.mobile.showPageLoadingMsg(); }, complete: function () { // $.mobile.hidePageLoadingMsg(); }, contentType: 'application/json', dataType: 'jsonp', jsonp: 'callback', type: 'GET', error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(xhr.responseText); //alert(thrownError); }, success: function (data) { var result = data.GetEmployeeListingResult; $.each(result, function (index, output) { $('#EmployeeList').append('<li> <a href=EmployeeDetails.html?EmployeeID=' + output.EmployeeID + '>' + output.EmployeeName + ' </a> .....</li>'); }); $('#EmployeeList').listview('refresh'); } }); }); </script>
Out put of the the web service would in json format , to bind the data from web service to the list , use the $.each(result, function (index, output) { and give the reference to the UL list
$.each(result, function (index, output) { $('#EmployeeList').append('<li> <a href=EmployeeDetails.html?EmployeeID=' + output.EmployeeID + '>' + output.EmployeeName + ' </a> .....</li>'); }); $('#EmployeeList').listview('refresh');
For any queries , please email the query to vishnuprasad (dot) ramakrishnan (at) <yahoo> (dot) (com)
The source code for this tutorial has can be downloaded from here
Your blog is gr8
Gr8 work
I know this web page gives quality based articles and additional information, is
there any other site which offers such information in quality?
How to write the javascript if mobile part is done with Phonegap.I want to do the same(listview).. but with phonegap ..
‘ ‘ + output.EmployeeName + ‘ …..’… How to write this Part if i don’t have a EmployeeDetails.html file..My WCF service is running good..Plss Help me…
hi Phone gap is plugin to to talk to the device features,. Its not for UI rending and design. If am not wrong you should use the notmal html or jquery mobile for UI
Thanks in support of sharing such a fastidious thought, article
is good, thats why i have read it completely
Hello there! This post couldn’t be written much better! Reading through this post reminds me of my previous roommate! He continually kept talking about this. I will forward this post to him. Fairly certain he’s going
to have a great read. Thank you for sharing!
You really make it seem really easy along with your presentation but I in finding
this topic to be really one thing which I feel I’d never understand. It seems too complex and very extensive for me. I’m
taking a look forward on your next post, I will try to get
the dangle of it!
Hello my loved one! I wish to say that this
post is amazing, great written and come with approximately all important infos.
I’d like to see extra posts like this .
Very good post! We are linking to this particularly great article on our site.
Keep up the great writing.
Hello There. I found your blog using msn. This is a very well written
article. I will make sure to bookmark it and come back to read more of your useful
information. Thanks for the post. I will definitely return.
Hi, Neat post. There’s an issue with your site in internet explorer, would check this? IE nonetheless is the market leader and a large element of folks will miss your fantastic writing due to this problem.
An impressive share! I have just forwarded this onto a co-worker who has been
conducting a little research on this. And he actually ordered me dinner simply because I stumbled
upon it for him… lol. So allow me to reword this…
. Thank YOU for the meal!! But yeah, thanks for spending
the time to talk about this subject here on your internet site.
Hey! I’m at work browsing your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the fantastic work!
I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get set up? I’m assuming having a
blog like yours would cost a pretty penny?
I’m not very web savvy so I’m not 100% positive.
Any recommendations or advice would be greatly appreciated.
Cheers
Thanks for sharing your thoughts. I truly appreciate your efforts and I will be waiting for your next
write ups thanks once again.
Greetings, I do think your blog could be having web browser compatibility issues.
Whenever I look at your web site in Safari, it looks fine however, when opening in I.
E., it has some overlapping issues. I merely wanted to give you a quick heads up!
Other than that, fantastic blog!
Great article…. Thanks a ton…
whoah this blog is excellent i like studying your posts.
Keep up the good work! You realize, lots of persons are searching round for this
info, you can aid them greatly.
We are a group of volunteers and opening a new scheme in our community.
Your website provided us with valuable information
to work on. You have done an impressive job and our whole community will be thankful to you.
I am truly glad to glance at this blog posts which includes
tons of valuable information, thanks for providing these
kinds of information.
WOW just what I was looking for. Came here by searching for mortgage loan modification
I loved as much as you will receive carried out right here.
The sketch is attractive, your authored subject matter stylish.
nonetheless, you command get got an nervousness over that you
wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often
inside case you shield this increase.
Thanks for finally talking about >Step by Step Tutorial
– Restful WCF Web Service and Jquery Mobile WR Vishnu <Loved it!
Great post. I was checking constantly this blog and I am impressed!
Very useful info particularly the last part 🙂 I care for such information a lot.
I was looking for this certain info for a long time.
Thank you and good luck.
Source code links are not working..
Do you mind if I quote a couple of your articles
as long as I provide credit and sources back to your weblog?
My blog is in the exact same niche as yours and my
users would genuinely benefit from some of the information you provide here.
Please let me know if this ok with you. Thank you!
I blog quite often and I really appreciate your content. Your article has truly peaked my interest.
I will take a note of your website and keep checking for new details
about once per week. I opted in for your RSS feed as well.
Appreciating the time and effort you put into your website and detailed information you present.
It’s good to come across a blog every once in a while that isn’t the same outdated rehashed material.
Excellent read! I’ve bookmarked your site and I’m including your RSS feeds to
my Google account.
Can someone tell me if this set up will work for a web service that is not hosted locally? I am going to be putting my web service on an internal server at my company and need to make sure that my mobile application will still be able to communicate with my service. If not, can someone point me in the direction of tips to make it compatible in that way?
Quality content is the main to be a focus for the visitors to pay a visit the website,
that’s what this web page is providing.
Good Article
Greetings from California! I’m bored at work so I decided to browse your site on my iphone during lunch break.
I love the information you present here and can’t wait to take
a look when I get home. I’m surprised at how fast your blog loaded on my
phone .. I’m not even using WIFI, just 3G .. Anyhow, awesome blog!
Hello colleagues, how is everything, and what you want to say concerning this article,
in my view its actually awesome in support of me.
You have a decent number of movies coming
up each week and so you have a good number of options at hand.
Today, the 50s hit cat eye frame and 70s popular round shaped frames are
gaining popularity. com is one of the most popular Website for Selling Bollywood
Sarees:.
It’s really a nice and useful piece of information. I’m satisfied that
you shared this helpful info with us. Please stay us up to date like this.
Thank you for sharing.
Que jogos com casino irá você escolher atualmente? http://spottydog06.bottompics.s14.deinprovider.de/test.php?a%5B%5D=casino%20royale%201967%20%28%3Ca%20href%3Dhttp%3A%2F%2Fcassinodigital.com%2Fbingo%2F%3Ecassinodigital.com%3C%2Fa%3E%29
Assim você tem como como ganhar dinheiro na гede.