SlideShare a Scribd company logo
1 of 50
Android Ax App – Part 1–Set up the
intermediate WCF service
December 5, 2011.Net, Android, Ax 2012, Dynamics Ax, JSON, REST, WCFAndroid,AX2012, JSON, REST, WCF
2 Votes
I came across a blog by Joris De Gruyter http://daxmusings.blogspot.com/2011/11/10-minute-app-windows-phone-7-
app.html and decided to use that to connect to an Android device.
This is part 1 of 2 to explain the process of creating the Android application to connect to Ax via AIF services.
Unlike the blog mentioned above, I had to enable REST in the WCF service, and output it as JSON. This is because
android has a better JSON support than SOAP (ksoap can be used to consume the WCF services, but I have found
JSON to be a much easier approach)
To enable REST services, I installed the WCFRestContrib package. This is available from NuGet and can be installed
using
PM> Install-Package wcfrestcontrib
We can create the WCF Service using the no configuration mode. This link defines how to create a WCF service with no
configuration. Which means most of the web.config is deleted, and another identifier is attached to the SVC file. This
however relies of transport security as there is no SOAP envelope around this. WCFRESTContrib allows to create
acustom authentication system. The authentication data can be retrieved from the HTML headers and verified.
So the WCF service should look like this, it enables a GET method and has a certain URI, and outputs the data in JSON
01
02
03
04
05
06
07
08
09
10
11
12
13
namespace WcfService1
{
[ServiceContract]
[ServiceAuthentication] //WCFRESTContrib attribute - authentication per session (or at method level for per call)
[WebGet(UriTemplate = "/api1/appName", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
string ApplicationName();
[WebGet(UriTemplate = "/api1/items", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
List GetAllItemIds();
}
}
The Service interface markup (this allows for a noconfiguration WCF Service)
1
2
3
4
5
6
<%@ ServiceHost
Language="C#"
Debug="true"
Service="WcfService1.Api1"
CodeBehind="Api1.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
%>
7
The Service file itself
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
namespace WcfService1
{
[WebAuthenticationConfiguration(
typeof(WcfService1.ApiAuthnetication),
typeof(ApiAuthneticationValidator),
true,
"My Application")]
public class Api1 : IApi1 {
public string GetUsername()
{
object authValue;
string authStr = "", username = "", password = "";
try {
var keys = OperationContext.Current.IncomingMessageProperties.Keys;
OperationContext.Current.IncomingMessageProperties.TryGetValue("httpRequest", out authValue);
if (authValue != null)
{
System.ServiceModel.Channels.HttpRequestMessageProperty p = (System.ServiceModel.Channels.HttpReque
authStr = p.Headers.Get("Authorization");
ApiAuthnetication.GetUsernamePwd(authStr, out username, out password);
}
}
catch (Exception e)
{
return e.Message;
}
return username;
}
public string ApplicationName()
{
string username = this.GetUsername();
return username;
}
public List GetAllItemIds()
{
31
32
33
34
35
36
37
38
39
40
return Item.GetItems(this.GetUsername());
}
}
}
Notice the header attributes. This needs to be defined and is based on the WCFRESTContrib package. The
authentication classes created is. Notice that the Username and password are being sent in the header with the tag
“Authorization” this can be renamed to anything you like
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
namespace WcfService1
{
public class ApiAuthnetication : WcfRestContrib.ServiceModel.Dispatcher.IWebAuthenticationHandler {
public static bool GetUsernamePwd(string authenticationStr, out string username, out string password)
{
bool result = true;
username = "";
password = "";
try {
var values = authenticationStr.Split(':');
username = values[0];
password = values[1];
}
catch {
result = false;
}
return result;
}
public System.Security.Principal.IIdentity Authenticate(
System.ServiceModel.Web.IncomingWebRequestContext request,
System.ServiceModel.Web.OutgoingWebResponseContext response,
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
object[] parameters,
System.IdentityModel.Selectors.UserNamePasswordValidator validator,
bool secure,
bool requiresTransportLayerSecurity,
string source)
{
string authHeader = "";
string userName = "";
string password = "";
if (request.Headers.HasKeys() == true && request.Headers.AllKeys.Contains("Authorization") == true)
{
authHeader = request.Headers.Get("Authorization");
//var values = authHeader.Split(':');
//userName = values[0];
//password = values[1];
GetUsernamePwd(authHeader, out userName, out password);
}
validator.Validate(userName, password);
return new GenericIdentity(userName, this.GetType().Name);
}
}
public class ApiAuthneticationValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
//Do your custom authentication here
if (userName.Equals("claimguy@myapp.com", StringComparison.InvariantCultureIgnoreCase) == false
|| password.Equals("claimguy@myapp.com", StringComparison.InvariantCultureIgnoreCase) == false)
throw new Exception("Authentication Failed");
}
}
}
52
53
54
55
The code to get the InventTable data is pretty similar to Joris’s blog. Here is mine:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
namespace WcfService1
{
public class Item {
public string ItemId { get; set; }
public string Name { get; set; }
public static List GetItems(string username)
{
List items = new List();
string itemIdFrom = "1000"; //I cheated here
string itemIdTo = "1105"; //I cheated here again
//Fetch items from AX here
using (ItemService.ItemServiceClient client = new ItemService.ItemServiceClient())
{
ItemService.QueryCriteria qc = new ItemService.QueryCriteria();
ItemService.CriteriaElement criteria = new ItemService.CriteriaElement();
criteria.DataSourceName = "InventTable";
criteria.FieldName = "ItemId";
criteria.Operator = ItemService.Operator.Range;
criteria.Value1 = itemIdFrom;
criteria.Value2 = itemIdTo;
qc.CriteriaElement = new ItemService.CriteriaElement[] { criteria };
ItemService.CallContext context = new ItemService.CallContext();
context.Company = "ceu";
context.MessageId = Guid.NewGuid().ToString();
context.LogonAsUser = string.Format("LoonAx{0}", username);
var axItems = client.find(context, qc);
if (axItems.InventTable != null)
{
foreach (var inventTable in axItems.InventTable)
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
{
Item item = new Item() { ItemId = inventTable.ItemId, Name = inventTable.NameAlias };
items.Add(item);
}
}
}
/* //Mocking for AIF
for (int i = 0; i < 10; i++) { Item item = new Item() { ItemId = (1000 + i + 1).ToString(), Name = (1000 +
}*/ return items;
}
}
}
To make the connection secure (since we are sending the authentications via plain text in the HTML headers, this service
should ideally be secure)
Android with WCF service using JSON
Matija Božičević - 01.03.2012.
C# Android JSON WCF
inShare1
In this article I will show you simple example how to:
1. Create simple .NET WCF service
2. Connect Android application with .NET WCF service, get some data in JSON format, and show data in Android's ListView
1. Create simple .NET WCF service
Service.svc
With function GetPersons() we get data from SQL 2008 database, and return them as generic list.
?
1
2
3
4
5
6
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Web.Script.Serialization;
using MB.AndroidWCF.DataAccessLayer;
namespace MB.AndroidWCF
{
public class Service : IService
{
public List<spGetPersonsResult> GetPersons()
{
// Get data with DLINQ
return new dbAndroidWCFDataContext().spGetPersons().ToList();
}
}
}
IService.cs
Note that the spGetPersonsResult is SQL stored procedure accessed with DLINQ.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using MB.AndroidWCF.DataAccessLayer;
namespace MB.AndroidWCF
{
[ServiceContract]
public interface IService
{
[OperationContract]
16
17
18
19
20
21
22
23
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "GetPersonsJSON")]
List<spGetPersonsResult> GetPersons();
}
}
The WCF service returns data in JSON format like this:
?
1
2
3
4
{"GetPersonsResult":[{"ID":1,"FullName":"Matija Božičević"},
{"ID":2,"FullName":"Al Pacino"},
{"ID":3,"FullName":"Clint Eastwood"}]}
2. Connect Android application with .NET WCF service, get some data inJSON format, and show data in
Android's ListView
MainActivity.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package AndroidWCFApp.package;
import android.app.Activity;
import android.view.View;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GetPersons();
}
public void GetPersons() {
ArrayList<String> persons = FromJSONtoArrayList();
ListView listView1 = (ListView)findViewById(R.id.ListView01);
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
listView1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, persons));
}
public ArrayList<String> FromJSONtoArrayList() {
ArrayList<String> listItems = new ArrayList<String>();
try {
// Replace it with your own WCF service path
URL json = new URL("http://192.168.1.1:9020/Service.svc/GetPersonsJSON");
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("GetPersonsResult");
for (int i = 0; i < jsonArray.length(); i++) {
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
JSONObject jObject = (JSONObject)jsonArray.get(i);
// "FullName" is the property of .NET object spGetPersonsResult,
// and also the name of column in SQL Server 2008
listItems.add(jObject.getString("FullName"));
}
reader.close();
} catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
return listItems;
}
}
69
70
Walkthrough - Working with WCF
PDF for offline use:
 Download PDF
