Xamarin.Android - Create A Chat App Using ASP.NET And SignalR

Introduction

In this article, we shall learn how to create a signalR chat client application using Asp.Net and Xamarin.Android.

What is SignalR?

Signalr is a library for asp.net developer that rearranges the way toward adding ongoing web usefulness to applications. Constant web usefulness is the capacity to have server code push substance to associated customers right away as it winds up noticeably accessible, as opposed to having the server sit tight for a customer to ask for new information.

                      

Prerequisites

You are required to have basic knowledge of asp.net web application and intermediate level of knowledge xamarin.android and basic idea of microsoft azure web app publishing.

  • Asp.net Web application
  • Microsoft Azure account
  • Xamarin Android app
  • SignalR Component
Server Side Application

Step 1

Open Visual Studio-> New Project-> Templates-> Visual C#-> Web -> ASP.NET Web Application. Give the project name SignalR_Server select empty template and hit ok..

(ProjectName: SignalR_Server)

SignalR

SignalR

Step 2

Next go to Solution Explorer-> Project Name-> then Right Click to Add -> HTML Page.

(HtmlPage Name: Index)

SignalR

Step 3

Again go to Solution Explorer-> Project Name-> then Right Click to Add -> New Item-> SignalR Hub Class (v2) with name ChatHub.cs. The hub class essentially is a type of connection that makes connectivity between server and client.

(Class Name: ChatHub.cs) 

SignalR

Step 4

We need to add a Startup class so, go to Solution Explorer-> Project Name-> then Right Click to Add -> New Item-> OWIN Startup Class with name Startup.cs

(Class Name: Startup)

SignalR

Now we need to configure owin startup class. Go to Solution Explorer-> Project Name-> Startup.cs and write following code in startup class.

  1. //Any Connection or Hub wire up and configuration should go here.  
  2. app.MapSignalR();  

SignalR

Step 5

Go to Index page that we created in step 2. Solution Explorer-> Project Name-> Index page and write the following code.

 (File Name:  Index.html) 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>SignalR Chat Application</title>  
  5.     <style type="text/css">  
  6.         .container {  
  7.             background-color: #800000;  
  8.             border: thick solid #808080;  
  9.             padding: 20px;  
  10.             margin: 20px;  
  11.             color: azure;  
  12.             font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;  
  13.         }  
  14.     </style>  
  15. </head>  
  16. <body>  
  17.     <div class="container">  
  18.         <input type="text" id="message" placeholder="Write your message here!"/>  
  19.         <input type="button" id="sendmessage" value="Send" />  
  20.         <input type="hidden" id="displayname" />  
  21.         <ul id="discussion"></ul>  
  22.     </div>  
  23.     <!--Script references. -->  
  24.     <!--Reference the jQuery library. -->  
  25.     <script src="Scripts/jquery-3.2.1.min.js"></script>  
  26.     <script src="/Scripts/jquery-1.6.4.min.js"></script>  
  27.     <!--Reference the SignalR library. -->  
  28.     <script src="/Scripts/jquery.signalR-1.1.4.js"></script>  
  29.     <script src="Scripts/jquery.signalR-2.2.2.js"></script>  
  30.     <!--Reference the autogenerated SignalR hub script. -->  
  31.     <script src="/signalr/hubs"></script>  
  32.     <!--Add script to update the page and send messages.-->  
  33.     <script type="text/javascript">  
  34.   
  35.         $(function () {  
  36.             // Declare a proxy to reference the hub.  
  37.             var chat = $.connection.chatHub;  
  38.             // Create a function that the hub can call to broadcast messages.  
  39.             chat.client.broadcastMessage = function (name, message) {  
  40.                 // Html encode display name and message.  
  41.                 var encodedName = $('<div />').text(name).html();  
  42.                 var encodedMsg = $('<div />').text(message).html();  
  43.                 // Add the message to the page.  
  44.                 $('#discussion').append('<li><strong>' + encodedName  
  45.                     + '</strong>:  ' + encodedMsg + '</li>');  
  46.             };  
  47.             // Get the user name and store it to prepend to messages.  
  48.             $('#displayname').val(prompt('Enter your name:'''));  
  49.             // Set initial focus to message input box.  
  50.             $('#message').focus();  
  51.             // Start the connection.  
  52.             $.connection.hub.start().done(function () {  
  53.                 $('#sendmessage').click(function () {  
  54.                     // Call the Send method on the hub.  
  55.                     chat.server.send($('#displayname').val(), $('#message').val());  
  56.                     // Clear text box and reset focus for next comment.  
  57.                     $('#message').val('').focus();  
  58.                 });  
  59.             });  
  60.         });  
  61.     </script>  
  62. </body>  
  63. </html>  

