WCF .Net API Tutorial
- Glossary
- Introduction
- Connecting your service to the External Application API
- Using markup and commands
- Using the payment gateway
- Tutorial on building your first Mxit app in C#
Glossary
- Device Capabilities
- The capabilities of the user's currently online device, e.g. screen size and support for markup.
- External Application
- A third-party MXit application hosted externally to the MXit platform.
- External Application API
- A Net.TCP Microsoft WCF interface providing access to the MXit platform for application developers.
- MXit Client
- A MXit client application running on e.g. a mobile device or PC that is used by a user to access the MXit platform.
- MXit ID
- The identifier a user uses to log in to MXit. External applications only ever uses the User ID and never the MXit ID.
- MXit Platform
- The environment to which MXit clients connect and the External Application API provides access.
- Presence
- A status indicating whether a user is online or offline.
- User ID
- An identifier that identifies the MXit user uniquely, internally to the MXit platform. External applications only ever uses the User ID and never the MXit ID.
Introduction

The MXit External Application API is aimed at solo software developers or companies with a software development competency who wish to provide rich and dynamic services to MXit users. The technology is built on Microsoft's WCF framework, which is an extension of the .NET framework.
In order to use the API, you need the following:
- Microsoft .NET Framework SDK 3.5 or above
- Microsoft Visual Studio Express 2008 or above
- MXit External Application SDK installer
- Registered MXit service name and password
- Hosting environment
The MXit External Application API web service uses WCF's Net.TCP binding. We chose this to maximise throughput and minimise latency. That means that the web service can only be consumed by WCF supported services and frameworks.
It is vital for application developers to test their application on a variety of mobile devices to ensure correct rendering of the user interface.
Connecting your service to the External Application API
Setting up a new project
Install the External Application SDK, open Visual Studio and create a new project of your choice. This will normally be a Windows service or class library project, but for testing, a console application will suffice. The sample code provided here uses C#.

Next, you need to add MXitExternalAppSDK.dll and System.Drawing.dll as a references. Find the installation location of the MXit library by opening it from your start menu (it will install to MXit Lifestyle\MXit External Application SDK).
You're now ready to add a new service reference. Note that if you haven't added these references, the WSDL cannot be parsed in full and thus the full API won't be available. The endpoint's URI is http://externalappapi.mxit.com:9151/ExternalAppAPI/Comms/mex. We'll use ExternalAppAPI as the namespace. If you are using one of the examples included in the SDK download, be sure to update this service reference before continuing.

