XamChat – a Cross-platform App

Exclusive offer: get 50% off this eBook here
Xamarin Cross-platform Application Development

Xamarin Cross-platform Application Development — Save 50%

Develop production-ready applications for iOS and Android using Xamarin with this book and ebook

$26.99    $13.50
by Jonathan Peppers | February 2014 | Open Source

This article is written by Jonathan Peppers, the author of Xamarin Cross-platform Application Development. Xamarin technologies are used to develop real-world applications for iOS and Android. This article explains the concept of a cross-platform sample application that we can build using Xamarin Studio.

The best way to truly learn a programming skill, in our opinion, is to take on a simple project that requires you to exercise that skill. This gives new developers a project where they can focus on the concepts they are trying to learn without the overhead of fixing bugs or following customer requirements. To increase our understanding of Xamarin Studio and cross-platform development, let's develop a simple app called XamChat for iOS and Android.

In this article, we will cover the following topics:

  • Our sample application concept
  • The Model layer of our application
  • Mocking a web service
  • The ViewModel layer of our application

(For more resources related to this topic, see here.)

Describing our sample application concept

The concept is simple: a chat application that uses a standard Internet connection as an alternative to sending text messages. There are several popular applications like this in the Apple App Store, probably due to the cost of text messaging and support for devices such as the iPod Touch or iPad. This should be a neat real-world example that could be useful for users, and will cover specific topics in developing applications for iOS and Android.

Before starting with the development, let's list the set of screens that we'll need:

  • Login / sign up: This screen will include a standard login and sign-up process for the user
  • List of conversations: This screen will include a button to start a new conversation
  • List of friends: This screen will provide a way to add new friends when we start a new conversation
  • Conversation: This screen will have a list of messages between you and another user, and an option to reply

A quick wireframe layout of the application would help us grasp a better understanding of the layout of the app. The following figure shows the set of screens to be included in your app:

Developing our model layer

Since we have a good idea of what the application is, the next step is to develop the business objects or model layer of this application. Let's start out by defining a few classes that would contain the data to be used throughout the app. It is recommended, for the sake of organization, to add these to a Models folder in your project.

Let's begin with a class representing a user. The class can be created as follows:

public class User {   public int Id { get; set; }   public string Username { get; set; }   public string Password { get; set; } }

Pretty straightforward so far; let's move on to create classes representing a conversation and a message as follows:

public class Conversation {   public int Id { get; set; }   public int UserId { get; set; }   public string Username { get; set; } } public class Message {   public int Id { get; set; }   public int ConversationId { get; set; }   public int UserId { get; set; }   public string Username { get; set; }   public string Text { get; set; } }

Notice that we are using integers as identifiers for the various objects. UserId is the value that would be set by the application to change the user that the object is associated with.

Now let's go ahead and set up our solution by performing the following steps:

  1. Start by creating a new solution and a new C# Library project.
  2. Name the project as XamChat.Core and the solution as XamChat.
  3. Next, let's set the library to a Mono / .NET 4.5 project. This setting is found in the project option dialog under Build | General | Target Framework.
  4. You could also choose to use Portable Library for this project,

Writing a mock web service

Many times when developing a mobile application, you may need to begin the development of your application before the real backend web service is available. To prevent the development from halting entirely, a good approach would be to develop a mock version of the service.

First, let's break down the operations our app will perform against a web server. The operations are as follows:

  1. Log in with a username and password.
  2. Register a new account.
  3. Get the user's list of friends.
  4. Add friends by their usernames.
  5. Get a list of the existing conversations for the user.
  6. Get a list of messages in a conversation.
  7. Send a message.

Now let's define an interface that offers a method for each scenario. The interface is as follows:

public interface IWebService {   Task<User> Login(string username, string password);   Task<User> Register(User user);   Task<User[]> GetFriends(int userId);   Task<User> AddFriend(int userId, string username);   Task<Conversation[]> GetConversations(int userId);   Task<Message[]> GetMessages(int conversationId);   Task<Message> SendMessage(Message message); }

As you see, we're using asynchronous communication with the TPL(Task Parallel Library) technology.

Since communicating with a web service can be a lengthy process, it is always a good idea to use the Task<T> class for these operations. Otherwise, you could inadvertently run a lengthy task on the user interface thread, which would prevent user inputs during the operation. Task is definitely needed for web requests, since users could easily be using a cellular Internet connection on iOS and Android, and it will give us the ability to use the async and await keywords down the road.

