Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

How to Create WCF REST Service For Mobile App

805 views

Published on

How to Create WCF REST Service For Mobile App

Published in: Education
  • Be the first to comment

  • Be the first to like this

How to Create WCF REST Service For Mobile App

  1. 1. How to Create WCF REST Service For Mobile App Suttipong Kullawattana
  2. 2. Introduction • First allow me to say that this is my first article on c-sharpcorner.com. • In the era of smartphones and cloud throne, mobile applications now require not only beautiful interfaces and good quality but also the ability to synchronize data between devices using server-side technologies. If you have a plan to build applications like social apps, financial app. • You should care about technologies helping in building data service as soon as possible. • Currently there are many technologies in the .NET Framework to help you build services but in this article we will go into the details of the procedure to create a WCF REST Service that can be used on the mobile app or other client as desktop app, web app.
  3. 3. Web Services An inter-operable services hosted & up-running over the web which could be accessed by different independent clients like web browser There are 2 types Web Services • REST (Representational State Transfer) • SOAP (Simple Object Access Protocol)
  4. 4. Here is the index for web services tutorials including both SOAP (JAX-WS) and REST (JAX-RS) • JAX-RS (REST based web services) • Apache CXF – REST • JBoss RestEasy • Jersey 2.x • Spring Restful • JAX-WS (SOAP based web services) • Apache Axis 2 Reference Implementation • Apache CXF – SOAP • Metro Reference Implementation
  5. 5. Method Name and Soap Action: Namespace: URL:
  6. 6. Reference • http://www.benchresources.net/web-services/
  7. 7. Create WCF REST service
  8. 8. • In the first part we will create a WCF service that returns data in JSON format by 5 steps detailed as follows. 1. In Visual Studio 2013 we create a new web project.
  9. 9. 2.Then add a new item to the project and select WCF Service Item.
  10. 10. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace Tungnt.NET.WCFRestDemo { [ServiceContract] public interface IWCFRestDemo { [OperationContract] [WebGet(RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)] [WebInvoke(Method="GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string GetMessage(); [OperationContract] [WebInvoke(Method="POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string PostMessage(string userName); } }
  11. 11. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace Tungnt.NET.WCFRestDemo { public class WCFRestDemo : IWCFRestDemo { public string GetMessage() { return "Welcome to tungnt.net from GetMessage() WCF REST Service"; } public string PostMessage(string userName) { return string.Format("Welcome {0} to tungnt.net from PostMessage() WCF REST Service", userName); } } } 5. In the final step we will implement the interface's functions GetMessage/Post Message as in the following:
  12. 12. Configure WCF REST Service • We've just created the WFC REST service but to use this service in a mobile app we need one more step. The configuration service must return a JSON format instead of the default format SOAP (XML). In this second part we will configure WCF to use webHttpBinding to enable a WCF service that returns JSON format. Let's edit the web.config as follows. • Add an endpoint used webHttpBinding and restBehavior (helpEnabled = true to serve the development process as will be explained below) as in the following:
  13. 13. <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="restBehavior"> <webHttp helpEnabled="true"/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <services> <service name="Tungnt.NET.WCFRestDemo.WCFRestDemo"> <endpoint name ="RESTEndPoint" contract ="Tungnt.NET.WCFRestDemo.IWCFRestDemo" binding ="webHttpBinding" address ="rest" behaviorConfiguration ="restBehavior"/> </service> </services> </system.serviceModel>
  14. 14. Conclusion In this article I showed you how to create a WCF REST service that returns JSON data to be used in web applications (via JavaScript) or mobile applications such as iOS, Android, Windows Phone app. JSON is a format that is very popular today in the world of Web/Mobile because of the simplicity, lightweight and high portability so understanding how to use it has become a strong demand for developers.
  15. 15. Reference • http://www.c-sharpcorner.com/UploadFile/nikitakova/how-to-create- wcf-rest-service-for-mobile-app/
  16. 16. CREATE RESTful WCF Service API Using POST: Step By Step Guide
  17. 17. • In my previous article, I tried to explain about WCF Restful service using HTTP Get method. This works well as long as you are sending small data as information to the service. But if want to deliver huge data, HTTP GET Method is not a good choice. In this article, we will create one WCF RESTFul POST API. I will also try to explain why and where to use POST method. Introduction
  18. 18. Why to use POST, not GET? • When I write any WCF service, I always use POST. The reason is the advantage of POST over GET. Using HTTP POST method, you can almost achieve everything which you can achieve from GET. Despite this, you will get some additional feature if using POST. We might say that "GET" is basically for just getting (retrieving) data whereas "POST" may involve anything, like storing or updating data, or ordering a product, or sending E-mail, etc.
  19. 19. POST • Easy Character Encoding using application/x-www-form-urlencoded • No Proxy by default so always actual data from web server • Data length can be restricted by webserver, not by browser GET • Character encoding will reduce the amount of data that can be used because of URL encoding entities (i.e. three Japanese characters are converted to this: %26%2312454%3B%26%2312455%3B%26%2312502%3B) • Running an HTTP request with GET can be cached on your web browser or a configured proxy server • Maximum URL length is 2,083 characters in Internet Explorer (see MaxClientRequestBuffer: Use POST instead of GET to send large amounts of data in request)
  20. 20. • and lot more... • Extremely long URLs are usually a mistake. URLs over 2,000 characters will not work in the most popular web browser. Sending long information via URL is not a good way of implementation and also it has many restrictions, i.e., max length of URL, information format, bla bla bla. For example, Internet Explorer has a limitation implemented at 2083 characters. URI is meant to be readable not to send information. • So if you are writing any REST service and your information is long enough, better to choose POST instead of GET method. • In this article, I am going to create WCF Restful service using POST method and access it using HTTP Request. So we will have client and server both in this example code. I am creating one service which accepts HTTP Post XML request and response request data in XML format.
  21. 21. Reference • https://www.codeproject.com/Articles/201901/CREATE-RESTful-WCF- Service-API-Using-POST-Step-By
  22. 22. Simple Demo WCF Web Services
  23. 23. Topic • WCF - Introduction • What is a Service Contract, Operation Contract and a Data Contract • A word about WCF configuration • Look at our project defining simple Business Functionality • Expose the above Business Functionality via a WCF Web Service • Employ WCF Test Client to test out our newly created Web Service • Create a Proxy Client for our new Web Service • Test our above created proxy client • Final Thoughts
  24. 24. WCF - Introduction • WCF stands for Windows Communication Foundation. • WCF is a framework designed for supporting message-based communication on both client and server. • WCF supports multiple transports like SOAP over HTTP (our example Web Service is based on this), TCP, named pipes, MSMQ and some others. • WCF supports multiple encodings like XML, text, binary and a few other options. • Currently, to name some technologies that employ WCF are Windows Workflow, Silverlight, etc.
  25. 25. What is a Service Contract, Operation Contract and a Data Contract In WCF, contracts are used to define functionality. Contracts basically are formal agreements between a client and a service to define a platform-neutral and standard way of describing what a service will and can do. WCF defines 4 types of contracts: • Service Contracts • Operation Contracts • Data Contracts • Fault Contracts We will be looking at the first three contracts in this article.
  26. 26. • Service Contracts define the capabilities of a web service. It is essentially a Interface Contract that binds the application (business functionality - business operations being exposed) to provide a fixed set of operations (as stated in the interface contract) to the sources consuming the web service. It simply describes the client-callable operations, or methods, that are available on the service endpoint, and are exposed to the outside world. In terms of code: • All we need to do is to code and decorate a interface with ServiceContract attribute. • This interface will have members (methods) that will be made available as part of the Tweet Service to the outside world.
  27. 27. • Operation Contracts on the other hand defines the methods of the service that are accessible to the external systems. It is integral to the above created interface for Service Contract. Members marked with Operation Contract attribute in the Service Contract Interface are the ones which are exposed to external systems. Members not decorated with Operation Contract attribute in Service Contract Interface are not exposed as part of the web service. • In terms of code: It can be applied only on methods. It is used to decorate methods which belongs to Service Contract interfaces.
  28. 28. Implementing interface ITweetService.cs in class TweetService.svc.cs. Now, after implementing & building the project - go to TweetService.svc, right click and select view in browser.
  29. 29. Note - You can test all the other Service Methods as well using WCF test client. I will leave the remaining service methods for you to play with on your own.
  30. 30. In TweetClientDataService implementation (above screen- shot), I am using reference to TweetServiceClient. TweetServiceClient is providing us with a lot of functionality under the covers! Example: TweetServiceClient - is doing all the serialization and de-serialization behind the scenes for request and response SOAP envelopes. It is also opening the connection for us and sending and receiving the information on our behalf over the network. So, it has really abstracted away a lot of complications that one has to face when communicating through RPC SAOP style Web Services!
  31. 31. Test Our Above Created Proxy Client Wow! here we are... we have almost made it through! I have created a Program Class in the TweetClient project and have introduced some Command Prompt interface to interact with our Tweet Web Service operations. I will leave the Program Class in TweetClient Project for you to explore as it is fairly simple. To run the Program Class in TweetClient Project, follow the screen shot below:
  32. 32. Reference • https://www.codeproject.com/Articles/884992/Simple-Demo-WCF- Web-Services
  33. 33. Simple Demo WCF AJAX Web Service
  34. 34. Introduction • WCF AJAX Service- Introduction • Look at our project TweetBL defining simple Business Functionality • Creating a WCF AJAX Service project (for TweetBL Project's Business Functionality) • Running the default WCF AJAX Service project • Building WCF AJAX Service project (for TweetBL Project's Business Functionality) • Running the WCF AJAX Service project (now with our Business Code) • Switching from JSON to XML for WCF AJAX Web Service • Creating WCF AJAX Web Service Client • Testing WCF AJAX Web Service using our Service Client • Final Thoughts
  35. 35. WCF AJAX Service - Introduction • "Asynchronous JavaScript and XML" is a web development technique that supports creating an interactive website with rich client presentation. AJAX facilitates retrieval of data from a server: asynchronously - what this means is AJAX invokes a new request (for data) without disrupting the client's current view! • AJAX enables us to fetch Server-Side content dynamically and makes it look like client-side dynamic content... the user is subjected to no interruptions whatsoever! while AJAX does this dynamic server-side content fetching under the covers. Once this fetching of data form server is done, client's current view is updated with the retrieved data. • Finally, the main purpose of AJAX is to improve speed, usability and performance of a web application. • A business example could be a Rating Functionality on a Web Page. When a user rates something - their rating of say 5 is stored into the database without the need to refresh or reload the web page. The user just selects the 5 stars and goes on by his/her business on the web page whilst AJAX works on the background vigorously to please its masters by doing the needful. • Lastly, AJAX employs the below listed technologies (but is not limited too) and mechanisms to make a developers life easier: - JavaScript - XML - Asynchronous requests to server
  36. 36. As soon as we add the AJAX service, a few changes were made to our project. A few references and libraries from .NET were added to our project. We will cover a few interesting bits! Our Web.config file has also been modified! Let us have a look at that...
  37. 37. • A behaviour has been added to our Web.config file (above screen-shot) to enable Web Scripting for our project. An <endpointBehavior> has been added which will enable listening of request calls for web services. <enableWebScript /> behaviour maps Operation Contracts to specific URIs. <enableWebScript /> also creates a JavaScript proxy file for us for our services which we will have a look at shortly. <enableWebScript /> also enables a few ways for us to serialize data. We have options between JSON or XML to serialize data. The important thing to note here is that all this is part of Web API. • Notice the binding used "webHttpBinding". This allows our web service clients to communicate with our service using HTTP get and post verbs. Note only the methods decorated with Operation Contract attribute are exposed as services. • Along with the above changes, we are also provided with a template file for our TweetService.svc class.
  38. 38. Here unlike: SOAP over HTTP Web Services, we do not have an interface class. The Service Contract and Operation Contract attributes are directly defined on the class. Also, take a note of AspNetCompatibilityRequirements attribute: this attribute indicates that this service integrates with the ASP.Net pipeline. Now that we have created a project and have had a quick tour of what we have been given by default to work with, let's start building the real thing!
  39. 39. Building WCF AJAX Service Project (for TweetBL Project's Business Functionality) Time to build our real AJAX Service and remove DoWork method! Let us tap into TweetBL Project - ManageTweet.cs: this class has all the business code that we would need to manage a Tweet. We will expose all these methods as an AJAX Web Service. In TweetService.svc of Tweet.WCFService.AJAX project, we have included a reference to ManageTweet.cs of TweetBL Project and as demonstrated in the screen-shot above, all we do is pass the call that we receive for any TweetService.svc method to ManageTweet class methods to do the actual work. Simply put, all we do in our service class is call the business class to do the actual job.
  40. 40. We got an error back - WCF passed us some options that we can use to get more details regarding the issue that occurred on the server! Example: In the above screen-shot, we are advised to turn on includeExceptionDetailInFaults so let's do that...
  41. 41. Here is the screen-shot of the Web.config file after making the above mentioned changes.
  42. 42. Fortunately, for me DeleteTweet was called before making the call to GetTweets! Tweet with Id = 2 has been successfully deleted. Quick look at UpdateTweet method in TweetClient.aspx: I have commented the code for Create and Delete Tweet as I just want to focus on Update and Get.
  43. 43. Reference • https://www.codeproject.com/Articles/887611/Simple-Demo-WCF- AJAX-Web-Service
  44. 44. CONSUMING SOAP WEB SERVICES FROM ANDROID
  45. 45. Introduction • Though SOAP based web-services are rare in these days, but there are lots of old companies whose web-services are still SOAP-based. If anyone wants to consume those services from Android, it is very important to know the procedure of consuming SOAP-based webservice. There are lots of tutorials on consuming RESTful web- services with better explanation, but there are a few tutorials on consuming SOAP web-services with a clear explanation. • In this article, we will learn how to consume SOAP web services from Android. Before starting code, we have to collect some information:
  46. 46. • SOAP_ACTION • METHOD_NAME • NAMESPACE • URL • Parameter List • Request XML/ SOAP_BODY/ SOAP_MESSAGE (for Nested Parameters and Multiple Namespaces)
  47. 47. • Now, the question is how can we get these information? if your client or service provider give you all the information, you won’t need anything. But if they don’t, then follow the process given below: • Suppose, you have to consume the data from this service: http://www.w3schools.com/webservices/tempconvert.asmx • This is the URL!! • Click on it, you can see a link named “Service Description” and a list of Method Name(s). So, we can get the METHOD_NAMEs from here. Now, click on the “Service Description”.
  48. 48. Reference • http://www.nascenia.com/consuming-soap-web-services-from-android/ • http://www.javatpoint.com/android-web-service • http://stackoverflow.com/questions/13288993/consuming-wcf-service-in-android-app Android Series • https://github.com/survivingwithandroid/Surviving-with-android • https://github.com/IanDarwin/Android-Cookbook-Examples Android App Service • http://www.erenpinaz.com/blog/post/2016/3/consuming-restful-web-service-android-part-1 • http://www.erenpinaz.com/blog/post/2016/3/consuming-restful-web-service-android-part-2 loopJ HTTP • http://loopj.com/android-async-http/ WCF • http://www.topwcftutorials.net/ • https://nine69.wordpress.com/2010/04/10/wcf-series-เริ่มต้น-begin-i/ • http://www.prandroid.com/2014/04/how-to-communicate-wcf-webservices-in.html
  49. 49. Reference • Test Call Web Service http://www.webservicex.net/new/Home/Index • Test WSDL Web Service http://www.wsdl2code.com/Pages/Example.aspx https://blogs.msdn.microsoft.com/endpoint/2011/05/12/how-to-eliminate- tempuri-org-from-your-service-wsdl/ • How To Test Web Service https://www.codeproject.com/Articles/38839/Test-Your-ASP-NET- WebService-using-SoapUI
  50. 50. Reference WSDL • WSDL URL: http://www.webservicex.com/globalweather.asmx?wsdl • WSDL URL: http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL • WSDL URL: http://www.thomas- bayer.com/axis2/services/BLZService?wsdl • android-with-wcf-services https://wyousuf.wordpress.com/2012/03/01/android-with-wcf- services/
  51. 51. Reference • how-to-get-string-array-with-ksoap2-in-java-android http://stackoverflow.com/questions/7710741/how-to-get-string-array-with-ksoap2-in-java-android • SOAP http://www.thecrazyprogrammer.com/2016/11/android-soap-client-example-using-ksoap2.html • REST http://www.thecrazyprogrammer.com/2016/09/android-restful-web-service-client-example.html • invoke-a-operation-contract-through-web-browser http://stackoverflow.com/questions/10630707/invoke-a-operation-contract-through-web-browser • Android Exchanging Array Data between Java and JavaScript http://www.androidcookbook.com/Recipe.seam?recipeId=4426 http://stackoverflow.com/questions/2250917/passing-a-javascript-object-using-addjavascriptinterface-on-android http://stackoverflow.com/questions/10114993/how-to-pass-json-formatted-data-from-a-webview-to-a-html-page
  52. 52. Reference • Android Special Case http://www.c-sharpcorner.com/uploadfile/88b6e5/how-to-call-web-service-in-android-using-soap/ http://navinsandroidtutorial.blogspot.com/2013/12/android-soap-based-web-services.html http://www.javatpoint.com/android-web-service • OkHTTP http://androidgifts.com/okhttp-android-library-tutorial-library-7/ https://github.com/Android-Gifts/OkHttp-Library-Tutorial https://medium.com/square-corner-blog/okhttp-2-0-6da3fe12c879#.ktap9qg6s https://github.com/pratikbutani/JSONParsingUsingOkHTTP • Upload http://blog.aimanbaharum.com/2016/03/26/android-image-multi-part-upload/ https://github.com/aimanbaharum/android-multipart-upload-demo
  53. 53. Reference • Test HTTP/HTTPS/SSL/Certificate https://httpbin.org/ • GET/POST/PUT/DELETE http://howtoprogram.xyz/2016/10/31/java-rest-client-examples-using- okhttp/ https://github.com/howtoprogram/Java-Examples/tree/master/Java- RESTful-Client-Example • OkHTTP Wiki https://github.com/square/okhttp/wiki/Recipes

×