Step 6

Next go to Solution Explorer-> Project Name-> ChatHub then create a chathub class and replace following code with Hello method.

(File Name:  ChatHub.cs) 

  1. public void Send(string name, string message)  
  2.         {  
  3.             // Call the broadcastMessage method to update clients.  
  4.             Clients.All.broadcastMessage(name, message);  
  5.         }  
  6.   
  7.         public void SendMessage(string message, int color,string username)  
  8.         {  
  9.             Clients.All.UpdateChatMessage(message, color, username);  
  10.         }  

Step 7

Bulid and run the project.
 
 
Step 8

Go to Solution Explorer-> Project Name-> then Right Click -> Publish.

SignalR 

SignalR

SignalR

This service successfully publish on microsoft azure. Now everyone can use and access this service from given url.

http://azuresignalrserver.azurewebsites.net/

Output

SignalR

SignalR

Client Side

Step 1

Open Visual Studio-> New Project-> Templates-> Visual C#-> Android-> Blank app and give the project name SignalR_Client.

(ProjectName: SignalR_Client)

SignalR

Step 2

Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml. Open main.axml file and add following code.

(FileName: Main.axml)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#FFF">  
  6.     <ScrollView  
  7.         android:id="@+id/scrolview"  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="match_parent"  
  10.         android:background="#E2E2E2"  
  11.         android:layout_alignParentTop="true"  
  12.         android:layout_above="@+id/llContainer">  
  13.         <LinearLayout  
  14.             android:id="@+id/llChatMessage"  
  15.             android:layout_height="match_parent"  
  16.             android:layout_width="match_parent"  
  17.             android:orientation="vertical" />  
  18.     </ScrollView>  
  19.     <LinearLayout  
  20.         android:id="@+id/llChatMessage"  
  21.         android:layout_height="wrap_content"  
  22.         android:layout_width="match_parent"  
  23.         android:orientation="vertical"  
  24.         android:layout_alignParentBottom="true">  
  25.         <Button  
  26.             android:id="@+id/btnSend"  
  27.             android:layout_height="wrap_content"  
  28.             android:layout_width="match_parent"  
  29.             android:text="Send" />  
  30.         <EditText  
  31.             android:id="@+id/txtChat"  
  32.             android:layout_height="wrap_content"  
  33.             android:layout_width="match_parent"  
  34.             android:textColor="#000"  
  35.             android:textCursorDrawable="@null" />  
  36.     </LinearLayout>  
  37. </RelativeLayout>  

SignalR  SignalR

Step 3

Go to Solution Explorer-> Project Name then Right Click to Add new Item and select Fragment and give name GetInfo and add following code with appropriate namespaces.

(FileName: GetInfo.cs)

SignalR

Dialog Fragment C# Code 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. using Android.App;  
  7. using Android.Content;  
  8. using Android.OS;  
  9. using Android.Runtime;  
  10. using Android.Util;  
  11. using Android.Views;  
  12. using Android.Widget;  
  13.   
  14. namespace SignalR_Client  
  15. {  
  16.     public class GetInfo : DialogFragment  
  17.     {  
  18.         public class OnGetInfoCompleteEventArgs : EventArgs  
  19.         {  
  20.             public string TxtName { get; set; }  
  21.             public int BackgroundColor { get; set; }  
  22.         }  
  23.         public event EventHandler<OnGetInfoCompleteEventArgs> OnGetInfoComplete;  
  24.         public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)  
  25.         {  
  26.             // Use this to return your custom view for this Fragment  
  27.             // return inflater.Inflate(Resource.Layout.YourFragment, container, false);  
  28.   
  29.             View view = inflater.Inflate(Resource.Layout.getInfo, container, false);  
  30.             EditText txtName = view.FindViewById<EditText>(Resource.Id.txtName);  
  31.             Button btnOkay = view.FindViewById<Button>(Resource.Id.btnOkay);  
  32.             RadioGroup radioGroup = view.FindViewById<RadioGroup>(Resource.Id.radioGroup);  
  33.   
  34.             btnOkay.Click += (o, e) =>  
  35.             {  
  36.                 var args = new OnGetInfoCompleteEventArgs { TxtName = txtName.Text.Trim() };  
  37.                 switch (radioGroup.CheckedRadioButtonId)  
  38.                 {  
  39.                     case Resource.Id.radioRed:  
  40.                         args.BackgroundColor = 1;  
  41.                         break;  
  42.                     case Resource.Id.radioGreen:  
  43.                         args.BackgroundColor = 2;  
  44.                         break;  
  45.                     case Resource.Id.radioBlue:  
  46.                         args.BackgroundColor = 3;  
  47.                         break;  
  48.                 }  
  49.                 OnGetInfoComplete.Invoke(this, args);  
  50.   
  51.                 Dismiss();  
  52.             };  
  53.             return view;  
  54.         }  
  55.         public override void OnActivityCreated(Bundle savedInstanceState)  
  56.         {  
  57.             Dialog.Window.RequestFeature(WindowFeatures.NoTitle);  
  58.             base.OnActivityCreated(savedInstanceState);  
  59.         }  
  60.     }  
  61. }  

