What Is Wcf Service Android



  1. Android gRPC protoc Service Client Example. ServiceStack is an open source framework designed to be an alternative to the WCF, ASP.NET MVC, and ASP.NET Web API.
  2. WCF stands for Windows Communication Foundation. It is basically used to create a distributed and interoperable Application. WCF Applications came into the picture in.Net 3.0 Framework. This is a framework, which is used for creating Service oriented Applications.

On Android, the code to consume a WCF web service with a Stream parameter: It’s really simple once you get the right JARs. Android evidently doesn’t ship with the full complement of Apache HTTP libraries in JAVA. So you will need to download the following two and link them in your Eclipse project: apache-mime4j-0.6.1.jar. The WCF question was also discussed over at Hacker News, where one developer said: 'wcf works under core (at least most of it), core 3.0 + wcf + windows desktop shim actually makes everything under wcf working again.' To which, another developer said: 'Most of it is not good enough. I don't want to be the one stating on RFP 'it kind of works.'

Baudouin Giard
SoftFluent

September 2011

Summary: This article demonstrates how to consume mobile-enabled WCF services that were generated by CodeFluent Entities in an Android application.

Contents
I. Introduction
II. General Overview
III. The Mobile Application

This technical article illustrates how to consume, in an Android application, mobile-enabled WCF services as generated in the Generating Mobile-Enabled WCF Services Using CodeFluent Entities technical article.

This article will start by doing a brief overview of common mobile application design patterns, before an example implementation.

Please note that a complete working solution is provided with this example, so feel free to download and tour the code.

RESTful applications are amongst the most common application types in mobile environments; consequently it is easy to find documentation regarding this type of development on the internet.
The goal of our mobile applications is to show how to retrieve and how to create information on the server. Basically, in each application, we will:

  • Connect to the Employee web service
  • Display a list of all the employees of the company
  • Allow the end-user to fill in a form matching the HolidayRequest entity
  • Send this holiday request by connecting to the HolidayRequest web service.

A. Common mobile design patterns

If this is not your first mobile development you are probably already familiar with the typical design patterns for mobile platforms. Here are a few characteristics of a mobile app that differ from a desktop app and that a mobile developer must always keep in mind all along his work:

  • the network might become unavailable at any time and queries might not come to an end,
  • the application could be unexpectedly paused (e.g. by an incoming phone call, or by pressing the home button),
  • a mobile CPU is slow and consumes a lot of battery life, so it must be solicited as less as possible,
  • battery life is strategic and must be saved,
  • data transfers must be avoided as much as possible, for battery savings as much as for billing savings,
  • the application must scale on the largest panel of devices possible, so it must save memory to run on old phones.

In this article, I won’t necessarily respect all those patterns, since I’m not a confirmed mobile developer, and also in order to keep my code as easy to understand as possible. I will mainly focus on the communication part of the RESTful application, rather than mixing up things with advanced programming unrelated to the subject. You can see those developments as proof-of-concepts; it is up to you to implement all the right design patterns to make your enterprise-class business applications.

B. Generic RESTful design pattern

Here is what could be, in my opinion, a rather good design pattern for a RESTful application. I inspired from Virgil Dobjanschi’s Google I/O lecture. Dobjanschi explains that the intuitive way to implement a REST communication - create a worker thread within the UI thread - is a bad idea, since the UI thread might be interrupted anytime. He also gives some good ways to implement properly the REST architecture on a mobile device.
Here is the pattern I used:


1. Presentation layer

The presentation will be in charge of displaying our list of employees, let the user fill in a form corresponding to a holiday request, and trigger the upload of this request to our service.
The best way to do this is to implement a data binding between an in-memory model and the user interface.

2. Model layer

The model layer is in charge of keeping the application consistent and the code we develop as structured as possible. It allows manipulating the same structure of data on our mobile platform that the one we designed in CodeFluent Entities.

3. Persistence layer

The persistence layer is optional. Most of the time, we do not implement this layer on desktop smart-client applications because we assume that the network connection is permanent. In mobile phone development, even if a lot of applications are working this way, we should not go with this hypothesis for the many reasons that I exposed in the Common mobile design patterns section.
This layer is in charge on providing the application with intermediary persistence storage between the UI and the Data Access layer. When the application is killed, the data stays on the phone and can be instantly displayed at a next launch. This is the little “plus” that make some mobile applications better than others.
In our example, it would be especially good because our application downloads a list of the company’s employees, a data that is unlikely to change a lot: this means it doesn’t need to be downloaded each time the application is launched.

