SlideShare a Scribd company logo
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.HttpRequ
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 = newItemService.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
1
0
1
1
1
2
1
3
1
4
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;
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
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
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 {
39
40
// 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++) {
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
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
SampleCode:
ď‚· 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 back
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:
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 ot
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.
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.
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.
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.
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.
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 HelloWorldDataw
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; }
}
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);
}
}
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 br
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,
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 platf
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:
Configure IIS Express to Accept Remote connections - This step involves editing the config file for IIS Express to accept remote connections on a specific po
then setting up a rule for IIS Express to accept the incoming traffic.
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.
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 XMLsnippet:
<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 th
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>
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
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 compute
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.
Add a new Android project to the solution and name it HelloWorld.Android.
Change the default namespace of the application from HelloWorld.Android to HelloWorld.Droid.
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 commandline:
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 a
shown in the following screenshot:
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:
With the above infrastructure in place, we can finish up the Android application. Edit the file Activity1.cs and add the following instancevariables:
[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;
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:
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.
Next we need to instantiate the client proxy class in our Activity. Edit Activity1.cs and add the following two methods tothe 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 onlycall the WCF service asynchronously.
Responses from the WCF service will handled by the xxxCompleted events that were generated bySLsvcUtil.exe.
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");
}
Finally, we need to add event handlers for the xxxCompleted events of the HelloWorldService proxy client. Once again edit Activity1.cs and add the
followingmethods:
private void ClientOnGetHelloDataCompleted(object sender, GetHelloDataCompletedEventArgs getHelloDataCompletedEventArg
{
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);
}
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 eac
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 earli
in this walkthrough:
Let's get started with the Xamarin.iOS application.
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:
To create the user interface for our application, edit the .XIB in Interface Builder and add two UIButtons and twoUITextViews. Add the outlets for eachcon
according to the followingtable:
Name Text
UIButton sayHelloWorldButton Say HelloWorld
UITextView sayHelloWorldText
UIButton getHelloWorldDataButton Get Hello WorldData
UITextView sayHelloWorldText
After creating the outlets, the UI should resemble the following screenshot:
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:
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 instan
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.
After adding the variable above, update the ViewDidLoad method to include the following code:
public override void ViewDidLoad()
{
base.ViewDidLoad();
InitializeHelloWorldServiceClient();
}
Next, add some helper methods to instantiate a HelloWorkdService client proxy instance and hook up a couple event handlers.. Add the following two meth
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;
}
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);
}
Finally, add the event handlers for the xxxOnCompleted events that the HelloWorldServiceproxy 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);
}
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

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
stratospheres
 
From 0 to Spring Security 4.0
From 0 to Spring Security 4.0From 0 to Spring Security 4.0
From 0 to Spring Security 4.0
robwinch
 
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
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
Dzmitry Naskou
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
Dzmitry Naskou
 
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
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
MongoDB
 
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
 
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
Felipe Prado
 
Client-side Auth with Ember.js
Client-side Auth with Ember.jsClient-side Auth with Ember.js
Client-side Auth with Ember.js
Matthew Beale
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 
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
Micha Kops
 
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
Lauren Elizabeth Tan
 
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
Rodrigo Cândido da Silva
 
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
Aleksandar Ilić
 
AJAX
AJAXAJAX
AJAX
Gouthaman V
 
Url programming
Url programmingUrl programming
Url programming
vantinhkhuc
 
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
Johan Nilsson
 

What's hot (18)

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
 
From 0 to Spring Security 4.0
From 0 to Spring Security 4.0From 0 to Spring Security 4.0
From 0 to Spring Security 4.0
 
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
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
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...
 
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
 
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
 
Client-side Auth with Ember.js
Client-side Auth with Ember.jsClient-side Auth with Ember.js
Client-side Auth with Ember.js
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
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
 
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
 
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
 
AJAX
AJAXAJAX
AJAX
 
Url programming
Url programmingUrl programming
Url programming
 
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
 

Viewers also liked

Show loader to open url in web view
Show loader to open url in web viewShow loader to open url in web view
Show loader to open url in web view
Aravindharamanan S
 
Vortrag ralph behrens_ibm-data
Vortrag ralph behrens_ibm-dataVortrag ralph behrens_ibm-data
Vortrag ralph behrens_ibm-data
Aravindharamanan S
 