Now let's implement a fake service that implements this interface. Place classes such as FakeWebService in the Fakes folder of the project. Let's start with the class declaration and the first method of the interface:

public class FakeWebService {   public int SleepDuration { get; set; }   public FakeWebService()   {     SleepDuration = 1;   }   private Task Sleep()   {     return Task.Delay(SleepDuration);   }   public async Task<User> Login(     string username, string password)   {     await Sleep();     return new User { Id = 1, Username = username };   } }

We started off with a SleepDuration property to store a number in milliseconds. This is used to simulate an interaction with a web server, which can take some time. It is also useful for changing the SleepDuration value in different situations. For example, you might want to set this to a small number when writing unit tests so that the tests execute quickly.

Next, we implemented a simple Sleep method to return a task that introduce delays of a number of milliseconds. This method will be used throughout the fake service to cause a delay on each operation.

Finally, the Login method merely used an await call on the Sleep method and returned a new User object with the appropriate Username. For now, any username or password combination will work; however, you may wish to write some code here to check specific credentials.

Now, let's implement a few more methods to continue our FakeWebService class as follows:

public async Task<User> Register(User user) {   await Sleep();   return user; } public async Task<User[]> GetFriends(int userId) {   await Sleep();   return new[]   {     new User { Id = 2, Username = "bobama" },     new User { Id = 2, Username = "bobloblaw" },     new User { Id = 3, Username = "gmichael" },   }; } public async Task<User> AddFriend(   int userId, string username) {   await Sleep();   return new User { Id = 4, Username = username }; }

For each of these methods, we kept in mind exactly same pattern as the Login method. Each method will delay and return some sample data. Feel free to mix the data with your own values.

Now, let's implement the GetConversations method required by the interface as follows:

public async Task<Conversation[]> GetConversations(int userId) {   await Sleep();   return new[]   {     new Conversation { Id = 1, UserId = 2 },     new Conversation { Id = 1, UserId = 3 },     new Conversation { Id = 1, UserId = 4 },   }; }

Basically, we just create a new array of the Conversation objects with arbitrary IDs. We also make sure to match up the UserId values with the IDs we've used on the User objects so far.

Next, let's implement GetMessages to retrieve a list of messages as follows:

public async Task<Message[]> GetMessages(int conversationId) {   await Sleep();   return new[]   {     new Message     {       Id = 1,       ConversationId = conversationId,       UserId = 2,       Text = "Hey",     },     new Message     {       Id = 2,       ConversationId = conversationId,       UserId = 1,       Text = "What's Up?",     },     new Message     {       Id = 3,       ConversationId = conversationId,       UserId = 2,       Text = "Have you seen that new movie?",     },     new Message     {       Id = 4,       ConversationId = conversationId,       UserId = 1,       Text = "It's great!",     },   }; }

Once again, we are adding some arbitrary data here, and mainly making sure that UserId and ConversationId match our existing data so far.

And finally, we will write one more method to send a message as follows:

public async Task<Message> SendMessage(Message message) {   await Sleep();   return message; }

Most of these methods are very straightforward. Note that the service doesn't have to work perfectly; it should merely complete each operation successfully with a delay. Each method should also return test data of some kind to be displayed in the UI. This will give us the ability to implement our iOS and Android applications while filling in the web service later.

Next, we need to implement a simple interface for persisting application settings. Let's define an interface named ISettings as follows:

public interface ISettings {   User User { get; set; }   void Save(); }

Note that you might want to set up the Save method to be asynchronous and return Task if you plan on storing settings in the cloud. We don't really need this with our application since we will only be saving our settings locally.

Later on, we'll implement this interface on each platform using Android and iOS APIs. For now, let's just implement a fake version that will be used later when we write unit tests. The interface is created by the following lines of code:

public class FakeSettings : ISettings {   public User User { get; set; }   public void Save() { } }

Note that the fake version doesn't actually need to do anything; we just need to provide a class that will implement the interface and not throw any unexpected errors.

This completes the Model layer of the application. Here is a final class diagram of what we have implemented so far:

Xamarin Cross-platform Application Development Develop production-ready applications for iOS and Android using Xamarin with this book and ebook
Published: February 2014
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Writing the ViewModel layer

Now that we have our model layer implemented, we can move on to write the ViewModel layer. The ViewModel will be responsible for presenting each operation to the UI and offering properties to be filled out by the View layer. Other common responsibilities of this layer are input validation and simple logic to display busy indicators.

At this point, it would be a good idea to include the ServiceContainer class in our XamChat.Core project, as we will be using it through our ViewModels to interact with the Model layer. We will be using it as a simple option to support dependency injection and Inversion of Control; however, you may use another library of your preference for this.

