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)
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.
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 () {
-
- var chat = $.connection.chatHub;
-
- chat.client.broadcastMessage = function (name, message) {
-
- var encodedName = $('<div />').text(name).html();
- var encodedMsg = $('<div />').text(message).html();
-
- $('#discussion').append('<li><strong>' + encodedName
- + '</strong>: ' + encodedMsg + '</li>');
- };
-
- $('#displayname').val(prompt('Enter your name:', ''));
-
- $('#message').focus();
-
- $.connection.hub.start().done(function () {
- $('#sendmessage').click(function () {
-
- chat.server.send($('#displayname').val(), $('#message').val());
-
- $('#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)
- {
-
- Clients.All.broadcastMessage(name, message);
- }
-
- public void SendMessage(string message, int color,string username)
- {
- Clients.All.UpdateChatMessage(message, color, username);
- }
Step 7
Bulid and run the project.
Step 8
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)
- {
-
-
-
- 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
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)
- <?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.
Step 5
Solution Explorer-> Project Name-> MainActivity file and add following code and use appropriate namespaces.
(FileName: GetInfo.cs)
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);
-
-
- 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) =>
- {
-
-
- 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