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,
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;
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;
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:
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;
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.