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
Step 1
(ProjectName: SignalR_Server)


Step 2
Next go to Solution Explorer-> Project Name-> then Right Click to Add -> HTML Page.
(HtmlPage Name: Index)

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)

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)

Now we need to configure owin startup class. Go to Solution Explorer-> Project Name-> Startup.cs and write following code in startup class.
- //Any Connection or Hub wire up and configuration should go here.
- app.MapSignalR();

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)
- <!DOCTYPE html>
- <html>
- <head>
- <title>SignalR Chat Application</title>
- <style type="text/css">
- .container {
- background-color: #800000;
- border: thick solid #808080;
- padding: 20px;
- margin: 20px;
- color: azure;
- font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <input type="text" id="message" placeholder="Write your message here!"/>
- <input type="button" id="sendmessage" value="Send" />
- <input type="hidden" id="displayname" />
- <ul id="discussion"></ul>
- </div>
- <!--Script references. -->
- <!--Reference the jQuery library. -->
- <script src="Scripts/jquery-3.2.1.min.js"></script>
- <script src="/Scripts/jquery-1.6.4.min.js"></script>
- <!--Reference the SignalR library. -->
- <script src="/Scripts/jquery.signalR-1.1.4.js"></script>
- <script src="Scripts/jquery.signalR-2.2.2.js"></script>
- <!--Reference the autogenerated SignalR hub script. -->
- <script src="/signalr/hubs"></script>
- <!--Add script to update the page and send messages.-->
- <script type="text/javascript">
- $(function () {
- // Declare a proxy to reference the hub.
- var chat = $.connection.chatHub;
- // Create a function that the hub can call to broadcast messages.
- chat.client.broadcastMessage = function (name, message) {
- // Html encode display name and message.
- var encodedName = $('<div />').text(name).html();
- var encodedMsg = $('<div />').text(message).html();
- // Add the message to the page.
- $('#discussion').append('<li><strong>' + encodedName
- + '</strong>: ' + encodedMsg + '</li>');
- };
- // Get the user name and store it to prepend to messages.
- $('#displayname').val(prompt('Enter your name:', ''));
- // Set initial focus to message input box.
- $('#message').focus();
- // Start the connection.
- $.connection.hub.start().done(function () {
- $('#sendmessage').click(function () {
- // Call the Send method on the hub.
- chat.server.send($('#displayname').val(), $('#message').val());
- // Clear text box and reset focus for next comment.
- $('#message').val('').focus();
- });
- });
- });
- </script>
- </body>
- </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)
- public void Send(string name, string message)
- {
- // Call the broadcastMessage method to update clients.
- Clients.All.broadcastMessage(name, message);
- }
- public void SendMessage(string message, int color,string username)
- {
- Clients.All.UpdateChatMessage(message, color, username);
- }
Step 7

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


This service successfully publish on microsoft azure. Now everyone can use and access this service from given url.
http://azuresignalrserver.azurewebsites.net/
Output


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)

Step 2
Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml. Open main.axml file and add following code.
(FileName: Main.axml)
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#FFF">
- <ScrollView
- android:id="@+id/scrolview"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#E2E2E2"
- android:layout_alignParentTop="true"
- android:layout_above="@+id/llContainer">
- <LinearLayout
- android:id="@+id/llChatMessage"
- android:layout_height="match_parent"
- android:layout_width="match_parent"
- android:orientation="vertical" />
- </ScrollView>
- <LinearLayout
- android:id="@+id/llChatMessage"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:orientation="vertical"
- android:layout_alignParentBottom="true">
- <Button
- android:id="@+id/btnSend"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:text="Send" />
- <EditText
- android:id="@+id/txtChat"
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:textColor="#000"
- android:textCursorDrawable="@null" />
- </LinearLayout>
- </RelativeLayout>

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)

Dialog Fragment C# Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Runtime;
- using Android.Util;
- using Android.Views;
- using Android.Widget;
- namespace SignalR_Client
- {
- public class GetInfo : DialogFragment
- {
- public class OnGetInfoCompleteEventArgs : EventArgs
- {
- public string TxtName { get; set; }
- public int BackgroundColor { get; set; }
- }
- public event EventHandler<OnGetInfoCompleteEventArgs> OnGetInfoComplete;
- public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
- {
- // Use this to return your custom view for this Fragment
- // return inflater.Inflate(Resource.Layout.YourFragment, container, false);
- View view = inflater.Inflate(Resource.Layout.getInfo, container, false);
- EditText txtName = view.FindViewById<EditText>(Resource.Id.txtName);
- Button btnOkay = view.FindViewById<Button>(Resource.Id.btnOkay);
- RadioGroup radioGroup = view.FindViewById<RadioGroup>(Resource.Id.radioGroup);
- btnOkay.Click += (o, e) =>
- {
- var args = new OnGetInfoCompleteEventArgs { TxtName = txtName.Text.Trim() };
- switch (radioGroup.CheckedRadioButtonId)
- {
- case Resource.Id.radioRed:
- args.BackgroundColor = 1;
- break;
- case Resource.Id.radioGreen:
- args.BackgroundColor = 2;
- break;
- case Resource.Id.radioBlue:
- args.BackgroundColor = 3;
- break;
- }
- OnGetInfoComplete.Invoke(this, args);
- Dismiss();
- };
- return view;
- }
- public override void OnActivityCreated(Bundle savedInstanceState)
- {
- Dialog.Window.RequestFeature(WindowFeatures.NoTitle);
- base.OnActivityCreated(savedInstanceState);
- }
- }
- }
Step 3
(FileName: getInfo.axml)
- <?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"
- android:padding="20dp"
- android:background="#808080"
- android:minWidth="400dp"
- android:minHeight="200dp">
- <EditText
- android:id="@+id/txtName"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:textColor="#000"
- android:hint="UserName" />
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <View
- android:layout_width="match_parent"
- android:layout_height="20dp"
- android:layout_margin="5dp"
- android:background="#FF0000"
- android:layout_weight="33" />
- <View
- android:layout_width="match_parent"
- android:layout_height="20dp"
- android:layout_margin="5dp"
- android:background="#00FF00"
- android:layout_weight="33" />
- <View
- android:layout_width="match_parent"
- android:layout_height="20dp"
- android:layout_margin="5dp"
- android:background="#0000FF"
- android:layout_weight="33" />
- </LinearLayout>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <RadioGroup
- android:id="@+id/radioGroup"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <RadioButton
- android:id="@+id/radioRed"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="33"
- android:layout_margin="5dp"
- android:text="Red" />
- <RadioButton
- android:id="@+id/radioGreen"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="33"
- android:layout_margin="5dp"
- android:text="Green" />
- <RadioButton
- android:id="@+id/radioBlue"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="33"
- android:layout_margin="5dp"
- android:text="Blue" />
- </RadioGroup>
- </LinearLayout>
- <Button
- android:id="@+id/btnOkay"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Okay"
- android:layout_gravity="center_horizontal"
- android:padding="10dp" />
- </LinearLayout>
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.