Step 3

Next open Solution Explorer-> Project Name-> Resources-> Layout-> then Right Click to Add new Layout give the name getInfo and add the following code in getInfo.axml.

(FileName: getInfo.axml)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:padding="20dp"  
  7.     android:background="#808080"  
  8.     android:minWidth="400dp"  
  9.     android:minHeight="200dp">  
  10.     <EditText  
  11.         android:id="@+id/txtName"  
  12.         android:layout_width="match_parent"  
  13.         android:layout_height="wrap_content"  
  14.         android:textColor="#000"  
  15.         android:hint="UserName" />  
  16.     <LinearLayout  
  17.         android:layout_width="match_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:orientation="horizontal">  
  20.         <View  
  21.             android:layout_width="match_parent"  
  22.             android:layout_height="20dp"  
  23.             android:layout_margin="5dp"  
  24.             android:background="#FF0000"  
  25.             android:layout_weight="33" />  
  26.         <View  
  27.             android:layout_width="match_parent"  
  28.             android:layout_height="20dp"  
  29.             android:layout_margin="5dp"  
  30.             android:background="#00FF00"  
  31.             android:layout_weight="33" />  
  32.         <View  
  33.             android:layout_width="match_parent"  
  34.             android:layout_height="20dp"  
  35.             android:layout_margin="5dp"  
  36.             android:background="#0000FF"  
  37.             android:layout_weight="33" />  
  38.     </LinearLayout>  
  39.     <LinearLayout  
  40.         android:layout_width="match_parent"  
  41.         android:layout_height="wrap_content"  
  42.         android:orientation="horizontal">  
  43.         <RadioGroup  
  44.             android:id="@+id/radioGroup"  
  45.             android:layout_width="match_parent"  
  46.             android:layout_height="wrap_content"  
  47.             android:orientation="horizontal">  
  48.             <RadioButton  
  49.                 android:id="@+id/radioRed"  
  50.                 android:layout_width="wrap_content"  
  51.                 android:layout_height="wrap_content"  
  52.                 android:layout_weight="33"  
  53.                 android:layout_margin="5dp"  
  54.                 android:text="Red" />  
  55.             <RadioButton  
  56.                 android:id="@+id/radioGreen"  
  57.                 android:layout_width="wrap_content"  
  58.                 android:layout_height="wrap_content"  
  59.                 android:layout_weight="33"  
  60.                 android:layout_margin="5dp"  
  61.                 android:text="Green" />  
  62.             <RadioButton  
  63.                 android:id="@+id/radioBlue"  
  64.                 android:layout_width="wrap_content"  
  65.                 android:layout_height="wrap_content"  
  66.                 android:layout_weight="33"  
  67.                 android:layout_margin="5dp"  
  68.                 android:text="Blue" />  
  69.         </RadioGroup>  
  70.     </LinearLayout>  
  71.     <Button  
  72.         android:id="@+id/btnOkay"  
  73.         android:layout_width="wrap_content"  
  74.         android:layout_height="wrap_content"  
  75.         android:text="Okay"  
  76.         android:layout_gravity="center_horizontal"  
  77.         android:padding="10dp" />  
  78. </LinearLayout>   