Soap toolkits
Soap toolkitsSoap toolkits
Soap toolkits
Aravindharamanan S
 
Net framework
Net frameworkNet framework
Net framework
Aravindharamanan S
 
13 pv-do es-18-bigdata-v3
13 pv-do es-18-bigdata-v313 pv-do es-18-bigdata-v3
13 pv-do es-18-bigdata-v3
Aravindharamanan S
 
Agent technology for e commerce-recommendation systems
Agent technology for e commerce-recommendation systemsAgent technology for e commerce-recommendation systems
Agent technology for e commerce-recommendation systems
Aravindharamanan S
 
Culbert recommender systems
Culbert recommender systemsCulbert recommender systems
Culbert recommender systems
Aravindharamanan S
 
B14200
B14200B14200
Andrei shakirin rest_cxf
Andrei shakirin rest_cxfAndrei shakirin rest_cxf
Andrei shakirin rest_cxf
Aravindharamanan S
 
Big data tutorial_part4
Big data tutorial_part4Big data tutorial_part4
Big data tutorial_part4
Aravindharamanan S
 
Chapter 02 collaborative recommendation
Chapter 02   collaborative recommendationChapter 02   collaborative recommendation
Chapter 02 collaborative recommendation
Aravindharamanan S
 
Json generation
Json generationJson generation
Json generation
Aravindharamanan S
 
0321146182
03211461820321146182
0321146182
Aravindharamanan S
 
Recommender systems session b
Recommender systems session bRecommender systems session b
Recommender systems session b
Aravindharamanan S
 
Sqlite tutorial
Sqlite tutorialSqlite tutorial
Sqlite tutorial
Aravindharamanan S
 
Soap pt1
Soap pt1Soap pt1
Soap pt1
Aravindharamanan S
 
Introduction to visual studio and c sharp
Introduction to visual studio and c sharpIntroduction to visual studio and c sharp
Introduction to visual studio and c sharp
Aravindharamanan S
 
Httpclient tutorial
Httpclient tutorialHttpclient tutorial
Httpclient tutorial
Aravindharamanan S
 

Viewers also liked (18)

Show loader to open url in web view
Show loader to open url in web viewShow loader to open url in web view
Show loader to open url in web view
 
Vortrag ralph behrens_ibm-data
Vortrag ralph behrens_ibm-dataVortrag ralph behrens_ibm-data
Vortrag ralph behrens_ibm-data
 
Soap toolkits
Soap toolkitsSoap toolkits
Soap toolkits
 
Net framework
Net frameworkNet framework
Net framework
 
13 pv-do es-18-bigdata-v3
13 pv-do es-18-bigdata-v313 pv-do es-18-bigdata-v3
13 pv-do es-18-bigdata-v3
 
Agent technology for e commerce-recommendation systems
Agent technology for e commerce-recommendation systemsAgent technology for e commerce-recommendation systems
Agent technology for e commerce-recommendation systems
 
Culbert recommender systems
Culbert recommender systemsCulbert recommender systems
Culbert recommender systems
 
B14200
B14200B14200
B14200
 
Andrei shakirin rest_cxf
Andrei shakirin rest_cxfAndrei shakirin rest_cxf
Andrei shakirin rest_cxf
 
Big data tutorial_part4
Big data tutorial_part4Big data tutorial_part4
Big data tutorial_part4
 
Chapter 02 collaborative recommendation
Chapter 02   collaborative recommendationChapter 02   collaborative recommendation
Chapter 02 collaborative recommendation
 
Json generation
Json generationJson generation
Json generation
 
0321146182
03211461820321146182
0321146182
 
Recommender systems session b
Recommender systems session bRecommender systems session b
Recommender systems session b
 
Sqlite tutorial
Sqlite tutorialSqlite tutorial
Sqlite tutorial
 
Soap pt1
Soap pt1Soap pt1
Soap pt1
 
Introduction to visual studio and c sharp
Introduction to visual studio and c sharpIntroduction to visual studio and c sharp
Introduction to visual studio and c sharp
 
Httpclient tutorial
Httpclient tutorialHttpclient tutorial
Httpclient tutorial
 

Similar to Android+ax+app+wcf

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
Andolasoft Inc
 
Web services in java
Web services in javaWeb services in java
Web services in java
maabujji
 
Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)
Mindfire Solutions
 
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
Saltmarch Media
 