Normally, we start off by writing a base class for all the ViewModel layers within our project. This class always has the functionality shared by all the classes. It's a good place to put some parts of the code that are used by all the methods in the classes; for example, notification changes, methods, or similar instances.

Place the following code snippet in a new ViewModels folder within your project:

public class BaseViewModel {   protected readonly IWebService service =     ServiceContainer.Resolve<IWebService>();   protected readonly ISettings settings =     ServiceContainer.Resolve<ISettings>();   public event EventHandler IsBusyChanged = delegate { };   private bool isBusy = false;   public bool IsBusy   {     get { return isBusy; }     set     {       isBusy = value;       IsBusyChanged(this, EventArgs.Empty);     }   } }

The BaseViewModel class is a great place to insert any common functionality that you plan on reusing throughout your application. For this app, we only need to implement some functionality to indicate if the ViewModel layer is busy. We provided a property and an event that the UI will be able to subscribe to and display a wait indicator on the screen. We also added some fields for the services that will be needed. Another common feature that could be added would be validation for user inputs; however, we don't really need it for this application.

Implementing our LoginViewModel class

Now that we have a base class for all of the ViewModel layers, we can implement ViewModel for the first screen in our application, the Login screen.

Now let's implement a LoginViewModel class as follows:

public class LoginViewModel : BaseViewModel {   public string Username { get; set; }   public string Password { get; set; }   public async Task Login()   {     if (string.IsNullOrEmpty(Username))       throw new Exception("Username is blank.");     if (string.IsNullOrEmpty(Password))       throw new Exception("Password is blank.");     IsBusy = true;     try     {       settings.User = await service         .Login(Username, Password);       settings.Save();     }     finally     {       IsBusy = false;     }   } }

In this class, we implemented the following:

  • We subclassed BaseViewModel to get access to IsBusy and the fields containing common services
  • We added the Username and Password properties to be set by the View layer
  • We added a User property to be set when the log in process is completed
  • We implemented a Login method to be called from View, with validation on Username and Password properties
  • We set IsBusy during the call to the Login method on IWebService
  • We set the User property by awaiting the result from Login on the web service

Basically, this is the pattern that we'll follow for the rest of the ViewModels in the application. We provide properties for the View layer to be set by the user's input, and methods to call for various operations. If it is a method that could take some time, such as a web request, you should always return Task and use the async and await keywords.

Note that we used a try and finally block for setting IsBusy back to false. This will ensure it gets reset properly even when an exception is thrown. We plan on handling the error in the View layer, so we can display a native pop up to the user displaying a message.

Implementing our RegisterViewModel class

Since we have finished writing our ViewModel class to log in, we will now need to create one for the user's registration.

Let's implement another ViewModel to register a new user:

public class RegisterViewModel : BaseViewModel {   public string Username { get; set; }   public string Password { get; set; }   public string ConfirmPassword { get; set; } }

These properties will handle inputs from the user. Next, we need to add a Register method as follows:

public async Task Register() {   if (string.IsNullOrEmpty(Username))     throw new Exception("Username is blank.");   if (string.IsNullOrEmpty(Password))     throw new Exception("Password is blank.");   if (Password != ConfirmPassword)     throw new Exception("Passwords don't match.");   IsBusy = true;   try   {     settings.User = await service       .Register(new User { Username = Username,         Password = Password, });     settings.Save();   }   finally   {     IsBusy = false;   } }

The RegisterViewModel class is very similar to the LoginViewModel class, but has an additional ConfirmPassword property for the UI to set. A good rule to follow for when to split up the ViewModel layer's functionality is to always create a new class when the UI has a new screen. This helps to keep your code clean and somewhat follow the single responsibility principle for your classes. This concept states that a class should only have a single purpose or responsibility. We'll try to follow this concept to keep our classes small and organized, which can be more important than usual when sharing code across platforms.

Implementing our FriendViewModel class

Next on the list is a ViewModel layer to work with a user's friend list. We will need a method to load a user's friend list and add a new friend.

Now let's implement the FriendViewModel as follows:

public class FriendViewModel : BaseViewModel {   public User[] Friends { get; private set; }   public string Username { get; set; } }

Now we'll need a method to load friends. This method is as follows:

public async Task GetFriends() {   if (settings.User == null)     throw new Exception("Not logged in.");   IsBusy = true;   try   {     Friends = await service       .GetFriends(settings.User.Id);   }   finally   {     IsBusy = false;   } }

