SignalR in Blazor - Making Real-Time Chat with Blazor Server SignalR Example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today i'll show you how to create a simple real-time chat application using blazer server with signalr in.net 5. so let's get coding create a new project in visual studio so open up a visual studio create a new project uh this is going to be a blazer a blazer server application but if you can't find it in here in the recent project templates obviously search for it in the templates uh you should have it and then give it a name i'm just going to call it chatty uh and then the project directory will be the one that i chose okay so this is it and then hit next and then in the target framework i'm choosing.net 5 because this is what i'm using to demonstrate to make this tutorial and then click create okay so as we're here the next thing to do is to add the signal our new get package and uh if we uh right click on the dependencies so this is the project right click on the dependencies manage new get packages just make sure that the package source is nuget.org and then in the browse we need to type in microsoft.esp.net asp.netcore.signalr.client don't worry i'll link you up in the description uh with this package uh latest stable version is 5.0.10 at the time of recording this video and click install accept the licenses and we are good to go okay following we need to set up the chat hub so um right click on your project and add a new folder called hubs this is gonna hold the hubs obviously and in our case we're gonna create a brand new class uh that's gonna be our hub called um chat hub really simply chat hub and that's it this is going to um inherit from the hub class and it's not going to know about it so we're just going to press ctrl dot to import the um the necessary framework which is signal r uh and then in here we're going to create um a method called send message and this is going to be asynchronous and asynchronous task because it's not going to return anything so public async send message and keep a hold of this name because we're gonna need it uh later on in the tutorial uh and this is gonna take um obviously this is going to be a task this is going to take a string a user um for the purposes of this video we're not going to do any identity uh we're not going to implement any identity into this chat application but we're just going to pretend that the user has got a string that's a unique identifier for instance but that's going to be their username okay and then the second parameter is the message so user and the message those are the two arguments that this method takes and then in here we're gonna await on clients dot all dot send async so we're calling this method with the following arguments uh the first one is the string so that's receive message this is the name of the method that we want to access inside uh signalr at the client uh at the client level and then um user and then message so obviously we're gonna pass in these two arguments so again uh this is a name that we're giving and um you'll see why this is important to keep a hold of this name obviously because we're going to implement a method that has got the same name as this one inside our chat widget so uh stick around for for that following we'll need to set up a startup.cs class for signalr so if you save this and obviously obviously save the project as well it's really really important before running the app please make sure that you save the project because um you the package might be uninstalled for some reason if you don't save the package might be uninstalled so if we go into the startup.cs and uh scroll down to configure services method and in here what we want to do is add response compression so the way we do that is if we come in here this is the last um this is the last line in this method and we hit a break line and then we do services dot add response compression right and i'm going to explain in a moment what this method does uh open and close parentheses and then inside here we need to define some options of options you can call them options or obts it's sort of like a standard okay um and then we need to define them right so opts dot mime types uh okay and then this one don't worry in a second i'll i'll explain as well response compression defaults and this is not going to be recognized so we need to import using microsoft asp.net core response compression so control dot yeah and then mime types and then concatenate so in here um opening close parentheses and then a new array oops so a new a new array and then in here we're going to do in a string in curly braces application slash octet stream okay so to recap this step really quick what we did is uh went into startup.cs configure services and we have added a new line to add the response compression and basically what this is uh what this does is it compresses the data that is sent um between the server and the client and um to make it uh faster so we need this to make the the compression faster and it's also recommended by microsoft and then the my types this is what we're doing here we are defining the mime types as application slash octet stream this is important to define so that the server and the client recognize the data type that's uh passed in with the payload the the payload being the data that's passed in with the request so it's really important to do this step right okay so that's in a nutshell what is going on in there and then the last thing to do in as part of this step is to define an end point and to do that you come in between uh you you come between this uh map blazer hub and map fall back to page and you hit a a new line there and then you define endpoint endpoints dot map hub of type chat hub chat hub and then control dot to import the hubs folder the hubs namespace and then in here you give it a route of chat hub okay so that's it so we need to define this endpoint otherwise you can't uh you will not be recognized okay next thing to do really simple step is to add a user message model uh and we need to do that because we need to store the username well inside the app on the client level we need to store the username we need to store their message their day date sent and a bull flag that defines if the user is the current user so obviously let's create a new folder called models because that's a best practice to have a separate folder for your models or data transfer objects if you if you don't have a if you have a database instead but we're just going to call it uh models and then in here let's add a new class just a simple class called a user message message and hit enter and then in here let's define a few properties just four of them so if you type in p r o p and then double tap visual studio should create a property for you um this is going to be a string and it's going to be called username and then ctrl d to duplicate that line and then here this is going to be a string still and this is going to store the message and then the third property so control d again obviously uh it's gonna be a boolean a bull flag it's either let me turn uh true or false uh and this is a current user it's gonna going to call it like this you can call it is current user it's it's up to you and then the last one is date time that's that's the data type and then i'm going to call this date sent cool that's it with this step oh and by the way if you do enjoy this video please make sure that you hit that thumbs up button so this video can spread out to as many people as possible i really appreciate your time thank you okay so the last thing that we want to do is to set up the chat page and that's going to be in done in index.razer so if we open up the pages and then head over to index.razer um in here we're going to strip out everything from from what we've got as the default one and then what we need to do here is uh add a couple of containers so this is going to be the upper container which is going to hold the messages feed and the down container which is going to hold the inputs so the username the message text area as well as the send button and obviously this particular page is going to have a code section where we're going to do our client-side logic first thing that we need to do is to add a few using so we know that uh what we're working with so i shouldn't have deleted the the pages the page directive uh but i'm gonna put it back so that's a default slash so that's a home yeah and then we're gonna add a uh using to the signalr uh package microsoft package okay so using microsoft dot sp net core dot sign our dot client yeah and then using models uh because this is where the user message model that we've created is stored that's namespace okay uh then we are models then we are going to inject uh the navigation manager uh because we'll need that to uh to set up the the um the chat hub the hub connection so i'm going to call this navigation manager and then the last stamp is addon implements i async disposable so we can dispose the hub connection if that's not null um okay following we're going to quickly define some properties so that when we're going to start using them inside the containers inside the ui we won't get those aggie errors so uh if you go down um add a code uh a code block right here okay so in here we've got a few properties uh the first one is private um hub connection uh and these are more private fields rather than property so that's uh my mistake have connection and that's going to be known by default right we're not going to initialize that by default inside the code we're going to initialize that on initialized async so you'll see in a moment what i mean private list of user message and this is going to be the message field and let's call this user messages and let's new that up with an empty list and then private string username input that's going to store the username that's on the screen currently and then duplicate this and then this is going to be the message input okay and the last uh last field that we want to to do now or almost the last one is if the user is read-only and you'll see why that's important um in a second because if we don't have identity then we need to make sure that we lock the username field right after the first message is sent so that we can ensure that the name doesn't change so it doesn't break our application obviously it's not secure don't take this for granted but this is just solving the problem for the purposes of our tutorial so this is going to be a private boolean is user read only and by default this is going to be false because when we first load the application obviously we want them to be able to insert to input their their username then a public boolean yeah called is connected and we define this in place by doing hub connection by checking if the hub connections state is hub connection state dot connected yeah um so this is an enum uh so if the state property of the hub connection is connected yeah is one then is connected is going to be set to true um so we're going to use this property in uh in a moment yeah following we need to lay out the two containers we've got two containers one that's at the top that's going to hold the messages feed and it's going to show them to the user and then the second one is going to hold the inputs as already stated before so username message as well as the send button so this is what we're going to do now so i'm just going to copy [Music] a snippet that i've already have so so i don't bore you with the details of typing out classes and um i'm obviously going to walk through them so uh this stiff container that's the upper container the messages feed has got a class of container overflow auto so that we can scroll up and down to see all the messages um and then we're gonna add a shadow a padding a margin a background of white because we want the messages to pop out better and we're going to add some some nice shadows to the messages um containers so you'll see why why that's really good in a moment and then we're going to make it rounded a bit and then a height of 500 pixels because i want that to be the standard i i don't want that to be you can put that to whatever you want but i'm just going to leave that at 500 because i don't want that to stretch over and to make the inputs not visible anymore yeah okay and then the second container is obviously the inputs field uh and this is the the the one that we're going to start with so this is going to be the div container and this is for the front end i'm using bootstrap okay so in here uh what we're going to do is add a new row to hold the inputs and then three columns first one a bit smaller that's going to hold the username that's not going to be used very often but the second one is going to be probably double as as as large um so that's going to be the message the third one is going to hold the the button in place okay so uh without further ado let's let's go ahead and do this so div class row and then in here div class call third one three second one six so i'm going to make this three so the total adds up to um to 12 which is the total width of the screen okay so let's start with the first one okay in here we're going to add an input of type text of course um and then we don't need the name for it nor do we need a value because we're working with blazer so we know what we're doing um we're handling that separately okay and the bind property is username input which is this right here so you see why it was important to define them at the beginning and then i'm going to add a class and uh and the placeholder so i'm just going to copy and paste that uh so a class a form of form control so it looks decent and then a placeholder of your name uh and then here is um where we'll use the uh is read only flag so by doing read-only by accessing the read-only attribute of the input html tag and we're gonna set that to add sign is user read-only okay so we'll define that later on in the in the following steps okay so this is the uh this is the button secondly we need to add the text area yeah type in text area and press tab and then here bind to the message input okay again i'm going to copy and uh and paste the other properties um again form control so it looks decent uh type text um actually we don't need the type text because this is a text area and then the placeholder um that's going to be start typing or something similar yeah and then the very last one is the the save button uh which is obviously gonna be a button of type button and really quickly uh two things that we need to add so the on click event yeah uh this is gonna call the send and it's not gonna find it obviously but that's fine we're gonna get that in a second and then the disabled uh attribute needs to be defined to the um is connected flag right here yep if it's not connected then disable the button yeah and uh also we need to add a few uh classes so bt and btm primary so it looks okay okay so that's it with the bottom container uh what we'll do next is define the following functions inside the code block so we'll define the on init on initialized async obviously we'll define the send function and the dispose function so let's get to it okay and this is protected the very first one is on initialized async so that's a protected uh override and if you uh type if you press say uh space here you'll be able to access the blazer lifecycle methods that you can override um so we're gonna need the uninitialized async and it's gonna generate the snippet for us which is really really cool okay in here we need to define our hub connection um what does that mean we need to define it and then we need to initialize it as well and to start the the connection so when the page loads up when the page uh first initializes we need this to be we need the connection to be already started for us to be used yep so we're gonna define uh we're gonna define the node so far no hub connection as a new hub connection builder with url with url complete playing around with me navigation manager dot to absolute uri and then here we're gonna do the chat hub endpoint this is the one that we have defined in startup.cs right here so make sure that that's the same and also that it matches the class name as well it doesn't have to be um capitalized it's fine but just make sure that it's uh it's the same one as the one defined in startup otherwise it's not going to be able to connect you to the right place and then call the build method on it and that's it so we have defined the hub connection and the errors went away thankfully and then the hub connection we do hub connection dot on so this is where we bind onto the method that we have created inside the chat hub so in here we need to define the two data types that we're passing into the method on string string and then opening close parentheses and then the semicolon so in here we do the name of the method that we have defined inside the send message right here so that's receive meth message uh on receive message and then it takes two parameters so we need to define them in here user and message okay so this is an anonymous function opening close parentheses so let's uh go down onto the next line so it looks nice and nice and readable and then in here we do this so when we receive this message when we send this message what do we need to do beforehand so we need to add that message um and the user so the user and the message to a list of messages to be able to show them on the screen obvious obviously um so the way we do that we just append um a new instance of user messages into our list that we've initialized at the top of this code block so to do this we do user messages user messages dot add then in here we need to add in a new we knew up a new user message instance with the username of user with the message of message with a current user of and here we need to uh figure out if this is the current user and this is important uh because we don't want to just uh uh dump out all the messages into the feed we want to uh add a space between them and to make our messages uh be to the right and then their messages to be to the left so that we can distinguish which you which ones are ours and which are which ones are from the from the other sender yeah so in here we define the current user as user if it's if the user is the same as the username input so this is where it's important to add the ease read only is user read-only flag to the uh username input so that the uh client can't uh change their username midway through the process of this um of sending the message yeah and then the very last thing is date sent and this is uh date time dot now okay the next thing that we need to do inside this function is to define the state to call the state has changed so that uh we can notify the we can notify blazer that the state has changed so you can render the message on the on the screen yeah uh and then inside this on initialize async the very last thing that we need to do is a wait for um a start async method that we're calling on the hub connection yeah so await hub connection dot start async yeah so we're calling start acing so again really quickly we have declared the um we have defined the hub connection and then we've defined uh something that should happen when the hub connection calls the receive message uh yeah and then in here we just add a new user message instance to the user messages so that we can render them on the screen then we call the state has changed at the end of everything we need to put we need to add in the await hub connection dot start acing and this is underlining it with red because we haven't got the asynchronous keyword in here and you will see the error goes away next method is the send method so this is going to be a private asynchronous task send that's the name of the of the method that we decided to call it again this is up to you how you want to call it and then in order to send a message let's first um let's first check if the user input as well as the message are not null or empty yeah so if you type in if and then double tab if string so i've put an exclamation mark so that's the signifies and not obviously is not is null or empty i want to use and we check for the username input as well as if string dot is no longer empty the message input okay so if these two evaluate to to true then we're good to send the message so here is where we send the message to the hub to notify um uh to notify the client we do await and then hub connection dot send async and this is the name of the method the name of this method right here so send message um okay add the semicolon at the end i've already done that so send message and then the second parameter of course is the username input and then the third one is the message input you've guested already okay and then after we send this message the very first message what we want to do is set ease user read only equal to true this will make basically every time you send a message it will send that it will make this flag set to true you can find obviously better ways of doing this but of course i'm just going to leave it at that because it it's not hurting the application for the purposes of this tutorial and then we need to empty out the messages input right after we send a message so that we don't have to delete the old message after we've just sent it yeah so messages input dot messages input is equal to string dot empty cool and that's it oh and by the way how do you uh like working with blazer let me know in the comments below is it easy or not so easy to work with blazer or of course for my tutorials or from any other um developers tutorials on youtube um yeah i quite like it actually i find it easy sometimes to find documentations but hey i want to know what you guys think so we can spawn up some conversations so let me know in the comments down below what you think okay the last method is the dispose method that we want to do so that's a public async value task dispose async yep then let's fix the indentation and then if hub connection if hub connection is not normal then just dispose async on the hub connection so await we're going to await this method hub connection dot dispose acing so we make sure that we dispose everything after we're finished okay the very last thing that we have to do as part of this tutorial is to lay out the um the upper container the messages feed so before doing that let's just see what we've got so far so if you open up package manager console and you type in dotnet watch run and hit enter let's run the application and let's see what we've got so far so that we can work with uh with the designs a bit okay so uh here we've got the um the application up and running so it looks really nice apart from something i don't know if you spotted it but i did so we didn't actually give a value to this button a name um so we're just gonna give it a name here of send and if we press save and we come back to the application there you go we've got the sent the name of the button right here okay so as you can see we've got the name uh the the message obviously the username the message and the send button so what we what we want to do now is add a nice message feed right here so that we can obviously we can see the messages the cool thing is that if we want we can copy the url go into a new tab and here we are we can uh we are working off of the same we're working on the same instance right so um well on different instances but we can see each other messages and you'll see how that's uh how that's possible in a second so upper container let's do that now let's first check if we've got any messages and to do that we add an add sign inside that container type in an if uh double tab and then in here if there are user messages dot any so if there are user messages dot any and then we put a not inside in front of it so that it means if there are no messages then type in a paragraph to say no messages yet start chatting yeah an incentive to just get people um to want to just get us a chat between ourselves yeah um okay and then inside here uh this is a simple for each loop so if you type in for each double tab for each user message in user messages so we loop over every row inside the user messages that we've appended every time we press the send button which is right here so every time we press a send button we call the send method which is this one yeah so we do this we we firstly check obviously if the username and message is not empty and as we said we're sending the message to the client level okay so in here we need we need to add a new row for each record that we've got in the user messages which is for each message obviously so we need to add a new div container yeah with a class of row and we add a margin button of three and uh this display should be flex and you'll see why that's important in a moment because we'll move the containers around depending on um who sent them yeah so inside here we add the bootstrap card so div class card yeah and then let's add a shadow as well okay um and then let's uh make let's define the width of this card so that it's it's always the same with for a four hour tutorial so style obviously you can do this in the side.css i'm just going to quickly chuck it in here which is not best practice but um serves the purpose so width is 18 rem yep semicolon and then inside here uh we inside this card we need to add a header a sort of a body and then a footer so the header will have the username uh the body will hold the message and then the footer will hold the date sent so that we know when we send or receive that message for that matter from the other person okay so first thing div class card header yeah and then the second thing is a actually a ul class of list group group um and then list group flush yeah it's just a bit of flaming that we need to do beforehand so that it looks decent uh just stick with me so then a list item of class list group item yep and then inside this list group item is the user message dot message okay and then we need to define the footer as well oh i forgot to add the user message in the user the username in here so user message you probably already done that because it's um all we need to do is add the current user in here so uh sorry not the current user the user name yeah and then the last thing uh is to define the footer uh so div class card footer and then in here we need to add a span of class small so that this piece of text appears as small as it probably does in most of the chat applications so then here user message dot date send um so let's format this to string really quickly um hhm this is just so it looks uh more like uh more readable so it's it's showing the month in words and it's showing the the time and um the hour and the time okay so let's see what we've got so far so if you save this is going to start building and it's going to reload the website so if we go this has already reloaded for us if not just press ctrl r so reload the page yourself it should be okay and then we have no messages yet start chatting so let's put a name in here and hey there this is my very first message and then press save so there you go we've got our very first message right here we've got the name the username the message as well as the the in time nicely uh the date sent nicely formatted so then here in the message let's type in another message to say um hello second message and then we type that in and it's right here so we need to reload this page obviously to uh to see them side by side okay and then here let's add in johnny and um annie yeah and then in here hey annie what's up we send this ray johnny says hey annie what's up and then he says hey johnny yeah all good there you go so uh this is how uh this is how it's done and um to take this one step further as we've already laid the foundation so all we need to do is play around with some conditions and some classes um let's actually move this around these containers so that uh the program can figure out which ones are our messages and which which ones are um the sender's messages so to do that we come in here and in the um in the row yeah in the div row what we need to do is check if it's the current user so if it's let's go back to the application and let's see if it's the current user what we want to do is um a float basically float the container to the right so that it signifies that that's our message um that's probably what whatsapp is doing as well or messenger or any other type of chat application so let's do that so opening close apprentices uh obviously put an ad sign before of it so this signifies that this is a code block inside our client level uh by the way uh if you don't know what i mean i've created a seven part um a blazer playlist that takes you from basics to create a recipe manager application i'm going to link that up in in this video so please make sure to check that out okay so in here we'll need to check if user message dot current user so if it's the current user then add in the following class so inside the class attribute we're doing this yeah justify content end if it's not the current user then don't add anything yeah so this is what we're doing and to take this one step further again because we wanted this to be top notch uh we need to do the same thing for the um for the card so that we can add some colors so if it's the current user then let's add a uh margin right of of five obviously because this is to the right and also before doing that let's add a class called color green um and this doesn't mean anything this class doesn't exist but if we head over to site.cs and scroll down we can actually uh add that glossy and so we can make the container uh green that's a nice color for our own messages yeah so i've already got a code for this color so we can set the background color to this shade you can set it to whatever you want but i like this shade quite much uh okay so let's see uh let's see what we've got so far obviously refresh your um refresh your pages so johnny hey there any yeah and there you go we've got the message where this is johnny we've got the message on the right hand side where this is someone else it's not even got a name yet so any uh if i type that in correctly yeah annie hey johnny yep uh so as you can see uh and he's gonna send a message on annie's page this is going to show on the right hand side on johnny's page is going to show in on the um on the left hand side so the very last thing that i would like to do is instead of seeing my own name because i know my own name or already let's make this so that it shows um as u yeah and then for annie this is going to show as johnny and also let's make this screen as well because it doesn't look right okay so in here instead of showing the username let's actually first let's make a code block right here and to say if user message.currentuser then do type in you otherwise do the type in the user message and take the add sign out and also on the on the list group we need to uh on the list group item specifically um here we can add the color green so the background color green uh by checking if the user message not the current user again this is the same check and if it's if it's the current user then add the color green otherwise don't add anything save this and let's reload the the apps to see how this is going okay so in here johnny hey there annie yeah and then in here hello johnny yeah so that we send you that message no messages yet disappeared we've got this on the right hand side for johnny we've got this on left hand side for annie this is saying you i'm sending a message to johnny i sound like a football referee uh well i want to be one but uh yeah and then in here uh for the next side we've got her message um all with green on the right-hand side for her on the left-hand side for johnny uh so that is really cool i think the um a very tiny bit of thing that we forgot to do is um add a margin left to uh where um to uh if if it's not a current users so that it shows this message as um nicely laid out on the on the screen that's it for today's tutorial if you want to learn the basics of blazer i've put together a playlist right here where we'll build together a recipe manager so make sure you check that out i truly hope you've enjoyed this tutorial and it's been a value to you and if it was why not hit that like button to make sure that this video spreads out to as many people as possible and i post weekly tutorials just like this one on blazerand.net in general so if you like content like this please subscribe and join our club if you've got questions or suggestions of any type please make sure that you leave them to the comment section below and i'll make sure to respond to every single one of them until next time stay safe
Info
Channel: Code with Julian
Views: 10,766
Rating: undefined out of 5
Keywords: Blazor Server SignalR Example, Blazor SignalR, SignalR, Bazor Server SignalR Hub, Blazor Server Side
Id: I9bA8elRULI
Channel Id: undefined
Length: 42min 36sec (2556 seconds)
Published: Mon Oct 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.