Solution Explorer-> Project Name-> MainActivity file and add following code and use appropriate namespaces.
MainActivity C# Code
- using Android.App;
- using Android.Widget;
- using Android.OS;
- using Microsoft.AspNet.SignalR.Client;
- using System;
- using Android.Content.Res;
- using Android.Views;
- namespace SignalR_Client
- {
- [Activity(Label = "SignalR_Client", MainLauncher = true)]
- public class MainActivity : Activity
- {
- public string UserName { get; set; }
- public int BackgroungColor { get; set; }
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- // Set our view from the "main" layout resource
- SetContentView(Resource.Layout.Main);
- GetInfo getinfo = new GetInfo();
- getinfo.OnGetInfoComplete += Getinfo_OnGetInfoComplete;
- getinfo.Show(FragmentManager, "GetInfo");
- }
- private async void Getinfo_OnGetInfoComplete(object sender, GetInfo.OnGetInfoCompleteEventArgs e)
- {
- UserName = e.TxtName;
- BackgroungColor = e.BackgroundColor;
- var hubConnection = new HubConnection("http://azuresignalrserver.azurewebsites.net/");
- var chatHubProxy = hubConnection.CreateHubProxy("ChatHub");
- chatHubProxy.On<string, int, string>("UpdateChatMessage", (message, color, user) =>
- {
- //UpdateChatMessage has been called from Sever
- RunOnUiThread(() =>
- {
- TextView txt = new TextView(this);
- txt.Text = user + ": " + message;
- txt.SetTextSize(Android.Util.ComplexUnitType.Sp, 20);
- txt.SetPadding(10, 10, 10, 10);
- switch (color)
- {
- case 1:
- txt.SetTextColor(Android.Graphics.Color.Red);
- break;
- case 2:
- txt.SetTextColor(Android.Graphics.Color.MediumSeaGreen);
- break;
- case 3:
- txt.SetTextColor(Android.Graphics.Color.Blue);
- break;
- default:
- txt.SetTextColor(Android.Graphics.Color.Black);
- break;
- }
- txt.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent)
- {
- TopMargin = 10,
- BottomMargin = 10,
- LeftMargin = 10,
- RightMargin = 10,
- Gravity = GravityFlags.Right
- };
- FindViewById<LinearLayout>(Resource.Id.llChatMessage).AddView(txt);
- });
- });
- try
- {
- await hubConnection.Start();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- FindViewById<Button>(Resource.Id.btnSend).Click += async (o, e2) =>
- {
- var message = FindViewById<EditText>(Resource.Id.txtChat).Text;
- await chatHubProxy.Invoke("SendMessage", new object[] { message, BackgroungColor, UserName });
- };
- }
- }
- }
OutPut


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

Chittaranjan SwainPosted Sep 30, 2019, 11:03 PM
Nice article....
ganesh devlekarPosted Nov 9, 2018, 12:46 PM
Instead of azure can we have alternative of other like hosting REST Web Api or some thing like we can host on personal server instead of Azure
Wei Chun LaiPosted Sep 18, 2018, 4:37 AM
Do u have example for xamarin forms(android & ios) for the client side code?
Wendell RamosPosted Jun 13, 2018, 10:22 PM
Idk why sir, but i can only use 2 user on the server side, whenever I create another tab (for third user). I can't send message anymore. It also not working on client side, It only works when i use 2 device, please Help
Wendell RamosPosted Jun 13, 2018, 4:07 AM
Sir, why I can only use 2 user at the same time? How can I make it multiple user using the chat hub like a group chat?
Mandisa GiqikaPosted Apr 8, 2018, 5:50 AM
Dear Ahsan! Great article indeed I think this what I have been looking for all this time. Can you publish your app to SQLServer?
Dany TodPosted Mar 31, 2018, 7:42 AM
Dear Ahsan! I have solved the problem. Thank you very much for your help.
Dany TodPosted Mar 28, 2018, 4:46 PM
How can I connect the SignalR_Server with the SignalR_Client ? The SignalR_Client -App I have already at my phone
Dany TodPosted Mar 28, 2018, 4:43 PM
I would like to know how can I connect two phones to chat with a other person? I thank you in advance
Dany TodPosted Mar 28, 2018, 4:42 PM
Dear Ahsan, i have a question
Satyaprakash SamantarayPosted Nov 13, 2017, 11:54 AM
Nice article and clearly described.... Keep continuing....