4. Data access layer

The Data Access layer is the part that interests us. This layer is in charge of getting the information remotely and converting it to model objects. It is also in charge of sending back to the service newly created objects. The Data Access layer may be itself divided in two sub-layers: a web client and a serialization processor.
The client will do the networking part and the processor will be in charge of serializing and deserializing the parameters and the results of the network transactions.


If you want to have a better understanding on how to develop RESTful applications on mobile devices, I invite you to watch the video of the Google I/O lecture linked above (~60’) or have a look to the slides of this presentation.

Wcf

I tried to stick the most I could to the first design pattern Virgil Dobjanschi presents in its Google I/O lecture:


The only difference is that in my case the Service is connected to the Content Provider instead of the Processor.

A. Presentation

In Android development, a presentation view is called an Activity. In my case, I configured the Android Virtual Device as a tablet, which comes with a 10” screen. It allows me to have only one Activity in my application.
Designed in the file res > layout > main.xml, the view matches our HolidayRequest entity definition:



From top to bottom in the UI we have:

What
  • A refresh button
  • A spinner containing the list of our employees
  • A textbox to indicate the number of days of the requested vacation
  • Two date pickers for the begin date and the end date
  • A spinner to choose the type of vacation
  • A textbox to write a comment
  • A save button

The controller of this view is the MainActivity class of the com.softfluent.mobileholidays package. It just contains event handlers for the buttons “Refresh List” and “Send my query”. Those handlers trigger the web service and receive the results. It also contains a SimpleCursorAdapter ensuring the data binding between the employee content provider and the employee spinner list.

B. Model

C# wcf web service

I had to create Java classes for each of my entities. I put them in the package com.softfluent.mobileholidays.model. They are really simple classes matching the model we designed in CodeFluent Entities, except for the relations (don’t forget what I mentioned above about lazy-loading).

Tip: You can use your SoftFluent.MobileHolidays.ConsoleApp project to see what a serialized entity instance looks like.

However, we have to add Android-specific code to this base model.

According to the diagram above we will create a HolidayRequest from the Activity and pass it down to the Service, in Android we need it to implement the Parcelable interface which is a form of binary serialization.

In order to respect the chosen pattern, we will implement the optional persistence layer. We will use an Android ContentProvider to store our Employee objects. We must add a nested Employees class to our Employee class, implementing the BaseColumns interface:

Employee.javaCopy Code

See the Content Providers section of Android developer guide if you are not familiar with data storage on Android.


C. Persistence

Like I said, we will implement a persistence layer in our Android application. Android provides the developer with a generic concept of content providers that give a standard way to retrieve, store and manipulate data from applications.


I chose to implement a SQLLite Database based Content Provider to store the Employee list because this is the most common way to do it. The “employees” spinner in the Activity is connected to this Content Provider by a SimpleCursorAdapter which provides a binding between the view and the data.


It represents a lot of code, but pretty much everything is generic and easily reusable from one model to another just by changing the name of the fields. I invite you to consult the code of the file: EmployeeContentProvider.java. This a basic implementation of a Content Provider, such as those you can easily find on the web.

D. Data Access

Here is the part in which we will consume our services.


The Service Helper is just a class implementing a few static methods to create an Intent object to start the Service. A Service is, on Android, a long-running background operation.

Our Service inherits the IntentService class, which is a base class designed for services like ours.

WebService.javaCopy Code

Our Service receives its parameters in its “extras” Bundle:

  • A ResultReceiver to which it will send the result of the web service transaction,
  • Depending on the 'action' specified in the Intent, a HolidayRequest object.

Note that our service is the part of our model dealing with the Employees Content Provider. On the diagram, it is specified that the Processor would do it. It just made more sense to me at the time I coded it not to delegate the storage operations to the processor: it makes the processor less complicated, and easier to replace if we need someday to change the serialization format.

The Processor class is just a set of static methods, each corresponding to a service operation. The Processor delegates the network interaction to the RestClient class, and just serializes and deserializes the objects. The JSON serialization is handled by the Google Gson library.

Note that we created a custom JSONSerializer for the dates, because the default serialization of dates by Gson did not match the one used by the services in the first place (remember that a date is not a standard type in Json):

JSONSerializer<Date>Copy Code