Sample Code:
 HelloWorld.zip
Related Articles:
 Windows Communication Foundation on MSDN
 Using SLsvcUtil.exe to Access a Service
Related SDKs:
 Microsoft Silverlight 5 SDK
This walkthrough covers how a mobile application built with Xamarin can consume a WCF web service using the
BasicHttpBinding.
Overview
It is a common requirement for mobile applications to be able to communicate with backend systems. There are many choices and options for backe
frameworks, one of which is Windows Communication Foundation (WCF). This walkthrough will provide an example of how a Xamarin mobile
application can consume a WCF service using the BasicHttpBinding, as outlined below:
1. Create a WCF Service - In this section we will create a very basic WCF service having two methods. The first method will take a string parameter,while the oth
method will take a C# object. This section will also discuss how to configure a developer's workstation to allow remote access to the WCF service.
2. Create a Xamarin.Android Application - Once the WCF service has been created,we will create a simple Xamarin.Android application that will use the WCF
service. This section will cover how to create a WCF service proxy class to facilitate communication with the WCF service.
3. Create a Xamarin.iOS Application - The final part of this tutorial involves creating a simple Xamarin.iOS application that will use the WCF service.
The following screen shots shows the two applications running:
Requirements
This walkthrough assumes that you have some familiarity with creating and using WCF services.
In order to create the WCF service proxies, you will need the Silverlight 5 SDK installed. Download and run the installer from Microsoft before
proceeding with this walkthrough.
IIS Express will be used to host the WCF Service used in this walkthrough. This is the default web server for Visual Studio 2012. Installing IIS Exp
in older versions of Visual Studio is beyond the scope of this walkthrough.
Note:This walkthrough was created on Windows 8 using Visual Studio 2012. If you are using on an older version of Windows or Visual Studio, be
aware that some parts of this walkthrough may not be applicable to your development environment.
Creating a WCF Service
The first task before us is to create a WCF service for our mobile applications to communicate with.
1. Start up Visual Studio 2012, and press Alt-F-N-P to open the New Project dialog. Select the WCF Service Applicationtemplate from the new project dialog as
shown in the following screenshot:
Name the project HelloWorldWcfHost, and name the solution HelloWorld. Click the OK button.
2. Next we need to create the service contract for the web service. Add an interface named IHelloWorldService and paste in the following code:
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract]
string SayHelloTo(string name);
[OperationContract]
HelloWorldData GetHelloData(HelloWorldData helloWorldData);
}
This service provides two methods - one that takes a string for a parameter and another that takes a .NET object.
3. Our WCF service requires the class HelloWorldData as a parameter,so let's create this type next. Add a new class to the project named HelloWorldData w
the following implementation:
[DataContract]
public class HelloWorldData
{
public HelloWorldData()
{
Name = "Hello ";
SayHello = false;
}
[DataMember]
public bool SayHello { get; set; }
[DataMember]
public string Name { get; set; }
}
4. The final thing we need to do is to create the WCF Service class . Press Ctrl-Shift-A to bring up the Add New Itemdialog:
Add a new WCF Service class to the project named HelloWorldService. Edit the class so that it implementsIHelloWorldService and contains
code from the following snippet:
public class HelloWorldService : IHelloWorldService
{
public HelloWorldData GetHelloData(HelloWorldData helloWorldData)
{
if (helloWorldData == null)
{
throw new ArgumentNullException("helloWorldData");
}
if (helloWorldData.SayHello)
{
helloWorldData.Name = String.Format("Hello World to {0}.", helloWorldData.Name);
}
return helloWorldData;
}
public string SayHelloTo(string name)
{
return string.Format("Hello World to you, {0}", name);
}
}
5. This final step is optional. In it we change the default port for the WCF service to use 9607 for connections being made from localhost. Press Alt-P-P to bri
up the Project Properties dialog for the HelloWorldWcfHost project. Select theWeb tab,and set the Project Url to http://localhost:9607/, as shown in th
following screenshot:
At this point we should have a working WCF service. If we run the project, and point our browser to http://localhost:9067/HelloWorldService.svc, w
should see the following page:
This current setup is sufficient if we only have to connect with the WCF service from our local workstation. However, remote devices (such as an
Android device or an iPhone) do not have any access to the WCF service. The next section will cover how to configure Windows 8 and IIS Express
accept remote connections.
Note: The following section is only necessary if you need to accept remote connections on a Windows 8 workstation. If you have an alternate platfo
on which to deploy this Web Service you can ignore following section.
Configuring Remote Access to IIS Express
By default, Windows 8 and IIS Express will not accept remote connections. Before any remote devices, such as an Android device or an iPhone can
communicate with our WCF service we must make the following changes:
1. Configure IIS Express to Accept Remote connections - This step involves editing the config file for IIS Express to accept remote connections on a specific por
then setting up a rule for IIS Express to accept the incoming traffic.
2. Add an Exception to Windows Firewall - We must open up a port through Windows Firewall that remote applications can use to communicate with the WCF
service.
You will need to know the IP address of your workstation. For the purposes of this example we'll assume that our workstation has the IP address
192.168.1.143.
1. Let's begin by configuring IIS Express to listen for external requests. We do this by editing the configuration file for IIS Express
at %userprofile%documentsiisexpressconfigapplicationhost.config, as shown in the following screenshot:
Locate the site element with the name HelloWorldWcfHost. It should look something like the following XML snippet:
<site name="HelloWorldWcfHost" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="vmware-hostShared Folderstomworkxamarincodeprivate-
sampleswebservicesHelloWorldHelloWorldWcfHost" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:9607:localhost" />
</bindings>
</site>
We will need to add another binding to open up port 9608 to outside traffic. Add the following XML to the bindingselement:
<binding protocol="http" bindingInformation="*:9608:192.168.1.143" />
This will configure IIS Express to accept HTTP traffic from any remote IP address on port 9608 on the external IP address of the computer. This ab
snippet assumes the IP address of the computer running IIS Express is 192.168.1.143. After the changes, the bindings element should look like the
following:
<site name="HelloWorldWcfHost" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="vmware-hostShared Folderstomworkxamarincodeprivate-
sampleswebservicesHelloWorldHelloWorldWcfHost" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:9607:localhost" />
<binding protocol="http" bindingInformation="*:9608:192.168.1.143" />
</bindings>
</site>
2. Next, we need to configure IIS Express accept incoming connections on port 9608. Startup up an administrative command prompt, and run this command:
> netsh http add urlacl url=http://192.168.1.143:9608/ user=everyone
3. The final step is to configure Windows Firewall to permit external traffic on port 9608. From an administrative command prompt, run the following command:
> netsh advfirewall firewall add rule name="IISExpressXamarin" dir=in protocol=tcp localport=9608 profile=private
remoteip=localsubnet action=allow
This command will allow incoming traffic on port 9608 from all devices on the same subnet as the Windows 8 workstation.
At this point we have created a very basic WCF service hosted in IIS Express that will accept incoming connections from other devices or computer
our subnet. You can test this out by visiting http://localhost:9607/HelloWorldService.svc on your workstation and
http://192.168.1.143:9608/HelloWorldService.svc from another computer on your subnet.
Creating a Xamarin.Android Application
Now that we have the WCF service working, let's move on to creating a Xamarin.Android application.
1. Add a new Android project to the solution and name it HelloWorld.Android.
2. Change the default namespace of the application from HelloWorld.Android to HelloWorld.Droid.
3. Next we need to create a proxy for the web service. To create the proxy we'll use the Silverlight Service Model Proxy Generation Tool (SLsvcUtil.exe). You
find this command line utility at the following location:
C:Program Files (x86)Microsoft SDKsSilverlightv5.0ToolsSLsvcUtil.exe
Ensure that the WCF service we created in the previous section is running, and then run SLsvcUtil.exe with the following command line:
SLsvcUtil.exe /noConfig http://localhost:9607/HelloWorldService.svc
This will create a service proxy called HelloWorldService in the file HelloWorldService.cs. Add this file to your Xamarin.Android project as
shown in the following screenshot:
4. Before this generated proxy class will compile, we need to add to some references to our Xamarin.Android project, as shown in the follwoing screenshot:
5. With the above infrastructure in place, we can finish up the Android application. Edit the file Activity1.cs and add the following instance variables:
[Activity(Label = "@string/app_name", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{
public static readonly EndpointAddress EndPoint = new
EndpointAddress("http://192.168.1.143:9609/HelloWorldService.svc");
private HelloWorldServiceClient _client;
private Button _getHelloWorldDataButton;
private TextView _getHelloWorldDataTextView;
private Button _sayHelloWorldButton;
private TextView _sayHelloWorldTextView;
6. Next, update Main.axml with the following XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1">
<Button
android:id="@+id/sayHelloWorldButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/say_hello_world" />
<TextView
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/sayHelloWorldTextView" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1">
<Button
android:id="@+id/getHelloWorldDataButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/get_hello_world_data" />
<TextView
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/getHelloWorldDataTextView" />
</LinearLayout>
</LinearLayout>
The following is a screenshot of what this UI looks like in the designer:
7. Now with the UI and instance variables in place, modify OnCreate to contain the following code:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
InitializeHelloWorldServiceClient();
// This button will invoke the GetHelloWorldData - the method that takes a C# object as a parameter.
_getHelloWorldDataButton = FindViewById<Button>(Resource.Id.getHelloWorldDataButton);
_getHelloWorldDataButton.Click += GetHelloWorldDataButtonOnClick;
_getHelloWorldDataTextView = FindViewById<TextView>(Resource.Id.getHelloWorldDataTextView);
// This button will invoke SayHelloWorld - this method takes a simple string as a parameter.
_sayHelloWorldButton = FindViewById<Button>(Resource.Id.sayHelloWorldButton);
_sayHelloWorldButton.Click += SayHelloWorldButtonOnClick;
_sayHelloWorldTextView = FindViewById<TextView>(Resource.Id.sayHelloWorldTextView);
}
The code above initializes the instance variables for our class and wires up some event handlers.
8. Next we need to instantiate the client proxy class in our Activity. Edit Activity1.cs and add the following two methods to the class:
private void InitializeHelloWorldServiceClient()
{
BasicHttpBinding binding = CreateBasicHttp();
_client = new HelloWorldServiceClient(binding, EndPoint);
_client.SayHelloToCompleted += ClientOnSayHelloToCompleted;
_client.GetHelloDataCompleted += ClientOnGetHelloDataCompleted;
}
private static BasicHttpBinding CreateBasicHttp()
{
BasicHttpBinding binding = new BasicHttpBinding
{
Name = "basicHttpBinding",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
TimeSpan timeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
return binding;
}
The code above instantiates and initializes a HelloWorldService object. The WCF proxy class can only call the WCF service asynchronously.
Responses from the WCF service will handled by the xxxCompleted events that were generated by SLsvcUtil.exe.
9. Now we need to add the event handlers for the two buttons in our activity. Edit Activity1.cs and add the following two methods:
private void GetHelloWorldDataButtonOnClick(object sender, EventArgs eventArgs)
{
HelloWorldData data = new HelloWorldData { Name = "Mr. Chad", SayHello = true };
_getHelloWorldDataTextView.Text = "Waiting for WCF...";
_client.GetHelloDataAsync(data);
}
private void SayHelloWorldButtonOnClick(object sender, EventArgs eventArgs)
{
_sayHelloWorldTextView.Text = "Waiting for WCF...";
_client.SayHelloToAsync("Kilroy");
}
10. Finally, we need to add event handlers for the xxxCompleted events of the HelloWorldService proxy client. Once again edit Activity1.cs and add the
following methods:
private void ClientOnGetHelloDataCompleted(object sender, GetHelloDataCompletedEventArgs getHelloDataCompletedEventArgs
{
string msg = null;
if (getHelloDataCompletedEventArgs.Error != null)
{
msg = getHelloDataCompletedEventArgs.Error.Message;
}
else if (getHelloDataCompletedEventArgs.Cancelled)
{
msg = "Request was cancelled.";
}
else
{
msg = getHelloDataCompletedEventArgs.Result.Name;
}
RunOnUiThread(() => _getHelloWorldDataTextView.Text = msg);
}
private void ClientOnSayHelloToCompleted(object sender, SayHelloToCompletedEventArgs sayHelloToCompletedEventArgs)
{
string msg = null;
if (sayHelloToCompletedEventArgs.Error != null)
{
msg = sayHelloToCompletedEventArgs.Error.Message;
}
else if (sayHelloToCompletedEventArgs.Cancelled)
{
msg = "Request was cancelled.";
}
else
{
msg = sayHelloToCompletedEventArgs.Result;
}
RunOnUiThread(() =>_sayHelloWorldTextView.Text = msg);
}
11. Run the application, and click on the two buttons. Our application will call the WCF asynchronously. Within 30 seconds a response should be received from each
WCF method, and our application should look something like the following screenshot:
Now that we have a working Xamarin.Android application, let's create a Xamarin.iOS client.
Creating a Xamarin.iOS Application
The Xamarin.iOS version is very similar to the Xamarin.Android application and will use the exact same WCF proxy client code that was generated
by SLsvcUtil.exe. The following screenshot shows our application after it has successfully interacted with the WCF service that we created earlie
in this walkthrough:
Let's get started with the Xamarin.iOS application.
1. Start up Xamarin Studio, and open the HelloWorld solution. Add a new iPhone Single View Application to the solution, as shown in the following screenshot:
2. To create the user interface for our application, edit the .XIB in Interface Builder and add two UIButtons and twoUITextViews. Add the outlets for each con
according to the following table:
Name Text
UIButton sayHelloWorldButton Say Hello World
UITextView sayHelloWorldText
UIButton getHelloWorldDataButton Get Hello World Data
UITextView sayHelloWorldText
After creating the outlets, the UI should resemble the following screenshot:
3. Next, add the WCF proxy class HelloWorldService.cs to our project by pressing Option-Cmd-A. This will bring up theAdd files dialog which you can us
locate and add the file to the project. Once that is done add references toSystem.Runtime.Serialization, System.ServiceModel,
and System.ServiceModel.Web just as we did in the Android application. The following screenshot shows Solution Explorer after adding these references:
4. We need to add a couple variables to our view controller that the WCF client code will use. Edit the classXamarin_iOSViewController and add two instanc
variables as shown in the following code snippet:
public partial class Xamarin_iOSViewController : UIViewController
{
public static readonly EndpointAddress EndPoint = new
EndpointAddress("http://192.168.1.143:9609/HelloWorldService.svc");
private HelloWorldServiceClient _client;
You will probably have to change the IP address to that of the computer that is hosting your WCF service.
5. After adding the variable above, update the ViewDidLoad method to include the following code:
public override void ViewDidLoad()
{
base.ViewDidLoad();
InitializeHelloWorldServiceClient();
}
6. Next, add some helper methods to instantiate a HelloWorkdService client proxy instance and hook up a couple event handlers.. Add the following two metho
to Xamarin_iOSViewController:
private void InitializeHelloWorldServiceClient()
{
BasicHttpBinding binding = CreateBasicHttp();
_client = new HelloWorldServiceClient(binding, EndPoint);
_client.SayHelloToCompleted += ClientOnSayHelloToCompleted;
_client.GetHelloDataCompleted += ClientOnGetHelloDataCompleted;
getHelloWorldDataButton.TouchUpInside += GetHelloWorldDataButtonTouchUpInside;
sayHelloWorldButton.TouchUpInside += SayHelloWorldDataButtonTouchUpInside;
}
private static BasicHttpBinding CreateBasicHttp()
{
BasicHttpBinding binding = new BasicHttpBinding
{
Name = "basicHttpBinding",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
TimeSpan timeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
return binding;
}
7. Next, create event handlers for the two UIButtons in the XIB file as shown below:
private void SayHelloWorldDataButtonTouchUpInside(object sender, EventArgs e)
{
sayHelloWorldText.Text = "Waiting for WCF...";
_client.SayHelloToAsync("Kilroy");
}
private void GetHelloWorldDataButtonTouchUpInside(object sender, EventArgs e)
{
getHelloWorldDataText.Text = "Waiting WCF...";
HelloWorldData data = new HelloWorldData { Name = "Mr. Chad", SayHello = true };
_client.GetHelloDataAsync(data);
}
8. Finally, add the event handlers for the xxxOnCompleted events that the HelloWorldService proxy client will raise when the WCF service sends a reply ba
our application. Add the following two methods to Xamarin_iOSViewController:
private void ClientOnGetHelloDataCompleted(object sender, GetHelloDataCompletedEventArgs e)
{
string msg = null;
if (e.Error != null)
{
msg = e.Error.Message;
}
else if (e.Cancelled)
{
msg = "Request was cancelled.";
}
else
{
msg = e.Result.Name;
}
InvokeOnMainThread(() => getHelloWorldDataText.Text = msg);
}
private void ClientOnSayHelloToCompleted(object sender, SayHelloToCompletedEventArgs e)
{
string msg = null;
if (e.Error != null)
{
msg = e.Error.Message;
}
else if (e.Cancelled)
{
msg = "Request was cancelled.";
}
else
{
msg = e.Result;
}
InvokeOnMainThread(() => sayHelloWorldText.Text = msg);
}
9. Now run the application, and click on each of the buttons in the UI. The WCF service will be called asynchronously. Within 30 seconds a response should be rec
from each WCF method, and our application should look like the following screenshot:
Summary
This tutorial covered how to work with a WCF service in a mobile application using Xamarin.Android and Xamarin.iOS. It showed how to create a
WCF service and explained how to configure Windows 8 and IIS Express to accept connections from remote devices. It then discussed how to gene
a WCF proxy client using the Silverlight Service Model Proxy Generation Tool ( SLsvcUtil.exe) and demonstrated how to use the proxy client in
both Xamarin.Android and Xamarin.iOS applications.

More Related Content

What's hot

Integrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight ApplicationsIntegrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight Applications
Dan Wahlin
 
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Hermann Burgmeier
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injection
Mickey Jack
 

What's hot (18)

Integrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight ApplicationsIntegrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight Applications
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
Final microsoft cloud summit - windows azure building block services
Final   microsoft cloud summit - windows azure building block servicesFinal   microsoft cloud summit - windows azure building block services
Final microsoft cloud summit - windows azure building block services
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
 
Client-side Auth with Ember.js
Client-side Auth with Ember.jsClient-side Auth with Ember.js
Client-side Auth with Ember.js
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injection
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
EmberConf 2015 – Ambitious UX for Ambitious Apps
EmberConf 2015 – Ambitious UX for Ambitious AppsEmberConf 2015 – Ambitious UX for Ambitious Apps
EmberConf 2015 – Ambitious UX for Ambitious Apps
 
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menaceDEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Android Cloud to Device Messaging Framework at GTUG Stockholm
Android Cloud to Device Messaging Framework at GTUG StockholmAndroid Cloud to Device Messaging Framework at GTUG Stockholm
Android Cloud to Device Messaging Framework at GTUG Stockholm
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2
 
AJAX
AJAXAJAX
AJAX
 

Viewers also liked (18)

Classical cryptography1
Classical cryptography1Classical cryptography1
Classical cryptography1
 
coloring method
 coloring method coloring method
coloring method
 
Embedded
EmbeddedEmbedded
Embedded
 
Alifeofinspiration nelsonmandela1918-2013-131205232125-phpapp02
Alifeofinspiration nelsonmandela1918-2013-131205232125-phpapp02Alifeofinspiration nelsonmandela1918-2013-131205232125-phpapp02
Alifeofinspiration nelsonmandela1918-2013-131205232125-phpapp02
 
Caqa5e ch1 with_review_and_examples
Caqa5e ch1 with_review_and_examplesCaqa5e ch1 with_review_and_examples
Caqa5e ch1 with_review_and_examples
 
Slides cao
Slides caoSlides cao
Slides cao
 
3 a. hil climbing
3 a. hil climbing3 a. hil climbing
3 a. hil climbing
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Cloudcomputingit703 130915004442-phpapp01
Cloudcomputingit703 130915004442-phpapp01Cloudcomputingit703 130915004442-phpapp01
Cloudcomputingit703 130915004442-phpapp01
 
Sp800 94.pdf
Sp800 94.pdfSp800 94.pdf
Sp800 94.pdf
 
Firewall
FirewallFirewall
Firewall
 
Des1
Des1Des1
Des1
 
C sharp notes
C sharp notesC sharp notes
C sharp notes
 
i_os_development_environment
i_os_development_environmenti_os_development_environment
i_os_development_environment
 
Nelson Mandela
Nelson Mandela Nelson Mandela
Nelson Mandela
 
Aes
AesAes
Aes
 
Owasp top 10
Owasp top 10Owasp top 10
Owasp top 10
 
Advanced databases -client /server arch
Advanced databases -client /server archAdvanced databases -client /server arch
Advanced databases -client /server arch
 

Similar to Android ax app wcf

Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
lonegunman
 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
Flavius-Radu Demian
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web applicationASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
AMARAAHMED7
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
Chui-Wen Chiu
 

Similar to Android ax app wcf (20)

How To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppHow To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native App
 
Web services in java
Web services in javaWeb services in java
Web services in java
 
Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)
 
Building RESTful Services with WCF 4.0
Building RESTful Services with WCF 4.0Building RESTful Services with WCF 4.0
Building RESTful Services with WCF 4.0
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
 
C#on linux
C#on linuxC#on linux
C#on linux
 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web applicationASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
 
WCF Fundamentals
WCF Fundamentals WCF Fundamentals
WCF Fundamentals
 
AJAX
AJAXAJAX
AJAX
 
CodeMash 2013 Microsoft Data Stack
CodeMash 2013 Microsoft Data StackCodeMash 2013 Microsoft Data Stack
CodeMash 2013 Microsoft Data Stack
 
Java servlets
Java servletsJava servlets
Java servlets
 
Express node js
Express node jsExpress node js
Express node js
 
ASP.NET MVC and ajax
ASP.NET MVC and ajax ASP.NET MVC and ajax
ASP.NET MVC and ajax
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 

Recently uploaded

+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
Health
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 

Recently uploaded (20)

A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 

Android ax app wcf

  • 1. Android Ax App – Part 1–Set up the intermediate WCF service December 5, 2011.Net, Android, Ax 2012, Dynamics Ax, JSON, REST, WCFAndroid,AX2012, JSON, REST, WCF 2 Votes I came across a blog by Joris De Gruyter http://daxmusings.blogspot.com/2011/11/10-minute-app-windows-phone-7- app.html and decided to use that to connect to an Android device. This is part 1 of 2 to explain the process of creating the Android application to connect to Ax via AIF services. Unlike the blog mentioned above, I had to enable REST in the WCF service, and output it as JSON. This is because android has a better JSON support than SOAP (ksoap can be used to consume the WCF services, but I have found JSON to be a much easier approach) To enable REST services, I installed the WCFRestContrib package. This is available from NuGet and can be installed using
  • 2. PM> Install-Package wcfrestcontrib We can create the WCF Service using the no configuration mode. This link defines how to create a WCF service with no configuration. Which means most of the web.config is deleted, and another identifier is attached to the SVC file. This however relies of transport security as there is no SOAP envelope around this. WCFRESTContrib allows to create acustom authentication system. The authentication data can be retrieved from the HTML headers and verified. So the WCF service should look like this, it enables a GET method and has a certain URI, and outputs the data in JSON 01 02 03 04 05 06 07 08 09 10 11 12 13 namespace WcfService1 { [ServiceContract] [ServiceAuthentication] //WCFRESTContrib attribute - authentication per session (or at method level for per call) [WebGet(UriTemplate = "/api1/appName", ResponseFormat = WebMessageFormat.Json)] [OperationContract] string ApplicationName(); [WebGet(UriTemplate = "/api1/items", ResponseFormat = WebMessageFormat.Json)] [OperationContract] List GetAllItemIds(); } } The Service interface markup (this allows for a noconfiguration WCF Service) 1 2 3 4 5 6 <%@ ServiceHost Language="C#" Debug="true" Service="WcfService1.Api1" CodeBehind="Api1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
  • 3. 7 The Service file itself 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 namespace WcfService1 { [WebAuthenticationConfiguration( typeof(WcfService1.ApiAuthnetication), typeof(ApiAuthneticationValidator), true, "My Application")] public class Api1 : IApi1 { public string GetUsername() { object authValue; string authStr = "", username = "", password = ""; try { var keys = OperationContext.Current.IncomingMessageProperties.Keys; OperationContext.Current.IncomingMessageProperties.TryGetValue("httpRequest", out authValue); if (authValue != null) { System.ServiceModel.Channels.HttpRequestMessageProperty p = (System.ServiceModel.Channels.HttpReque authStr = p.Headers.Get("Authorization"); ApiAuthnetication.GetUsernamePwd(authStr, out username, out password); } } catch (Exception e) { return e.Message; } return username; } public string ApplicationName() { string username = this.GetUsername(); return username; } public List GetAllItemIds() {
  • 4. 31 32 33 34 35 36 37 38 39 40 return Item.GetItems(this.GetUsername()); } } } Notice the header attributes. This needs to be defined and is based on the WCFRESTContrib package. The authentication classes created is. Notice that the Username and password are being sent in the header with the tag “Authorization” this can be renamed to anything you like 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 namespace WcfService1 { public class ApiAuthnetication : WcfRestContrib.ServiceModel.Dispatcher.IWebAuthenticationHandler { public static bool GetUsernamePwd(string authenticationStr, out string username, out string password) { bool result = true; username = ""; password = ""; try { var values = authenticationStr.Split(':'); username = values[0]; password = values[1]; } catch { result = false; } return result; } public System.Security.Principal.IIdentity Authenticate( System.ServiceModel.Web.IncomingWebRequestContext request, System.ServiceModel.Web.OutgoingWebResponseContext response,
  • 5. 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 object[] parameters, System.IdentityModel.Selectors.UserNamePasswordValidator validator, bool secure, bool requiresTransportLayerSecurity, string source) { string authHeader = ""; string userName = ""; string password = ""; if (request.Headers.HasKeys() == true && request.Headers.AllKeys.Contains("Authorization") == true) { authHeader = request.Headers.Get("Authorization"); //var values = authHeader.Split(':'); //userName = values[0]; //password = values[1]; GetUsernamePwd(authHeader, out userName, out password); } validator.Validate(userName, password); return new GenericIdentity(userName, this.GetType().Name); } } public class ApiAuthneticationValidator : System.IdentityModel.Selectors.UserNamePasswordValidator { public override void Validate(string userName, string password) { //Do your custom authentication here if (userName.Equals("claimguy@myapp.com", StringComparison.InvariantCultureIgnoreCase) == false || password.Equals("claimguy@myapp.com", StringComparison.InvariantCultureIgnoreCase) == false) throw new Exception("Authentication Failed"); } } }
  • 6. 52 53 54 55 The code to get the InventTable data is pretty similar to Joris’s blog. Here is mine: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 namespace WcfService1 { public class Item { public string ItemId { get; set; } public string Name { get; set; } public static List GetItems(string username) { List items = new List(); string itemIdFrom = "1000"; //I cheated here string itemIdTo = "1105"; //I cheated here again //Fetch items from AX here using (ItemService.ItemServiceClient client = new ItemService.ItemServiceClient()) { ItemService.QueryCriteria qc = new ItemService.QueryCriteria(); ItemService.CriteriaElement criteria = new ItemService.CriteriaElement(); criteria.DataSourceName = "InventTable"; criteria.FieldName = "ItemId"; criteria.Operator = ItemService.Operator.Range; criteria.Value1 = itemIdFrom; criteria.Value2 = itemIdTo; qc.CriteriaElement = new ItemService.CriteriaElement[] { criteria }; ItemService.CallContext context = new ItemService.CallContext(); context.Company = "ceu"; context.MessageId = Guid.NewGuid().ToString(); context.LogonAsUser = string.Format("LoonAx{0}", username); var axItems = client.find(context, qc); if (axItems.InventTable != null) { foreach (var inventTable in axItems.InventTable)
  • 7. 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 { Item item = new Item() { ItemId = inventTable.ItemId, Name = inventTable.NameAlias }; items.Add(item); } } } /* //Mocking for AIF for (int i = 0; i < 10; i++) { Item item = new Item() { ItemId = (1000 + i + 1).ToString(), Name = (1000 + }*/ return items; } } } To make the connection secure (since we are sending the authentications via plain text in the HTML headers, this service should ideally be secure) Android with WCF service using JSON Matija Božičević - 01.03.2012. C# Android JSON WCF
  • 8. inShare1 In this article I will show you simple example how to: 1. Create simple .NET WCF service 2. Connect Android application with .NET WCF service, get some data in JSON format, and show data in Android's ListView 1. Create simple .NET WCF service Service.svc With function GetPersons() we get data from SQL 2008 database, and return them as generic list. ? 1 2 3 4 5 6 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text;
  • 9. 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 using System.Web.Script.Serialization; using MB.AndroidWCF.DataAccessLayer; namespace MB.AndroidWCF { public class Service : IService { public List<spGetPersonsResult> GetPersons() { // Get data with DLINQ return new dbAndroidWCFDataContext().spGetPersons().ToList(); } } }
  • 10. IService.cs Note that the spGetPersonsResult is SQL stored procedure accessed with DLINQ. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using MB.AndroidWCF.DataAccessLayer; namespace MB.AndroidWCF { [ServiceContract] public interface IService { [OperationContract]
  • 11. 16 17 18 19 20 21 22 23 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetPersonsJSON")] List<spGetPersonsResult> GetPersons(); } } The WCF service returns data in JSON format like this: ? 1 2 3 4 {"GetPersonsResult":[{"ID":1,"FullName":"Matija Božičević"}, {"ID":2,"FullName":"Al Pacino"}, {"ID":3,"FullName":"Clint Eastwood"}]}
  • 12. 2. Connect Android application with .NET WCF service, get some data inJSON format, and show data in Android's ListView MainActivity.java ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 package AndroidWCFApp.package; import android.app.Activity; import android.view.View; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject;
  • 13. 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GetPersons(); } public void GetPersons() { ArrayList<String> persons = FromJSONtoArrayList(); ListView listView1 = (ListView)findViewById(R.id.ListView01);
  • 14. 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 listView1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, persons)); } public ArrayList<String> FromJSONtoArrayList() { ArrayList<String> listItems = new ArrayList<String>(); try { // Replace it with your own WCF service path URL json = new URL("http://192.168.1.1:9020/Service.svc/GetPersonsJSON"); URLConnection jc = json.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream())); String line = reader.readLine(); JSONObject jsonResponse = new JSONObject(line); JSONArray jsonArray = jsonResponse.getJSONArray("GetPersonsResult"); for (int i = 0; i < jsonArray.length(); i++) {
  • 15. 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 JSONObject jObject = (JSONObject)jsonArray.get(i); // "FullName" is the property of .NET object spGetPersonsResult, // and also the name of column in SQL Server 2008 listItems.add(jObject.getString("FullName")); } reader.close(); } catch(Exception e){ Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); } return listItems; } }
  • 16. 69 70 Walkthrough - Working with WCF PDF for offline use:  Download PDF Sample Code:  HelloWorld.zip Related Articles:  Windows Communication Foundation on MSDN  Using SLsvcUtil.exe to Access a Service Related SDKs:  Microsoft Silverlight 5 SDK This walkthrough covers how a mobile application built with Xamarin can consume a WCF web service using the BasicHttpBinding. Overview It is a common requirement for mobile applications to be able to communicate with backend systems. There are many choices and options for backe
  • 17. frameworks, one of which is Windows Communication Foundation (WCF). This walkthrough will provide an example of how a Xamarin mobile application can consume a WCF service using the BasicHttpBinding, as outlined below: 1. Create a WCF Service - In this section we will create a very basic WCF service having two methods. The first method will take a string parameter,while the oth method will take a C# object. This section will also discuss how to configure a developer's workstation to allow remote access to the WCF service. 2. Create a Xamarin.Android Application - Once the WCF service has been created,we will create a simple Xamarin.Android application that will use the WCF service. This section will cover how to create a WCF service proxy class to facilitate communication with the WCF service. 3. Create a Xamarin.iOS Application - The final part of this tutorial involves creating a simple Xamarin.iOS application that will use the WCF service. The following screen shots shows the two applications running:
  • 18.
  • 19. Requirements This walkthrough assumes that you have some familiarity with creating and using WCF services.
  • 20. In order to create the WCF service proxies, you will need the Silverlight 5 SDK installed. Download and run the installer from Microsoft before proceeding with this walkthrough. IIS Express will be used to host the WCF Service used in this walkthrough. This is the default web server for Visual Studio 2012. Installing IIS Exp in older versions of Visual Studio is beyond the scope of this walkthrough. Note:This walkthrough was created on Windows 8 using Visual Studio 2012. If you are using on an older version of Windows or Visual Studio, be aware that some parts of this walkthrough may not be applicable to your development environment. Creating a WCF Service The first task before us is to create a WCF service for our mobile applications to communicate with. 1. Start up Visual Studio 2012, and press Alt-F-N-P to open the New Project dialog. Select the WCF Service Applicationtemplate from the new project dialog as shown in the following screenshot:
  • 21. Name the project HelloWorldWcfHost, and name the solution HelloWorld. Click the OK button. 2. Next we need to create the service contract for the web service. Add an interface named IHelloWorldService and paste in the following code: [ServiceContract] public interface IHelloWorldService { [OperationContract] string SayHelloTo(string name); [OperationContract] HelloWorldData GetHelloData(HelloWorldData helloWorldData); } This service provides two methods - one that takes a string for a parameter and another that takes a .NET object.
  • 22. 3. Our WCF service requires the class HelloWorldData as a parameter,so let's create this type next. Add a new class to the project named HelloWorldData w the following implementation: [DataContract] public class HelloWorldData { public HelloWorldData() { Name = "Hello "; SayHello = false; } [DataMember] public bool SayHello { get; set; } [DataMember] public string Name { get; set; } } 4. The final thing we need to do is to create the WCF Service class . Press Ctrl-Shift-A to bring up the Add New Itemdialog:
  • 23. Add a new WCF Service class to the project named HelloWorldService. Edit the class so that it implementsIHelloWorldService and contains code from the following snippet:
  • 24. public class HelloWorldService : IHelloWorldService { public HelloWorldData GetHelloData(HelloWorldData helloWorldData) { if (helloWorldData == null) { throw new ArgumentNullException("helloWorldData"); } if (helloWorldData.SayHello) { helloWorldData.Name = String.Format("Hello World to {0}.", helloWorldData.Name); } return helloWorldData; } public string SayHelloTo(string name) { return string.Format("Hello World to you, {0}", name); } } 5. This final step is optional. In it we change the default port for the WCF service to use 9607 for connections being made from localhost. Press Alt-P-P to bri up the Project Properties dialog for the HelloWorldWcfHost project. Select theWeb tab,and set the Project Url to http://localhost:9607/, as shown in th following screenshot:
  • 25. At this point we should have a working WCF service. If we run the project, and point our browser to http://localhost:9067/HelloWorldService.svc, w should see the following page:
  • 26. This current setup is sufficient if we only have to connect with the WCF service from our local workstation. However, remote devices (such as an Android device or an iPhone) do not have any access to the WCF service. The next section will cover how to configure Windows 8 and IIS Express accept remote connections. Note: The following section is only necessary if you need to accept remote connections on a Windows 8 workstation. If you have an alternate platfo on which to deploy this Web Service you can ignore following section.
  • 27. Configuring Remote Access to IIS Express By default, Windows 8 and IIS Express will not accept remote connections. Before any remote devices, such as an Android device or an iPhone can communicate with our WCF service we must make the following changes: 1. Configure IIS Express to Accept Remote connections - This step involves editing the config file for IIS Express to accept remote connections on a specific por then setting up a rule for IIS Express to accept the incoming traffic. 2. Add an Exception to Windows Firewall - We must open up a port through Windows Firewall that remote applications can use to communicate with the WCF service. You will need to know the IP address of your workstation. For the purposes of this example we'll assume that our workstation has the IP address 192.168.1.143. 1. Let's begin by configuring IIS Express to listen for external requests. We do this by editing the configuration file for IIS Express at %userprofile%documentsiisexpressconfigapplicationhost.config, as shown in the following screenshot:
  • 28. Locate the site element with the name HelloWorldWcfHost. It should look something like the following XML snippet: <site name="HelloWorldWcfHost" id="2"> <application path="/" applicationPool="Clr4IntegratedAppPool"> <virtualDirectory path="/" physicalPath="vmware-hostShared Folderstomworkxamarincodeprivate- sampleswebservicesHelloWorldHelloWorldWcfHost" /> </application> <bindings> <binding protocol="http" bindingInformation="*:9607:localhost" />
  • 29. </bindings> </site> We will need to add another binding to open up port 9608 to outside traffic. Add the following XML to the bindingselement: <binding protocol="http" bindingInformation="*:9608:192.168.1.143" /> This will configure IIS Express to accept HTTP traffic from any remote IP address on port 9608 on the external IP address of the computer. This ab snippet assumes the IP address of the computer running IIS Express is 192.168.1.143. After the changes, the bindings element should look like the following: <site name="HelloWorldWcfHost" id="2"> <application path="/" applicationPool="Clr4IntegratedAppPool"> <virtualDirectory path="/" physicalPath="vmware-hostShared Folderstomworkxamarincodeprivate- sampleswebservicesHelloWorldHelloWorldWcfHost" /> </application> <bindings> <binding protocol="http" bindingInformation="*:9607:localhost" /> <binding protocol="http" bindingInformation="*:9608:192.168.1.143" /> </bindings> </site> 2. Next, we need to configure IIS Express accept incoming connections on port 9608. Startup up an administrative command prompt, and run this command: > netsh http add urlacl url=http://192.168.1.143:9608/ user=everyone 3. The final step is to configure Windows Firewall to permit external traffic on port 9608. From an administrative command prompt, run the following command: > netsh advfirewall firewall add rule name="IISExpressXamarin" dir=in protocol=tcp localport=9608 profile=private remoteip=localsubnet action=allow This command will allow incoming traffic on port 9608 from all devices on the same subnet as the Windows 8 workstation.
  • 30. At this point we have created a very basic WCF service hosted in IIS Express that will accept incoming connections from other devices or computer our subnet. You can test this out by visiting http://localhost:9607/HelloWorldService.svc on your workstation and http://192.168.1.143:9608/HelloWorldService.svc from another computer on your subnet. Creating a Xamarin.Android Application Now that we have the WCF service working, let's move on to creating a Xamarin.Android application. 1. Add a new Android project to the solution and name it HelloWorld.Android. 2. Change the default namespace of the application from HelloWorld.Android to HelloWorld.Droid. 3. Next we need to create a proxy for the web service. To create the proxy we'll use the Silverlight Service Model Proxy Generation Tool (SLsvcUtil.exe). You find this command line utility at the following location: C:Program Files (x86)Microsoft SDKsSilverlightv5.0ToolsSLsvcUtil.exe Ensure that the WCF service we created in the previous section is running, and then run SLsvcUtil.exe with the following command line: SLsvcUtil.exe /noConfig http://localhost:9607/HelloWorldService.svc This will create a service proxy called HelloWorldService in the file HelloWorldService.cs. Add this file to your Xamarin.Android project as shown in the following screenshot:
  • 31. 4. Before this generated proxy class will compile, we need to add to some references to our Xamarin.Android project, as shown in the follwoing screenshot:
  • 32. 5. With the above infrastructure in place, we can finish up the Android application. Edit the file Activity1.cs and add the following instance variables: [Activity(Label = "@string/app_name", MainLauncher = true, Icon = "@drawable/icon")] public class Activity1 : Activity { public static readonly EndpointAddress EndPoint = new EndpointAddress("http://192.168.1.143:9609/HelloWorldService.svc"); private HelloWorldServiceClient _client; private Button _getHelloWorldDataButton;
  • 33. private TextView _getHelloWorldDataTextView; private Button _sayHelloWorldButton; private TextView _sayHelloWorldTextView; 6. Next, update Main.axml with the following XML: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="0px" android:layout_weight="1"> <Button android:id="@+id/sayHelloWorldButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/say_hello_world" /> <TextView android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/sayHelloWorldTextView" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="0px" android:layout_weight="1"> <Button android:id="@+id/getHelloWorldDataButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/get_hello_world_data" /> <TextView
  • 35. 7. Now with the UI and instance variables in place, modify OnCreate to contain the following code: protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main);
  • 36. InitializeHelloWorldServiceClient(); // This button will invoke the GetHelloWorldData - the method that takes a C# object as a parameter. _getHelloWorldDataButton = FindViewById<Button>(Resource.Id.getHelloWorldDataButton); _getHelloWorldDataButton.Click += GetHelloWorldDataButtonOnClick; _getHelloWorldDataTextView = FindViewById<TextView>(Resource.Id.getHelloWorldDataTextView); // This button will invoke SayHelloWorld - this method takes a simple string as a parameter. _sayHelloWorldButton = FindViewById<Button>(Resource.Id.sayHelloWorldButton); _sayHelloWorldButton.Click += SayHelloWorldButtonOnClick; _sayHelloWorldTextView = FindViewById<TextView>(Resource.Id.sayHelloWorldTextView); } The code above initializes the instance variables for our class and wires up some event handlers. 8. Next we need to instantiate the client proxy class in our Activity. Edit Activity1.cs and add the following two methods to the class: private void InitializeHelloWorldServiceClient() { BasicHttpBinding binding = CreateBasicHttp(); _client = new HelloWorldServiceClient(binding, EndPoint); _client.SayHelloToCompleted += ClientOnSayHelloToCompleted; _client.GetHelloDataCompleted += ClientOnGetHelloDataCompleted; } private static BasicHttpBinding CreateBasicHttp() { BasicHttpBinding binding = new BasicHttpBinding { Name = "basicHttpBinding", MaxBufferSize = 2147483647, MaxReceivedMessageSize = 2147483647 }; TimeSpan timeout = new TimeSpan(0, 0, 30); binding.SendTimeout = timeout; binding.OpenTimeout = timeout; binding.ReceiveTimeout = timeout;
  • 37. return binding; } The code above instantiates and initializes a HelloWorldService object. The WCF proxy class can only call the WCF service asynchronously. Responses from the WCF service will handled by the xxxCompleted events that were generated by SLsvcUtil.exe. 9. Now we need to add the event handlers for the two buttons in our activity. Edit Activity1.cs and add the following two methods: private void GetHelloWorldDataButtonOnClick(object sender, EventArgs eventArgs) { HelloWorldData data = new HelloWorldData { Name = "Mr. Chad", SayHello = true }; _getHelloWorldDataTextView.Text = "Waiting for WCF..."; _client.GetHelloDataAsync(data); } private void SayHelloWorldButtonOnClick(object sender, EventArgs eventArgs) { _sayHelloWorldTextView.Text = "Waiting for WCF..."; _client.SayHelloToAsync("Kilroy"); } 10. Finally, we need to add event handlers for the xxxCompleted events of the HelloWorldService proxy client. Once again edit Activity1.cs and add the following methods: private void ClientOnGetHelloDataCompleted(object sender, GetHelloDataCompletedEventArgs getHelloDataCompletedEventArgs { string msg = null; if (getHelloDataCompletedEventArgs.Error != null) { msg = getHelloDataCompletedEventArgs.Error.Message; } else if (getHelloDataCompletedEventArgs.Cancelled) { msg = "Request was cancelled."; } else
  • 38. { msg = getHelloDataCompletedEventArgs.Result.Name; } RunOnUiThread(() => _getHelloWorldDataTextView.Text = msg); } private void ClientOnSayHelloToCompleted(object sender, SayHelloToCompletedEventArgs sayHelloToCompletedEventArgs) { string msg = null; if (sayHelloToCompletedEventArgs.Error != null) { msg = sayHelloToCompletedEventArgs.Error.Message; } else if (sayHelloToCompletedEventArgs.Cancelled) { msg = "Request was cancelled."; } else { msg = sayHelloToCompletedEventArgs.Result; } RunOnUiThread(() =>_sayHelloWorldTextView.Text = msg); } 11. Run the application, and click on the two buttons. Our application will call the WCF asynchronously. Within 30 seconds a response should be received from each WCF method, and our application should look something like the following screenshot:
  • 39. Now that we have a working Xamarin.Android application, let's create a Xamarin.iOS client.
  • 40. Creating a Xamarin.iOS Application The Xamarin.iOS version is very similar to the Xamarin.Android application and will use the exact same WCF proxy client code that was generated by SLsvcUtil.exe. The following screenshot shows our application after it has successfully interacted with the WCF service that we created earlie in this walkthrough:
  • 41. Let's get started with the Xamarin.iOS application. 1. Start up Xamarin Studio, and open the HelloWorld solution. Add a new iPhone Single View Application to the solution, as shown in the following screenshot:
  • 42. 2. To create the user interface for our application, edit the .XIB in Interface Builder and add two UIButtons and twoUITextViews. Add the outlets for each con
  • 43. according to the following table: Name Text UIButton sayHelloWorldButton Say Hello World UITextView sayHelloWorldText UIButton getHelloWorldDataButton Get Hello World Data UITextView sayHelloWorldText After creating the outlets, the UI should resemble the following screenshot:
  • 44. 3. Next, add the WCF proxy class HelloWorldService.cs to our project by pressing Option-Cmd-A. This will bring up theAdd files dialog which you can us locate and add the file to the project. Once that is done add references toSystem.Runtime.Serialization, System.ServiceModel, and System.ServiceModel.Web just as we did in the Android application. The following screenshot shows Solution Explorer after adding these references:
  • 45.
  • 46. 4. We need to add a couple variables to our view controller that the WCF client code will use. Edit the classXamarin_iOSViewController and add two instanc variables as shown in the following code snippet: public partial class Xamarin_iOSViewController : UIViewController { public static readonly EndpointAddress EndPoint = new EndpointAddress("http://192.168.1.143:9609/HelloWorldService.svc"); private HelloWorldServiceClient _client; You will probably have to change the IP address to that of the computer that is hosting your WCF service. 5. After adding the variable above, update the ViewDidLoad method to include the following code: public override void ViewDidLoad() { base.ViewDidLoad(); InitializeHelloWorldServiceClient(); } 6. Next, add some helper methods to instantiate a HelloWorkdService client proxy instance and hook up a couple event handlers.. Add the following two metho to Xamarin_iOSViewController: private void InitializeHelloWorldServiceClient() { BasicHttpBinding binding = CreateBasicHttp(); _client = new HelloWorldServiceClient(binding, EndPoint); _client.SayHelloToCompleted += ClientOnSayHelloToCompleted; _client.GetHelloDataCompleted += ClientOnGetHelloDataCompleted; getHelloWorldDataButton.TouchUpInside += GetHelloWorldDataButtonTouchUpInside; sayHelloWorldButton.TouchUpInside += SayHelloWorldDataButtonTouchUpInside; }
  • 47. private static BasicHttpBinding CreateBasicHttp() { BasicHttpBinding binding = new BasicHttpBinding { Name = "basicHttpBinding", MaxBufferSize = 2147483647, MaxReceivedMessageSize = 2147483647 }; TimeSpan timeout = new TimeSpan(0, 0, 30); binding.SendTimeout = timeout; binding.OpenTimeout = timeout; binding.ReceiveTimeout = timeout; return binding; } 7. Next, create event handlers for the two UIButtons in the XIB file as shown below: private void SayHelloWorldDataButtonTouchUpInside(object sender, EventArgs e) { sayHelloWorldText.Text = "Waiting for WCF..."; _client.SayHelloToAsync("Kilroy"); } private void GetHelloWorldDataButtonTouchUpInside(object sender, EventArgs e) { getHelloWorldDataText.Text = "Waiting WCF..."; HelloWorldData data = new HelloWorldData { Name = "Mr. Chad", SayHello = true }; _client.GetHelloDataAsync(data); } 8. Finally, add the event handlers for the xxxOnCompleted events that the HelloWorldService proxy client will raise when the WCF service sends a reply ba our application. Add the following two methods to Xamarin_iOSViewController: private void ClientOnGetHelloDataCompleted(object sender, GetHelloDataCompletedEventArgs e) { string msg = null;
  • 48. if (e.Error != null) { msg = e.Error.Message; } else if (e.Cancelled) { msg = "Request was cancelled."; } else { msg = e.Result.Name; } InvokeOnMainThread(() => getHelloWorldDataText.Text = msg); } private void ClientOnSayHelloToCompleted(object sender, SayHelloToCompletedEventArgs e) { string msg = null; if (e.Error != null) { msg = e.Error.Message; } else if (e.Cancelled) { msg = "Request was cancelled."; } else { msg = e.Result; } InvokeOnMainThread(() => sayHelloWorldText.Text = msg); } 9. Now run the application, and click on each of the buttons in the UI. The WCF service will be called asynchronously. Within 30 seconds a response should be rec from each WCF method, and our application should look like the following screenshot:
  • 50. This tutorial covered how to work with a WCF service in a mobile application using Xamarin.Android and Xamarin.iOS. It showed how to create a WCF service and explained how to configure Windows 8 and IIS Express to accept connections from remote devices. It then discussed how to gene a WCF proxy client using the Silverlight Service Model Proxy Generation Tool ( SLsvcUtil.exe) and demonstrated how to use the proxy client in both Xamarin.Android and Xamarin.iOS applications.