Finally, we'll need a method to add a new friend, and then update the list of friends contained locally:

public async Task AddFriend() {   if (settings.User == null)     throw new Exception("Not logged in.");   if (string.IsNullOrEmpty(Username))     throw new Exception("Username is blank.");   IsBusy = true;   try   {     var friend = await service       .AddFriend(settings.user.Id, Username); //Update our local list of friends     var friends = new List<User>();     if (Friends != null)       friends.AddRange(Friends);     friends.Add(friend);     Friends = friends       .OrderBy(f => f.Username)         .ToArray();   }   finally   {     IsBusy = false;   } }

Again, this class is fairly straightforward. The only thing new here is that we added some logic to update the list of friends and sort them within our client application and not the server. You could also choose to reload the complete list of friends if you have a good reason to do so.

Implementing our MessageViewModel class

Our final required ViewModel layer will be handling messages and conversations. We need to create a way to load conversations and messages, and send a new message.

Let's start implementing our MessageViewModel class as follows:

public class MessageViewModel : BaseViewModel {   public Conversation[] Conversations { get; private set; }   public Conversation Conversation { get; set; }   public Message[] Messages { get; private set; }   public string Text { get; set; } }

Next, let's implement a method to retrieve a list of conversations as follows:

public async Task GetConversations() {   if (settings.User == null)     throw new Exception("Not logged in.");   IsBusy = true;   try   {     Conversations = await service       .GetConversations(settings.User.Id);   }   finally   {     IsBusy = false;   } }

Similarly, we need to retrieve a list of messages within a conversation. We will need to pass the conversation ID to the service as follows:

public async Task GetMessages() {   if (Conversation == null)     throw new Exception("No conversation.");   IsBusy = true;   try   {     Messages = await service       .GetMessages(Conversation.Id);   }   finally   {     IsBusy = false;   } }

Finally, we need to write some code to send a message and update the local list of messages as follows:

public async Task SendMessage() {   if (settings.User == null)     throw new Exception("Not logged in.");   if (Conversation == null)     throw new Exception("No conversation.");   if (string.IsNullOrEmpty (Text))     throw new Exception("Message is blank.");   IsBusy = true;   try   {     var message = await service.SendMessage( new Message {   UserId = settings.User.Id,   ConversationId = Conversation.Id,   Text = Text, }); //Update our local list of messages     var messages = new List<Message>();     if (Messages != null)       messages.AddRange(Messages);     messages.Add(message);     Messages = messages.ToArray();   }   finally   {     IsBusy = false;   } }

This concludes the ViewModel layer of our application and the entirety of the shared code used on iOS and Android. For the MessageViewModel class, you could have also chosen to put GetConversations and Conversations properties in their own class, since they could be considered as a separate responsibility, but it is not really necessary.

Here is the final class diagram of our ViewModel layer:

Summary

In this article, we went over the concept for a sample application called XamChat. We also implemented the core business objects for the application in the Model layer. Since we do not have a server to support this application yet, we implemented a fake web service. This gives us the flexibility to move forward with the app without building a server application. We also implemented the ViewModel layer. This layer will expose operations in a simple way to the View layer.

Resources for Article:


Further resources on this subject:


Xamarin Cross-platform Application Development Develop production-ready applications for iOS and Android using Xamarin with this book and ebook
Published: February 2014
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Jonathan Peppers

Jonathan Peppers  is a Xamarin MVP and the lead developer of the popular cross-platform game, Draw a Stickman: EPIC. Jon works for Hitcents, a software development company based in Bowling Green, Kentucky. He has been working with the C# programming language for over 7 years. He has also been working with technologies such as WinForms, WPF, ASP.NET WebForms, and ASP.NET MVC. In recent years, Hitcents has been heavily investing in mobile development with Xamarin and has developed nearly 40 mobile applications across multiple platforms.

Books From Packt


Xamarin Mobile Application Development for iOS
Xamarin Mobile Application Development for iOS

Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API

Android Application Security Essentials
Android Application Security Essentials

WordPress Mobile Applications with PhoneGap
WordPress Mobile Applications with PhoneGap

Android Development Tools for Eclipse
Android Development Tools for Eclipse

PhoneGap Mobile Application Development Cookbook
PhoneGap Mobile Application Development Cookbook

PhoneGap 2.x Mobile Application Development Hotshot
PhoneGap 2.x Mobile Application Development Hotshot

Xamarin Mobile Application Development for Android
Xamarin Mobile Application Development for Android


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
F
G
W
s
S
p
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software