SignalR  SignalR   

Step 4

Go to Solution Explorer-> Components -> then Right Click-> Get More Components. In this way, you can move on xamarin components store then search SignalR and add to app.

SignalR

Step 5

Solution Explorer-> Project Name-> MainActivity file and add following code and use appropriate namespaces. 
(FileName: GetInfo.cs)

MainActivity C# Code 
  1. using Android.App;  
  2. using Android.Widget;  
  3. using Android.OS;  
  4. using Microsoft.AspNet.SignalR.Client;  
  5. using System;  
  6. using Android.Content.Res;  
  7. using Android.Views;  
  8.   
  9. namespace SignalR_Client  
  10. {  
  11.     [Activity(Label = "SignalR_Client", MainLauncher = true)]  
  12.     public class MainActivity : Activity  
  13.     {  
  14.         public string UserName { get; set; }  
  15.         public int BackgroungColor { get; set; }  
  16.         protected override void OnCreate(Bundle savedInstanceState)  
  17.         {  
  18.             base.OnCreate(savedInstanceState);  
  19.   
  20.             // Set our view from the "main" layout resource  
  21.             SetContentView(Resource.Layout.Main);  
  22.   
  23.             GetInfo getinfo = new GetInfo();  
  24.             getinfo.OnGetInfoComplete += Getinfo_OnGetInfoComplete;  
  25.             getinfo.Show(FragmentManager, "GetInfo");  
  26.         }  
  27.   
  28.         private async void Getinfo_OnGetInfoComplete(object sender, GetInfo.OnGetInfoCompleteEventArgs e)  
  29.         {  
  30.             UserName = e.TxtName;  
  31.             BackgroungColor = e.BackgroundColor;  
  32.   
  33.             var hubConnection = new HubConnection("http://azuresignalrserver.azurewebsites.net/");  
  34.             var chatHubProxy = hubConnection.CreateHubProxy("ChatHub");  
  35.   
  36.             chatHubProxy.On<string, int, string>("UpdateChatMessage", (message, color, user) =>   
  37.             {  
  38.                 //UpdateChatMessage has been called from Sever  
  39.   
  40.                 RunOnUiThread(() =>  
  41.                 {  
  42.                     TextView txt = new TextView(this);  
  43.                     txt.Text = user + ": " + message;  
  44.                     txt.SetTextSize(Android.Util.ComplexUnitType.Sp, 20);  
  45.                     txt.SetPadding(10, 10, 10, 10);  
  46.   
  47.                     switch (color)  
  48.                     {  
  49.                         case 1:  
  50.                             txt.SetTextColor(Android.Graphics.Color.Red);  
  51.                             break;  
  52.                         case 2:  
  53.                             txt.SetTextColor(Android.Graphics.Color.MediumSeaGreen);  
  54.                             break;  
  55.                         case 3:  
  56.                             txt.SetTextColor(Android.Graphics.Color.Blue);  
  57.                             break;  
  58.                         default:  
  59.                             txt.SetTextColor(Android.Graphics.Color.Black);  
  60.                             break;  
  61.                     }  
  62.   
  63.                     txt.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent)  
  64.                     {  
  65.                         TopMargin = 10,  
  66.                         BottomMargin = 10,  
  67.                         LeftMargin = 10,  
  68.                         RightMargin = 10,  
  69.                         Gravity = GravityFlags.Right  
  70.                     };  
  71.   
  72.                     FindViewById<LinearLayout>(Resource.Id.llChatMessage).AddView(txt);  
  73.   
  74.                 });  
  75.             });  

  76.             try  
  77.             {  
  78.                 await hubConnection.Start();  
  79.             }  
  80.             catch (Exception ex)  
  81.             {   
  82.                 Console.WriteLine(ex.ToString());  
  83.             }  
  84.   
  85.             FindViewById<Button>(Resource.Id.btnSend).Click += async (o, e2) =>  
  86.             {  
  87.                 var message = FindViewById<EditText>(Resource.Id.txtChat).Text;  
  88.                 await chatHubProxy.Invoke("SendMessage"new object[] { message, BackgroungColor, UserName });  
  89.             };  
  90.         }  
  91.     }  
  92. }  

OutPut

 

Summary

  • What is SiganlR
  • Asp.Net Web Application
  • Publish to Azure
  • Xamrin.Android Application
  • Output


Similar Articles