ASP.NET SignalR is a library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can push content to connected clients instantly as it becomes available.
In this tutorial, I am gonna show you how you can create a real-time chat UWP application using Azure Mobile App and SignalR. You can easily implement cool features of Azure Mobile App like user authentication and push notifications along with SignalR bi-directional communication to create awesome real-time apps.
Follow these steps to create a new Mobile App backend.
You Mobile App backend is now ready to use with your client app.
(Taken from here)
Now, we are ready to install SignalR package to our Mobile App.
Right Click your Mobile App project and click Manage NuGet Packages… as shown below. Select the Browse tab if it’s not already selected and search for SignalR and select Microsoft.AspNet.SignalR.Core package. Then click Install
Click OK to the first popup and accept the second one.
It should now create a Scripts folder.
Ready to write some code?
Create a ChatMessage.cs class inside the DataObjects folder.
Add the following code.
public
class
ChatMessage
{
string
Username {
get
;
set
; }
Message {
}
Create a new folder under your project’s root and name it whatever you want. I named mine Hubs.
Create a new class inside your folder named ChatHub.cs.
ChatHub : Hub
void
Send(ChatMessage message)
Clients.All.broadcastMessage(message);
Simple right?
Last but not least, open the Startup.cs class which is located in your project’s root and add app.MapSignalR(); below ConfigureMobileApp(app);
This will map SignalR to the app builder pipeline.
And that’s it! Your mobile app service is ready.
Let’s create our UWP Application.
Start by creating a new project by going to File->New->Project->Visual C#->Windows and select Blank App (Universal Windows) and name it whatever you want.
Then, right click your UWP project and click Manage NuGet Packages… like before.
Select the Browse tab if it’s not already selected and search for SignalR and select Microsoft.AspNet.SignalR.Client package this time. Then click Install
When it’s ready, create the same ChatMessage.cs class like before and place it wherever you want.
I am gonna use a simple data binding mechanic. If you need more info on what data binding is start here.
Create a class named ChatMessageViewModel.cs this will be used to represent our Chat Messages on our view.
ChatMessageViewModel
ObservableCollection<ChatMessage> Messages {
; } =
new
ObservableCollection<ChatMessage>();
ChatMessageViewModel ChatVM {
; }; = new ChatMessageViewModel();
HubConnection conn {
IHubProxy proxy {
App()
this
.InitializeComponent();
.Suspending += OnSuspending;
SignalR();
SignalR()
conn =
HubConnection(
"http://<;your-mobile-app>.azurewebsites.net"
);
proxy = conn.CreateHubProxy(
"ChatHub"
conn.Start();
proxy.On<ChatMessage>(
"broadcastMessage"
, OnMessage);
Broadcast(ChatMessage msg)
proxy.Invoke(
"Send"
, msg);
private
async
OnMessage(ChatMessage msg)
await Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
ChatVM.Messages.Add(msg);
});
This will create the connection to our mobile app service, connect to our ChatHub and register to broadcastMessage event which means, when the server sends a broadcastMessage message to us, OnMessage handler will be invoked.
The OnMessage handler adds the received message to our ObservableCollection, Messages, and the Broadcast method is used to send the message to our service by invoking the server-side Send method.
Our Logic is ready!
Now, the only thing left is creating our View. Let’s use the MainPage for that.
<
Page
x:Class
=
"ChatApplication.MainPage"
xmlns
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
"http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local
"using:ChatApplication"
xmlns:d
"http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc
"http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable
"d"
>
RelativePanel
TextBox
x:Name
"name"
RelativePanel.AlignRightWithPanel
"True"
RelativePanel.AlignLeftWithPanel
RelativePanel.AlignTopWithPanel
></
ListView
"lv"
ItemsSource
"{Binding Messages}"
RelativePanel.Above
"rp"
RelativePanel.Below
ListView.ItemTemplate
DataTemplate
x:DataType
"local:ChatMessage"
StackPanel
Orientation
"Horizontal"
TextBlock
Run
Text
"{x:Bind Username}"
": "
"{x:Bind Message}"
</
RelativePanel.AlignBottomWithPanel
"text"
RelativePanel.LeftOf
"send"
Button
Content
Click
"send_Click"
That’s my super simple View. I am using a TextBox for the username, a ListView for the messages, which uses the Messages ObservableCollection as it’s ItemSource, one more TextBox for the message we would like to send and a Button.
public MainPage(){ this.InitializeComponent(); this.DataContext = (Application.Current as App).ChatVM;} private void send_Click(object sender, RoutedEventArgs e){ (Application.Current as App).Broadcast(new ChatMessage {Username = name.Text, Message = text.Text});}
MainPage()
.DataContext = (Application.Current
as
App).ChatVM;
send_Click(
object
sender, RoutedEventArgs e)
(Application.Current
App).Broadcast(
ChatMessage {Username = name.Text, Message = text.Text});
And that’s the MainPage code behind the view.
I am just setting the DataContext of the MainPage to our ChatMessageViewModel and invoking the Broadcast method when the user clicks the button.
And voila! That’s it! Of course, you can follow the same logic to improve it with features like who’s online right now or private messaging. Also, you can even use push notifications and user authentication offered by Azure Mobile Apps easily.
You can find the GitHub repo here.
Thanks for reading! George