Implementing the callback interface
Before a connection can be established, you need to implement the API's CommsCallback interface. Create a new class to service the callbacks. Note the class attribute regarding concurrency: This attribute will ensure that your service utilises WCF's built-in threading mechanism and allow for full duplex communication.
using System.ServiceModel;
[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
internal class Callback : ExternalAppAPI.CommsCallback
{
// Empty class
}
Use Visual Studio to create the required event handlers automatically.

Connecting to the web service
Everything you need to connect is now set up. The following sample shows how to connect to the web service. A keep-alive packet should be sent every few minutes to keep your application's API session alive. You can also add functionality to reconnect in case of a lost connection (not shown here).
namespace ConsoleApplication
{
using System;
using System.ServiceModel;
using System.Threading;
using MXit;
public class Program
{
// Client connection
static ExternalAppAPI.CommsClient client;
public static void Main(string[] args)
{
try
{
// Create a new instance of the class that implements the API's callbacks
ExternalAppAPI.CommsCallback callback = new ExternalAppAPI.Callback();
InstanceContext context = new InstanceContext(callback);
// Create a new client connection
client = new ExternalAppAPI.CommsClient(context);
client.Connect("myservicename", "myservicepassword", SDK.Instance);
Console.WriteLine("Connected");
// Set up a keep-alive timer to keep the connection alive
Timer keepAliveTimer = new Timer(new TimerCallback(KeepAlive),
null,
3 * 60 * 1000,
3 * 60 * 1000);
Console.WriteLine("Press any key to disconnect . . .");
Console.ReadKey(true);
// Clean-up and disconnect
keepAliveTimer.Dispose();
client.Disconnect();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private static void KeepAlive(object stateInfo)
{
client.KeepAlive();
}
}
}
Handling messages and presence
All communication between applications and the API are sent as either message or presence packets. Messages can be plain text messages (e.g. chat messages) or rich messages containing special markup. There are different message types for sending and receiving messages: MessageReceived and IMessageToSend. The easiest way forward is to create the reply from the received message.
public void OnMessageReceived(MessageReceived messageReceived)
{
IMessageToSend messageToSend = messageReceived.CreateReplyMessage();
// ...
}
It is also possible to create your message without a prior request, e.g. to push a notification message to the user. Messages can only be pushed to users that has your application as a contact. Note that the user's presence status (i.e. whether being online or offline) will be unknown to the external application until the user has interacted with it. Until then, the implication is that the capabilities (screen size, support for markup, etc.) of the user's device will be unknown. The application shouldn't assume any capabilities, since the user could be online with a device different from the last time (e.g. switching between mobile and PC MXit client applications).
IMessageToSend msg = (IMessageToSend)MessageBuilder.CreateMessageToSend("theUserId");
Be sure to add the necessary references and using statements for the rest of the sample code in this tutorial to work correctly.
using MXit.Messaging;
using MXit.Messaging.MessageElements;
using MXit.Messaging.MessageElements.Actions;
using MXit.Messaging.MessageElements.Replies;
using MXit.User;
Your application would typically keep a user session, so be sure to clean up a user's session when you receive an offline presence packet. Offline presence is broadcasted to all of the user's contacts and services when the user logs off the MXit platform. Many users simply disconnects from the platform by terminating their MXit client abnormally. In such a case, the platform will timeout their session after roughly 15 minutes, given the user doesn't log in again during that time. Even though offline presence will always be sent under normal circumstances, you should still consider purging old or unused sessions as an optimisation.
public void OnPresenceReceived(Presence userPresence)
{
if (!userPresence.IsOnline)
{
// Clean up session
// ...
}
}
Using markup and commands
The SDK provides you with a number of classes and methods to build messages. The MessageBuilder consists of a large number of appenders to add various elements. Note that a message's body or type never needs to be set by the application: The SDK will set it accordingly.
text markup, clickable link
and emoticon.
![]() |
Text messages
Text messages are the simplest messages that can be sent to a user. This is achieved by simply appending text to your IMessageToSend. The font style and size can be manipulated and standard emoticons can be used.
messageToSend.Append("Hello World! ");
messageToSend.Append(Emoticons.Cool);
messageToSend.AppendLine();
messageToSend.Append("Some bold text", TextMarkup.Bold);
messageToSend.AppendLine();
Inline images
Inline images can be added to text messages. The flow, size and alignment can be adjusted in various ways.
Bitmap imageBitmap = new Bitmap(@"C:\Path\to\image.jpg");
IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(imageBitmap,
ImageAlignment.Center,
TextFlow.AloneOnLine,
imageBitmap.Width,
imageBitmap.Height);
messageToSend.Append(inlineImage);
Clickable links
Clickable links can be appended to messages in order to return a reply to the application when clicked by the user. Be sure to give the link an identifier unique to the application, so that it can identify the response.
IMessageElement link = MessageBuilder.Elements.CreateLink("Unique name to identify this link", // Optional
"How the link must be displayed", // Compulsory
"What to display when the link was clicked", // Optional
"Reply to return to the application"); // Optional
messageToSend.Append(link);
In order to parse the reply, the application must check that the message is of type MessageType.Normal. The message's body can then be checked for the reply message that was set for the link.
private bool IsMyLink(MessageReceived messageReceived)
{
return (messageReceived.Type == MessageType.Normal) &&
(messageReceived.Body == "Reply to return to the application");
}
Advanced markup and commands
![]() |
![]() |
![]() |
||
| A MXit Client showing a popup menu. |
A MXit Client showing the loading progress bar. |
A MXit Client showing a table using an image strip, mixed with an inline image, link and emoticon. |
Advanced markup allows you to build more structured messages, populating the client application's menu and building tables using images and actions.
Chat screen config
To prepare your message to accept advanced markup, a chat screen config must be defined. This config allows one to set the behaviour of the client application's chat screen, such as whether a progress indicator must be displayed while awaiting a response from the application or whether the screen must be cleared before rendering a new message.
Standard items to open the camera, voice recorder or file browser of the user's mobile phone can be added to the client application's menu for your application's tab. User defined items can be used to initiate custom commands.
IPopupMenu clientMenu = MessageBuilder.Elements.CreatePopupMenu();
clientMenu.Add(MenuItemType.UserDefined, "Item 1", "Reply message for item 1");
clientMenu.Add(MenuItemType.UserDefined, "Item 2", "Reply message for item 2");
IMessageElement chatScreenConfig = MessageBuilder.Elements.CreateChatScreenConfig(ChatScreenBehaviourType.Default | ChatScreenBehaviourType.ShowProgress,
clientMenu);
messageToSend.Append(chatScreenConfig);
In order to check whether one of the user defined items in the menu were actioned, check the received message for your reply message for that menu item. The application must ensure that menu items, links, table cells, etc. can be uniquely identified to match a response with a request.
private bool IsItem1(MessageReceived messageReceived)
{
return messageReceived.ExtractReply().ContainsKey("Reply message for item 1");
}
Image strips
Before tables with images can be constructed, the application first needs to register the necessary image strips with the API. Caching your image strips reduces bandwidth overhead between your application and the API, but more importantly, it saves the user bandwidth costs, since the client application will also cache the image strips.
An image strip consists of a number of tiles that are equal in size. The tiles in an image strip are zero indexed. Tiles in the same image strip can be used to define images for a blank table cell, a highlighted cell and a selected cell. Reregistering an image strip (i.e. using the same name) will replace the previous version. The application can also register different sizes of the same image strip to cater for different mobile phone screen sizes. The GetUser method on the client connection will return a UserInfo instance, containing the DeviceInfo for that user, including the screen's width and height.
The layer property determines the order in which tiles are drawn when multiple tiles are set for the same cell. A tile from an image strip with a layer of 0 will be drawn first and then an image from an image strip with a layer of 1, etc.. This is useful where one might have a background tile and a movable piece as another tile (e.g. in Chess or Go).
int tilesInTileStrip = 3;
Bitmap imageStripBitmap = new Bitmap(@"C:\Path\to\imagestrip.jpg");
IImageStripReference imageStrip = client.RegisterImageStrip("uniqueStripName",
imageStripBitmap,
imageStripBitmap.Width / tilesInTileStrip,
imageStripBitmap.Height,
0);
Tables
MXit markup tables are two dimensional grids to lay out text and images. Each cell can be assigned an action to return to the application when selected by the user. Some classic styles are available to quickly get going, but otherwise the borders, margins, padding, flow, colours and alignment can be adjusted as necessary. Tables can be used in two modes: replace and update. Replace mode will cause all data to be transmitted to the user's mobile phone with every request, whereas update mode will only send the differences. We encourage application developers to use the update mode to keep the user's bandwidth costs low. Note that we're using the imageStrip reference defined previously in the following sample code.
Arbitrary data can be attached to a cell as a tag. Note that tags aren't sent to the mobile device, but kept locally as a way for the application to keep state.
Tables cannot be nested, but multiple tables are allowed. Multiple cells cannot be spanned across a row or column.
private ITable GenerateTable(IMessageToSend messageToSend)
{
int tableSize = 3;
ITable table = MessageBuilder.Elements.CreateTable(messageToSend, "uniqueTableName", tableSize, tableSize);
table.SetClassicStyle(Color.Black);
table.SelectionMode = SelectionRectType.Fill;
table.Style.Align = AlignmentType.HorizontalCenter;
table.Mode = TableSendModeType.Replace;
for (int i = 0; i < tableSize; i++)
{
for (int j = 0; j < tableSize; j++)
{
// No padding
table[i, j].Style.Padding.Set(0);
// Attaching arbitrary data to the cell
table[i, j].Tag = string.Format("MyTaggedData{0}{1}", i, j);
// We allow for only one selection, which must automatically cause
// a submit action
Actions.ISelectAction selectAction = table.ActionCreator.Select(1, true);
// We use the tile at index 0 by default
table[i, j].Frames.Set(imageStrip, 0);
// We use the tile at index 1 to highlight a selected cell
selectAction.SelectedFrames.Set(imageStrip, 1);
table[i, j].Action = selectAction;
}
}
return table;
}
This table can now be appended to a message.
messageToSend.Append(GenerateTable(messageToSend));
When a user selects a cell, the selection will immediately be submitted as defined in the previous sample. The selection can be extracted as an ICellCoord.
if (messageReceived.ExtractReply().ContainsKey("uniqueTableName"))
{
ITableReply tableReply = (ITableReply)messageReceived.ExtractReply()["uniqueTableName"];
// There's only one selection to get
ICellCoord coordinate = tableReply.Selected[0];
}
Using the payment gateway
The payment gateway allows you to bill users of your application in MXit Moola. The application initiates the transaction as an asynchronous call. Control of the billing transaction is then transferred to MXit and the MXit user will be presented with a payment summary to either approve or decline. The API will return an asynchronous payment response as soon as the user has made a decision. Control of the transaction is then returned to the application.
![]() |
![]() |
|
| Sequence diagram showing the interactions between the application and API. |
Payment summary presented to the user. |
In case of a successful billing request, the application needs to confirm the request to complete the transaction. Once complete, the application can process the transaction as required.
Note that this interface doesn't provide a micro billing platform, in terms of frequency. Should micro billing be a requirement, the application should charge a fair amount to top up a wallet for that user, controlled by the application. The application can then perform micro billing on that wallet until it needs to be topped up again. There is currently no mechanism provided by this API to debit user accounts. Please contact MXit for more information.
Tutorial on building your first C# app on Mxit
To see an example of how to build your first C# app on Mxit, have a look at this tutorial.