C#on linux
C#on linuxC#on linux
C#on linux
AvarinTalks
 
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
 
AJAX
AJAXAJAX
AJAX
Gouthaman V
 
WCF Fundamentals
WCF Fundamentals WCF Fundamentals
WCF Fundamentals
Safaa Farouk
 
CodeMash 2013 Microsoft Data Stack
CodeMash 2013 Microsoft Data StackCodeMash 2013 Microsoft Data Stack
CodeMash 2013 Microsoft Data Stack
Mike Benkovich
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
Ahmed Madkor
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
Yiguang Hu
 
Express node js
Express node jsExpress node js
Express node js
Yashprit Singh
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
5.node js
5.node js5.node js
5.node js
Geunhyung Kim
 
ASP.NET MVC and ajax
ASP.NET MVC and ajax ASP.NET MVC and ajax
ASP.NET MVC and ajax
Brij Mishra
 
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
 
C#on linux
C#on linuxC#on linux
C#on linux
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
 
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
 
AJAX
AJAXAJAX
AJAX
 
WCF Fundamentals
WCF Fundamentals WCF Fundamentals
WCF Fundamentals
 
CodeMash 2013 Microsoft Data Stack
CodeMash 2013 Microsoft Data StackCodeMash 2013 Microsoft Data Stack
CodeMash 2013 Microsoft Data Stack
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Java servlets
Java servletsJava servlets
Java servlets
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
Express node js
Express node jsExpress node js
Express node js
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
5.node js
5.node js5.node js
5.node js
 
ASP.NET MVC and ajax
ASP.NET MVC and ajax ASP.NET MVC and ajax
ASP.NET MVC and ajax
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 

Recently uploaded

Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
saastr
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Jeffrey Haguewood
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 

Recently uploaded (20)

Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 

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.HttpRequ 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 = newItemService.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 1 0 1 1 1 2 1 3 1 4 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. 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 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 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 { 39 40 // 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. 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 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 SampleCode: ď‚· 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 back
  • 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: 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 ot 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. 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. 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. 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. 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. 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 HelloWorldDataw 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; } } 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); } } 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 br 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, 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 platf 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: Configure IIS Express to Accept Remote connections - This step involves editing the config file for IIS Express to accept remote connections on a specific po then setting up a rule for IIS Express to accept the incoming traffic. 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. 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 XMLsnippet: <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 th 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> 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 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 compute 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. Add a new Android project to the solution and name it HelloWorld.Android. Change the default namespace of the application from HelloWorld.Android to HelloWorld.Droid. 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 commandline: 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 a shown in the following screenshot:
  • 31. 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. With the above infrastructure in place, we can finish up the Android application. Edit the file Activity1.cs and add the following instancevariables: [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; 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. 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. Next we need to instantiate the client proxy class in our Activity. Edit Activity1.cs and add the following two methods tothe 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 onlycall the WCF service asynchronously. Responses from the WCF service will handled by the xxxCompleted events that were generated bySLsvcUtil.exe. 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"); } Finally, we need to add event handlers for the xxxCompleted events of the HelloWorldService proxy client. Once again edit Activity1.cs and add the followingmethods: private void ClientOnGetHelloDataCompleted(object sender, GetHelloDataCompletedEventArgs getHelloDataCompletedEventArg { 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); } 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 eac 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 earli in this walkthrough:
  • 41. Let's get started with the Xamarin.iOS application. 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. To create the user interface for our application, edit the .XIB in Interface Builder and add two UIButtons and twoUITextViews. Add the outlets for eachcon
  • 43. according to the followingtable: Name Text UIButton sayHelloWorldButton Say HelloWorld UITextView sayHelloWorldText UIButton getHelloWorldDataButton Get Hello WorldData UITextView sayHelloWorldText After creating the outlets, the UI should resemble the following screenshot:
  • 44. 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. 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 instan 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. After adding the variable above, update the ViewDidLoad method to include the following code: public override void ViewDidLoad() { base.ViewDidLoad(); InitializeHelloWorldServiceClient(); } Next, add some helper methods to instantiate a HelloWorkdService client proxy instance and hook up a couple event handlers.. Add the following two meth 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; } 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); } Finally, add the event handlers for the xxxOnCompleted events that the HelloWorldServiceproxy 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); } 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.