Last, the most important: the Rest client. I used the Apache Http Client, as recommended in the Google I/O lecture. Note this is standard Android development: the org.apache.http package is embedded in Android SDK.

This is a very simple implementation. A better way to do it would be to create a RestClient[EntityName] class for each entity, implementing methods corresponding to each method exposed by the web services.

Yet, this illustrates how to consume WCF services generated by CodeFluent Entities in an Android application.

Generating Mobile-Enabled WCF Services Using CodeFluent Entities
Consuming Generated WCF Services in Windows Phone
Consuming Generated WCF Services in iOS

What Is Wcf Used For

Custom Authentication in WCF

Windows Communication Foundation (WCF) is a .Net framework to build and develop service applications and also enhances to support multiple different protocols than its traditional “web service” counterpart like https, IPC, MSMQ, TCP etc.

WCF provides various security modes to create a secure communication channel when communicating with the client server.

Transfer Security Level

  1. Message security mode: This security mode provides end to end security which is transported through insecure communication like HTTP.
  2. Transport security mode: This security mode provides point to point security by transferring messages over communication protocols like TCP, IPC, Https.
  3. Mixed transfer security mode: This mode provides transport security for message privacy and it uses message security for security credentials.
  4. Both security mode: This mode is more robust than others and uses both transport and message-level security where WCF uses the secure channel with the encrypted message but it overloads the performance.

None: In this mode, the WCF service doesn’t use any authentication.

Message Security Level

What Is Wcf Ria Services

  1. None: No client authentication is performed in this level, the only message is encrypted for security.
  2. Windows Authentication: Client must provide windows credential to authenticate itself along with encryption of the message.
  3. Certificate: This mode uses the client certificate to authenticate client along with message encryption.
  4. UserName: This mode uses UserName and Password to authenticate client along with message encryption.
  5. Issued Token: This mode uses tokens to authenticate client along with message encryption.

In this article, we’ll understand custom authentication with Message level security with wsHttpBinding and UserName security level and the custom authorization with custom attribute.

Create New WCF Service

To create new WCF service:

Open visual studio → select New Project → select WCF template → select WCF service Application

This will create an interface class and svc files automatically.

Interface class would be decorated with [ServiceContact] Windows 7 pro oa dell. which describes the operations a service exposes to the client or another party.

The Methods that are decorated with [OperationContract] attribute are exposed to the client otherwise not.

Now configure <services> under <system.servicemodel>

Set endpoint address, binding type and contract under <service> section.

  • After completing all the steps try to browse service1.svc through visual studio in the browser. We will be able to access service.
  • Now we would implement user authentication in our service by using an abstract class UserNamePasswordValidator.
  • To implement abstract class UserNamePasswordValidator. Add reference to System.IdentityModel and create new class with suitable name, inherit UserNamePasswordValidator and override its Validate(string,string) method.
  • In the Validate () method, we can write any custom logic according to our requirement to validate the user credentials passed to WCF service by the client.
  • Also few changes to be done in web.config apart from overriding validate method in the service.
  • Add binding to message mode security and set client credential type to UserName in <system.serviceModel> in web config.
What Is Wcf Service Android

.Net developers can choose any client credential type according to our requirement but for this example, we are using UserName client credential type.

To make authentication of WCF service more secure use server certificate for authentication.

If certificate is available include it in WCF server otherwise we can also create self-signed certificate from IIS.

Follow these steps to create self-signed certificate from IIS:-

Step 1 – Open IIS Manager select and double-click “Server Certificates” From “IIS” pane.

Step 2 – Select “Create Self Signed Certificate”

Step 3 – Provide suitable name for certificate and select certificate store for the new certificate then click “Ok” to create certificate.

Step 4 – After clicking “OK” New certificate is created as highlighted below.

To make WCF service use our custom authentication make some changes in <behavior> section of <serviceBehaviors> in web.config.

Also, add the created self-signed certificate in “serviceCredentials” section.

As shown in above web.config file set attribute “cusomUserNamepasswordValidatorType” to WcfServiceDemo(service name).clientauthentication(class in which we have implemented our custom authentication code).WcfServiceDemo(service name).

Custom Authorization in WCF

Authorization is the process to get access and control to the WCF service by identifying clients that call the service and what operations a client can access.

After authenticating the user we should authorize the user to determine that which operations logged in user can access of WCF service.

