What Is Wcf Service Android

The problem is that WCF relies on run-time bytecode emission to generate proxy classes for your web service interfaces (specifically, through the System.Runtime.Remoting namespace). Bytecode emission is not supported on iOS, because all code has to be compiled ahead of time on that platform. Here I am creating the WCF Rest service to insert some data into database using POST method. So my database designs as follows. Android Training in Chennai app.

WCF is a tool often used to implement and deploy a service-oriented architecture (SOA). It is designed using service-oriented architecture principles to support distributed computing where services have remote consumers.Clients can consume multiple services; services can be consumed by multiple clients. The main issue with WCF is, its tedious and extensive configuration. It is not open source but can be consumed by any client that understands xml. It can be hosted with in the applicaion or on IIS or using window service. To use WCF as WCF Rest service you have to enable webHttpBindings. I'm using ksoap2 to call WCF Service from android with WSHttpBinding. When I set the security mode to none in web.config file of my WCF Project (.NET) for wsHttpBinding, my android code work fine. But when I remove this security mode tag, as it WCF Service with wsHttpBinding, by default uses security mode MESSAGE, my code does not work.

It seems processing XML is too heavy for mobile devices. Android did not provide any tool to help consuming SOAP web service. But as Android bundled with org.apache.http and org.json packages, it is relative simple to consume RESTful WCF services.

What Is Wcf Service Android Manager

The following sections describe the steps to create RESTfule WCF services and the Android client to consume the services.

First, I created a service contract with two GET and one POST operations. Since the Android client will transfer data in JSON objects, I specify JSON as request and response format. In order to support more than one parameter, I set BodyStyle to WrappedRequest.

Next, I defined the composite object will be transferred between server and Android client. It is simple but enough to prove we will be able to transfer complex objects.

Now, expose the WCF service via webHttp behavior in web.config.

It you are using Visual Studio's Development Server to test the WCF service, you may need to deploy the service to IIS.This is due to the Development Server only serve request from local machine, and the Android client won't be able to access the service hosted on it.

Further, if you are using host name (e.g. computer name) in the URL of the service, you may have to setup the DNS in you device or emulator, so that it can resolve the host name.Simply go to Settings -> Wireless Control -> Mobile Networks -> Access Point Names, click on the one that is in use, fill in Proxy and Port with your DNS server.

Now, I have my WCF service ready, and I am going to build the Android client to consume the WCF service.

During initialization, the Activity will invoke IVehicleService.GetPlates method to populatethe Spinner. When the Load Vehicle button is clicked, the vehicle will be loaded from the IVehicleService.GetVehicle methodand the EditText views will be populated. On the other hand, Save button will wrap the data enteredand post to IVehicleService.SaveVehicle method.

The code the initialize the UI I created.

The refreshVehicles method will be invoked when the activity is resumed or a new vehicle is saved.It send a GET request to the WCF service and retrieves a list of plates in JSON string, and the response string is parsed by JSONArray.

The onLoadVehicleClick method is the event handler for Load Vehicle button.Just like refreshVehicles method, It send a GET request to the WCF service and retrieve the vehicle information by plate number.But instead of JSONArray, it used JSONObject to parse the response data, since the WCF service is returningan vehicle object.

When Save button is clicked, onSaveVehicleClick method will be invoked.It simply gather all text fields into a JSONObject and post it to the WCF service.Noticed that the all the data was wrapped into an object named vehicle, WCF will passthis object as parameter vehicle.

Finally, add the internet permission into AndroidManifest.xml, to allow the sample application access WCF service.

And the demo is ready to go.

Service

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

  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.

What

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.

Wcf Service Android

Interface class would be decorated with [ServiceContact] 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.
Wcf
  • 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.

.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.

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.

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”.

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”.

C# Wcf Web Service

What Is Wcf Service Android

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.

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.

What Is Wcf Service Android Tv Box

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.

C# Wcf Service

Summary

What Is Wcf Used For

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.