WCF supports three ways to Authorize the user:-

  • Role-based Access – In this method access to the user for operations on the service is based on the user’s role.
  • Identity based Access/Claims based access – In this method access to the user is given based on its claims that are retrieved by user’s credentials when authenticating the user. This approach also used with issue token authentication.
  • Resource based Access – In this method, Windows Access Control Lists (ACLs) use the identity of the caller to determine access rights to the resource.

What Is Wcf Service Application

There are multiple ways to determine the user’s role:-

  • Windows Groups – In this method, we can use built-in Windows groups such as Administrators or Power Users or we can create your own Windows groups.
  • Custom Roles – In this method, we can create roles that are specific to the application, like admin, users.
  • ASP.NET Role Management – In this method, ASP.Net developers can use the ASP.NET role provider and user roles that have defined for a Web site.

WCF Pipeline

  • Injecting a Parameter Inspector in the WCF pipeline at the client or service side will allow validating any of the parameters that are going to be sent to the service or are received at the service end.
  • Parameter Inspector intercepts the incoming and outgoing requests and after processing the requests it extracts the parameters and inspects it.
  • The parameter inspector is the same for both server side and client side.
  • In WCF, Parameter inspector is implemented by implementing the interface ‘IparameterInspector’.

Implementation of Custom Authorization in WCF Service using ParameterInspector

Implement custom “BusinessServiceAccess” class by deriving “System.Attribute” class which contains “CheckAccessRights” method to check the access rights of the authenticated user in the WCF service.

  • We will use “CheckAccessRights” method to check the user authorization when it tries to call WCF service by extracting the parameters that are passed by the caller.
  • For intercepting the requests made by the caller and extracting the parameters from the request we will create class “MyParameterInspector” which implements “IparameterInspector” interface.
  • MyparameterInspector” class implements two methods “BeforeCall” and “AfterCall”.
  • AfterCall method executes after client calls are returned and beforservice responses are sent.
  • BeforeCall method executes before client calls are sent and after service responses are returned.

In “BeforeCall” method we have executed “CheckAccessRights” method if any attribute is present in the caller request and also to determine which roles are accessible by the caller by checking attributes.

Now that we have defined our parameter inspector we need to tell our WCF service that we are going to use it. To implement this we have to inject our “MyParameterInspector” class to the server side.

What

In the above code snippet we have used interface “IEndPointBehavior” which requires to implement the following four methods:-

  • AddBindingParameters: This method is used to pass custom data at runtime to enable bindings to support custom behavior.
  • ApplyClientBehavior: This method is used modify, examine or insert extensions to a client dispatcher in a client application.
  • ApplyDispatchBehavior: This method is used to modify, examine or insert extensions to operation-wide execution in a service application.
  • Validate: This method is used to confirm that an OperationDescription meets specific requirements. This can be used to ensure that an operation has a certain configuration setting enabled, supports a particular feature and other requirements.

In the method “ApplyDispatchBehavior” we have injected our parameter inspector in “dispatchOperation.ParameterInspectors”.

What Is Wcf Service Android Manager

To extend the behavior of the class “CultureEndpointBehavior” shown in above code snippet we need to implement new class which is derived from abstract class “BehaviorExtensionElement”.

In the above class two methods are overridden of abstract class.

  • CreateBehavior” method – Creates the instance of the extended behavior. As shown in above code snippet we have returned object of “CultureEndPointBehavior” class. The class that we have created above to inject parameterinspector to our WCF Service. Refer to fig (III).
  • BehaviorType” property returns the type of extended behavior. As shown in above code snippet we have returned type of (CultureEndPointBehavior).
  • Now to add the extension in WCF service add section “<extension></extension>” in web.config file

Our custom “parameterinspector” is now ready for use and service can authorize the caller using the Attribute.

Wcf Web Services

The only thing that remains is to decorate one or more of the exposed operation on the service contract with the newly created “BusinessServiceAccess” attribute.

Please note here that we are passing two parameters in BusinessServiceAccess attribute and this is the advantage over the traditional Authorize attribute approach where we could pass additional parameters which we could use at the time of checking rights. Refer CheckAccessRights function in BusinessServiceAccessAttribute class.

Summary

In this article we understand how to implement custom authentication and authorization in WCF service. In first part we understood about the authentication and also implemented custom authentication in WCF. In later part we have discussed about the authorization in WCF and also implemented custom authorization using Parameter Inspector.