SignalR - Learn basic fundamentals with .NET Core (.NET 7)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign [Music] guide my name is broken and I will be your instructor for this course in this course we will be learning asp.net core signalr and we will be starting from scratch I do expect you to have basic understanding of asp.net core and MVC because I will not be going into the basic foundations of what is a program file what are views controller and so on the main question is what is signalr let's switch to Microsoft website where we explain Basics about signalr first thing that you see here is real-time asp.net with signalr incredibly simple real-time web for asp.net now what is real-time web real time basically means that as soon as something is updated on the server or as soon as the data is updated you do not have to refresh your browser your browser automatically renders that change that is real time in simple term to give you some insights here let's say we are on Walmart.com and let's go to one of the item here at this time when the page loaded let's assume this item was in stock but you were deciding on this and at the same time this was the last item and someone already purchased that so in this case we will not see that notification here that it is sold out typically what happens is once you add to the card if you go to the card or when you are adding to the card at that time it will check is the inventory available like using signalr what you can do is let's say when the window is opened there was inventory but they were deciding on this for like five minutes and at the same time someone bought the last item what we can do is with signalr we can tell server that hey inventory is gone server will tell our client that hey this item inventory has gone to zero so dynamically it will change here without refreshing that this item is no longer available and that is the power that we can accomplish with signalr now that is just a brief example of what signalr can do but it is not just that thing signalr basically makes real-time web super simple let's scroll down here and we see it is a part of asp.net core framework so we don't have to add anything fancy it is an integral part of the.net framework what you can do with asp.net signalr one of the common example that comes is a chat application because when you are chatting typically you do not refresh the page the chat automatically displays the sender and receiver's message without refreshing so that is a common example that is displayed with signalr signalr is open source open protocol and you can view the complete code on GitHub on top of that signalr is super fast and scalable and Azure also supports signalr so there's quite a few things that we have to learn when it comes to signalr but to give you a 10 000 feet overview one thing that you need to know is if you need real-time web without refreshing the browser signalr is the answer but one thing that you should understand is signalr has two pieces one is the client side and other one is the server side now these client and server are both integral pieces of signal or application itself so signalr will have a server which we will call as Hub and then there can be many signalr clients that will communicate with the signal or Hub in real time I won't go into much details right now because we will be exploring all of this throughout the course and everything will make much more sense let me show you what we will be learning in this course you can see right now on the home page we have something called as total views and total connection if I open a new incognito window here and if I paste the same URL you will notice that total views and total connections are updating if you refresh the page here the total view updates and it simultaneously updates in both the windows even though we are not working on the other window that is the power of signalr on top of that if we connect to one other window here you will notice that total connection in all the windows gets updated to 3. and if we close any of the connection it decrements that to two because that is the total number of active connections right now so that will show us the basics of how we can calculate total views and number of active Connections in an application using signalr after that we will be implementing the deadly high low race where what we have to do is we basically have the end points here for voting so if I select that and let me open another browser here let me paste the URL where I have the type of cloak if I press enter here you will notice that count for cloak increments in all the open Windows here if I refresh the page here the count continues to increment so this will be like a voting count where whatever is the real count that we have that will be updated in all the windows that have the active connection if I change my vote to Resurrection Stone here paste that URL and hit the enter button it did not get copied let me copy this paste it here Stone perfect you see Resurrection stone is one now so if we keep on refreshing this tab the counter keeps on increasing in all the active connections these are the two basic projects that we will learn using signalr and with that you will get the basic understanding of what is a hub what is a client how to connect and how all the active connection gets the updated data so with that brief overview let me get started from the next video this video let's take a look at the typical HTTP request and see how that is different or what that cannot accomplish that signal or can accomplish typically we have a client and a server client will be the web browser and server will be where the application is hosted so when any browser requests a URL or request something the request goes to the server server takes its time and then it gives back a response if they click something else on the page then the request might go back to the server it processes something and gives back a response it can be either loading off the page or some other details but client always initiates a request and server responds back with the appropriate data this is typical scenario with an HTTP request but when we are working with signalr what can happen is client does not need to initiate a request what will happen is whenever server has new data it needs to notify client that hey this is the new data that is available if you want you can use that if not you can ignore that that is the limitation when it comes to an HTTP request because in signalr the server needs to notify client whenever a new data or something that they want to know is updated so when we are working with signalr it is basically a two-way or an open connection so the connection does not close so that means whenever server has to send some data it can use that existing connection and send some additional data now you might be saying that can this be done without signalr and of course it can be done signalr is just a wrapper that uses the real-time web techniques so let me give you just the terminology that signalr can use to communicate real-time data the first one and default one is web sockets websockets is the latest technology when it comes to real-time web communication all the modern browser supports websockets but if your application is supporting some Legacy browser then websockets might not be supported in that case the fallback will be servers and events and if that is not available the Lost fallback is long polling now you might be wondering what are these terms do not worry we will cover them when the time arrives but right now you need to remember few things signalr is not a magic thing that asp.net core team has discovered it is just an abstraction on top of these transport types and using them we will be establishing a two-way communication between client and server so with that brief overview of HTTP and transport types in signalr let's continue from the next video we want to start working with signalr to learn what exactly happens when we are using signalr the first piece of information that you will understand in signalr is hubs hubs are the critical entry points when we are working with signalr in simple terms Hub is a server-side class that is responsible to send and receive messages from all the connected clients so it acts as a communication controller when we are working with signalr let me explain this a little more with an example let's say you have multiple clients that are connected to an asp.net core MVC application in MVC we have models views and controller so our application is open in for browser then let's say one of the browser is requesting to go to home controller index action method so they will initiate a request that I want to open on forward slash index then in the middle ways when it goes to routing it will route that request to the correct controller and index method that way it is able to return the response back to the client based on whatever view or anything else that is needed so in this scenario you can see when you are adding routing to the MVC application that's how it knows that where the request should be navigated to when you are adding a signal or Hub you will be adding that and you will be registering what is the route to that particular hub so we will add a hub in our application and we can give that any route that we want in this example we are giving a route of hubs forward slash user account so that Hub is created on the server inside the.net core application then any browser that opens our application will have an active connection to that particular Hub as long as they are on the same page so this time if you notice the arrow here it is a two-way communication and not the one-way communication like we had before this connection will remain active as long as the page is kept open and then from a client if they request anything or even if server wants to send some data they can send that to the client they do not have to open a new connection because connection always stays open so any request from client to the server or server to the client will go through the Hub that we have created in signalr now you might be wondering how can we add Hub in our application it is pretty simple Hub is just a class that is derived from the Hub base class in the signal art Library and we will see that in the next video as well that being said there can be multiple herbs in an application and all of the clients if they are on the page that is using signalr they will have an active connection to the particular hub we will see all of this in much more details but I hope you are getting a rough idea of what signalr will do if not do not worry as we proceed with the first example everything will make much more sense so let's continue and create our Hub in the next video now before we create Hub in our application let me walk you through a 10 000 feet overview of the signalr flow now this flow might change a little bit based on how you are using signalr but I just want you guys to have something that way you can have some checkpoints when you are adding signalr so the first thing that we have to do is we have to create the signalr Hub that we will do in the next video once the signal light Hub is created you have to add methods to that hub after you add methods on HUB then you have to add client-side for signalr once the client side is added then you will have to connect to the signal or hub from your client side which can be JavaScript once you connect to the signalr hub then from the client-side JavaScript you can invoke signalr Hub methods and vice versa so signal or Hub can also invoke methods in your client-side JavaScript to notify clients and once your client site receives update from the server you can render some changes in Dom to display the real-time web that we were talking about so typically these are just checkpoints right now but once we add signalr in our project you will see each and every step in action and then this will make much more sense but typically we are creating a hub on the server side then we will be adding the client side for signalr we will establish a connection between client-side and server side and then client can invoke methods on HUB and hub can invoke methods on client that is the basic flow when it comes to signalr but do not scratch your head thinking about what are this new terminology all of these seven steps will be done from the next video we will first start by creating our project so I have opened Visual Studio 2022 let's hit create a new project here I will be creating an MVC project but if you use razor Pages or other project type signalr should work the same way we will work with a basic MVC project here and let me call this as signal r sample we will select next here and the.net framework will be.net 7. now right now.net 7 is in preview version so I'm using visual studio 2022 preview but you can use.net6 or any older version signal or logic should be consistent with the older version authentication type I will select individual accounts because I want to show you the integration with application DB context or Entity framework core with the user identity that it provides so that way we will have all the identity tables configured for us with that change let's set the create button and perfect project has been created here now the first thing that I would like to do here is add the project to Source control so let's add that to a git Repository and the repository name looks good which is signal our sample right now I will select the private repository but later on I will make this public once the course is launched so we will hack create and push here and perfect it has been added to Source control so now that our project has been created let's continue from the next video now that the project is created we will first work on creating a hub a hub is a server set class that is responsible to send messages to the client and also receive messages from clients so it acts as a communicator so first question how do we add a hub for our signal our application well adding that is pretty simple you can add it anywhere in the code So within our project we will add a new folder and we'll call that as hubs now the reason I'm using plural here is because Hub will be a reserved keyword so rather than getting conflicted with the namespace it is patched if we call it as apps here so inside the folder let's add a new class file the first Hub that we will create in our project I will call that class name as user hub now this is just a simple class nothing fancy right now but what makes this class a hub is we can Implement that and here we will write Hub and we will press Ctrl Dot you can see intellisense is displaying that we can add a using statement for microsoft.asp.net core dot signalr let's add that with that piece of code we have created a signalr hub but right now it does not make sense on what this Hub is responsible for or what exactly is it doing actually we have not even added signalr in our.net core project right now in order to add signalr to our project we have to do that in program.ces class file the class file here already has a DB context because we added individual user account everything with that looks good but when we are adding services to our container we have to add signalr as well so we will say Builder dot Services dot add signal r simple as that that will add signalr service inside our container then if we scroll down where we have the map controller route you can see in MVC we have routes that are provided similarly when we are working with signalr and hubs we have to give our Hub a route that way the application will know if a request comes in for one of the signal or Hub how to route it to this user Hub class file so for that on the app object we will have a method which is math Hub and that is inside microsoft.asp.net core dot signalr dot hub so inside maphub we have to tell which is the Hub class so the class that we want to configure right now is user hub we will press Ctrl dot add the using statement and then within the parameters here we have to give pattern which is nothing but the route itself so we can call that as hubs forward slash this is the user Hub so let's call that as user or you can be explicit like user account so just to recap what we have done in this video we first added a class user Hub and that is just implementing The Hub from asp.net code.signal art.hub and then in program.cs we added signalr to our services and we added a route to the signal or Hub that we created now if things are not making sense right now on what are we doing just stick with me for a couple of videos and when we see a signal are in action everything will make more sense but right now we have just created a hub and we have given that a route so that any methods in that Hub can be accessed using this route so with that we have accomplished the first step where we create the signalr Hub and we added the configuration for route in program.cs with that first step in place let's continue from the next video we have added the user Hub in our project the responsibility of this user Hub is to count the number of views on a web page so let's say if we open a page and if we refresh the page the count should increase so it will act as the counter on how many times that page has been viewed and if let's say two users have opened the same page the account will be due and if both of them refresh the page the account will now be 4 because both of them have refreshed so they have basically seen the page two times that is something that we want to track using signalr while we are still exploring the basics of signalr if you want to go fancy you can always Implement and save things in database but for now we will keep things in memory and super simple so inside the user Hub we will add a static end with the name of total views that will track the number of views our website gets next thing that we have to do is in our Hub we need to create a method that will be called to increment our total views so basically we are creating a method here that will be invoked every time that page loads or reloads so we will create public async task and I will call this new window loaded we can call this whatever we want we are just calling new window loaded that will be called whenever the page is loaded or it is refreshed now right now do not worry on how we will call this method the only thing that we should worry about is when a method is called in this Hub what it is responsible for well this is pretty simple it should just increment the total views that we will be able to track what is the current view or how many users have currently viewed the website now once we increment the total views remember that right now we are in the hub we are not on the client-side application so whenever we Implement something in the hub we have to tell all the clients that hey the total views have been updated this is the new count and I want you guys to use this however you want that is the responsibility of a hub it will do some processing and then it will tell all the clients that hey this value has been updated so you can use them or display that in your website so here we need to add some piece of logic that will send update to all the connected clients that total views have been updated and doing that is super simple we will have to await that and we have something called as clients these clients is inside the Hub implementation that we have so Hub will have a list of all the clients that are connected and right now we want to send an update to all the clients that are connected so we will say clients.all and there is a method send async inside here we first need a method name so let me call this update total views now you might be wondering that where is this method well we do not have that method right now but we will be creating that in the upcoming videos this method will be located inside the client side of the application Hub is running on the server side so server is telling that hey when the new window loader is invoked on the Hub I want to update the total views here and then I want to call this method update total views which will be located on the client side now when we call the update total views it makes sense that we have to pass the total views only then they will know that hey this is the current view count of the website so in order to pass parameter it is pretty simple you can add a comma and you can pass as many parameters as you want so if there are more than one parameters you can add one more comma and you can continue like that we just have one parameter right now when the new window loaded on the Hub is invoked we want to increment the total views and we want to implement a method update total views on all the clients and we will also pass the total view count so if we switch back to our presentation in this video we added methods to our hub but on top of that we also did one more thing and that's not in the order like I said before so along with point two we also covered 0.6 where in Signal or Hub we have added a method that will invoke the client-side method to notify clients but that method we have not created yet we will do that in the upcoming videos but our Hub now also invokes some method in the client side so basically we have covered points 1 2 and 6. with that in place let's continue from the next video now so far we have implemented Hub and we have also added our first method which is new window loaded that is responsible to invoke a method on the client side which will be update to reviews now before we start adding this method inside JavaScript of our project as the client side of the application we still do not have the client side of signalr we have added signalr on the server side where we have added that to our services and we also added the Hub route inside program.cs so now you might be wondering how do I add the client-side library for signalr that is pretty simple we will right click on signalr Sample which is our project name add and here we have to add a client-side library we will use the unpkg and then we have to type the library name that Library name is Microsoft forward slash signalr and we want the latest one so let's add that you can see it is adding many files to our project but honestly we only need the signalr.js file let me install the complete Library and then we have to add a link to signalr.js the library that we added is installed in www.root we have lib inside there we have Microsoft signalr d i s t browser and inside there we have signalr.js you can leave it right here but I'm just gonna move this inside the JS folder that way I can easily reference that rather than navigating through the lib folder so perfect we have added the client-side signalr to our project now in the next video we still need to create the update total views in the client side of the project let's switch back to the presentation real quick and in this video we completed adding the client-side signalr now before we work with anything else let's run our project and take a look at the output so perfect right here we have the basic template of home page privacy page we have login and registration that comes with the.net identity so this is the basic template that gets loaded with dotnet core identity now we will be working on the home page so let me stop the application we will go to our views here home index let me remove everything add a div here give it a class of container and inside there we will add a div give that a class of row inside there we will add another div give it a class of column 3 and we want to display total views to display the total views let me add another div give it a class of column 4 and inside there I will add a span with the ID of total views counter this is just an ID that we have given to our span right now there is no value in the span but we will be loading that pretty soon if we run the application now we will just see the total views and that looks good if we run the application we will see the default home page but we just have total views there and it's empty right now we will be using signalr in the index page so let me add that right here we can add a script tag give it an SRC of JS we have signalart.js that will add the client-side library of signalr inside our index View so there is one thing that you should be clear right now even though we are working on the same application when it comes to signalr there are two different pieces one is signalr client and the other one is signal art server or hub so inside program.cs or the Hub that we added that is the server side of signalr and then we will be having a client side inside our views that will be communicating with our user Hub and it will be invoking the methods that we see there so on the client side we need to set up a connection to our hub and the route for that connection is if we scroll down hubs forward slash user count so from the client which will be our JavaScript that we will be adding we need to establish a connection to our user hub let's establish that connection in the next video now that we have added signalr.js inside our index.cshtml we need to actually connect to the signalr hub from our client side of the application so in order to do that let's add a JavaScript file in our project so new item here let me search for Java there it is I will call this file as users count dot JS let's add that this will be the client side of our signalr and here we have to do four things first we need to establish a connection to the signalr hub so for that we will say variable connection let's call this user count is equal to new we will be using signal r on there we have method which is Hub connection Builder you can add some configuration within the parameters here but we will go with the simple one for now on that we have the width URL and here we have to give the URL of our signalr hub so we have that in program.cs let's go there and copy the route that we are using for our user Hub paste it right here that will establish the new signalr connection with the Hub at this location on this with URL we will finally invoke build and that will create our connection now this is basically a connection string where we are creating a connection but we are not establishing that connection yet we have to start that connection at the very end so right now we are just creating that connection here with the signalr Hub once the connection is established there are two things if we take a look at our user hub we have a method here so we need something to invoke this method and then our Hub also invokes some method in our client so we need the two-way connection so if we take a look at comments here first thing that we have is connect to methods that have invokes AKA receive notifications from The Hub so from Hub what are the notification that it is sending right now it is sending something to all the client with the name of update total views and it has a parameter so if we want to receive this notification we have to implement this update to reviews inside the client side so let me copy this name here go back to our JS and for that we have connection that is connection user count so on this connection we have an on method and there we have to write the method name on which we want to register a Handler so that is update total views and when this method is invoked we are actually receiving a value that value is the total views so we can retrieve that as a value here and we'll have an arrow function and we can do whatever we want right here so when we receive the total views from the user Hub inside our index.cshtml we have a span of total views counter we have to update that with the value that Hub provides us for the total views so we can go to our JS here and we can say variable new count span is equal to document.getelement by ID let's get this band with the ID of total views counter and then on the new account span dot inner text we want to set that text to be value Dot tostring so that will append the value that we received as the inner text of the total views counter so this will happen when the Hub will send notification to all the clients but in order for Hub to send the notification something has to invoke this new window loaded that comes next year we have invoke Hub methods so when something happens we need to trigger a method that is located on Hub so here we will create a function and I will call this new window loaded on client when this function will be invoked at that time on our signalr connection that we have which is connection user count we want to invoke a method so here you might be tempted to use invoke but if you scroll down you will see there is something called as send as well let me use that for now and later on I will tell you the difference so on the connection we are sending something that will be the method name that we want to invoke so on HUB the method is new window loaded let's paste that right here so perfect when the function of new window loaded on client will be invoked it will actually invoke The Hub method which is new window loaded we have connected to the method that Hub invokes and we have also added method to invoke methods that are inside the Hub last thing that we have to do here is start the connection so for that on our connection we have start and then we have problems so we will use start then in there we can have two methods one is on fulfilled and one is rejected so what should happen if the connection is established successfully and what should happen if it fails so for that let me also create two more methods here one will be function fulfilled and one will be function rejected so if everything is successful we might want to do something when it starts and if it is rejected or it fails then we might want to log something or do something else so inside then here we can call fulfilled if everything is successful and we can call it rejected if there are any errors right now if you want you can just do console.log here and I will log connection to user Hub successful so we have added quite a few code inside our JS file to connect to our signalr hub if we switch back to our PowerPoint we have successfully connected to Signal our hub from the client JavaScript and we started the connection then from the client side we called the signalr Hub methods and finally we also use the dot on to receive update from The signalr Hub so all the bits and pieces of typical signalr flow is covered so let's see everything in action in the next video so we have added quite a few code in the client side for our signalr in this video let me walk you through on what we did so far that way you have a complete overview of what we are doing so first we are establishing a connection here to our signal our Hub where we are using the route that we provided inside program.cs that will create the connection once the connection is made then we are registering to methods that the Hub invokes so if we go to user Hub our Hub is invoking this method which is update total views so we are telling signalr that hey I want to connect to that method so I want to receive notifications when server or Hub calls this update total views and when this method is called we receive some value in the parameters which is the total views so we will retrieve that and we are just appending that to a span and changing its inner text pretty straightforward so here we are hooking to a method that hub invokes then in our Hub we have this method new window loaded in order to invoke that method we have added a function here which is new window loaded on client when this function will be invoked on connection it is using send to invoke The Hub method so here we are calling a method on the Hub here we are connecting to a method that is there on the Hub here we are connecting to a method that hub invokes next we have added two basic JavaScript function fulfilled and rejected and we are using them when we start the connection fulfill will be called First and that will be responsible when everything is successful so let's say once everything is successful we want some notification we can do that right here and if it fails then rejected will be called so with that the client side of signalr is configured the last thing that we have to do here is if we go to our index we added the signalr.js we also have to register all the code that we added in users count so we will be adding JS for users count with that in place let's run the application even though we have users count here you can see total views is not getting affected but if you press F12 here you will see we have log that connection to user Hub was successful and if you notice information here we are using websocket to connect so basically we have connected to the signalr hub and that connection was successful now next what you need to notice here is we actually need to invoke this function new window loaded on client that will actually invoke The Hub method here and it will increment the total views and call the update total views on all the clients that have registered this client has already registered right here so let's copy this method name and let's invoke when the connection is successful so after we log let's invoke the new window loaded on client here this time when we run the application we will see the total views in action and perfect you can see total view count is 1. if you refresh the page that is incrementing but if we copy this localhost and open new incognito window paste it here great you can see the view count automatically updates on both the windows if I refresh one window the other one also gets the change that is the beauty and power of signalr so congratulations with that we have implemented the very first project using signalr and we have seen that in action with this accomplishment let's continue from the next video in the current application we are displaying total views if we refresh that or if we open up a new incognito window that is automatically getting updated in both the windows that functionality looks good right now what I want to implement is I want the total number of connected session what that basically means is that if there is a new window that is a new connection but if we refresh that window then that does not count towards a new connection so we basically want to track whenever a new connection is made and when that connection is closed we want to decrement that count so for that inside our project let's open up the user Hub where we are maintaining the total views we will have to add one more integer here which will be total users initially the total users will be zero but when a connection is made to our Hub then we will be incrementing total user if a connection is disconnected then we will be decrementing this total users so basically we want to tap into the connection and disconnection method of the user Hub these are built-in methods that are available and we can overwrite them so we will say public override task and the method name is on connected async and on disconnected async so when the connection is made with the increment total users by 1 and then let me implement the disconnected so task on disconnected async right here we will decrement the total users by one now whenever the total users are incremented or decremented we have to send this total users to all of the connected clients that way they can use that and display that on the page so just like we had a method here update total views we will create one more method which will be update total users so let me paste the same line here but we will change the method name to be update total users let's paste that now for the send async it needs an await so we can remove that and we can call get a waiter.cat result that will basically wait for this execution before it proceeds on the next line so we can do the same thing here let me hide this get a waiter dot get result now we need to implement the update total users that will be inside the JS file users count we have the connection here on update total views we need another connection on when the Hub method of update total users is invoked we want to capture that right here we will receive a value here and that value will be totaled users so let me pass that instead of total views perfect that looks good now previously we were modifying the total views counter inside the index view let's go there and let me create one more property we will copy this row paste it here and I will call this total connection or user and this will be total users counter let's copy that ID we will get that document by ID and the inner text here we will pass the value that we will receive for the total user this time we do not have to invoke method inside the fulfilled or any other place because it is automatically invoked on connection and disconnection so with that in place let's run our project and perfect you can see the total connection and users is also one now if for some reason this is not being loaded make sure to press Ctrl F5 to hard refresh that way the JavaScript gets loaded if it is cached in the browser but if we refresh here you can see the total fuse is getting updated but the total connection stays the same let's establish the new connection here in incognito window let me copy the URL paste it here and perfect as soon as we make a new connection you can see the total connection is updated let's copy this and open that in a new tab here and grid now the connections are three if we close them you will notice that it decrements in all the browser so with that we have seen the connected and disconnected method inside our signal or hub with that let's continue from the next video we have completed the first simple project with signalr and inside project resources documents I have a PDF for signalr basic flow here I'm just going through what we covered so far in this section so in order to get signalr first thing we have to do is we have to create a signalr hub we are adding that class here and we are adding builder.services.add signalr and we add the route for that hub that is the first step next step is to add methods to our Hub so inside our Hub we created a variable total views and we added a method new window loaded that increments the total views then we have to add client-side signalr so we added the client-side library and we configured signalr there we added that signal.js inside our view then we have to connect to signalr HUB from the client JavaScript so we create a connection using new signalr.hubconnectionbuilder DOT with URL and we will write the same path that we wrote In program.cs we will start that connection and we'll have fulfilled and rejected right there after that from client we will invoke The signalr Hub method using connection.send and then the method name this new window loaded is the method name of our signalr Hub that we created so that's how we will be invoking the methods inside our signalr hub the next thing that we have to do is when the Hub method is invoked it need to invoke some method in the client JavaScript so that we want to invoke on all of the connected clients so we'll say await clients.all dot send async the method name and the parameters this method we will have to create in the client-side JavaScript so we scroll down we create that using our connection dot on and then we write the method name the parameters and what we want to update so here we are basically hooking on to the notification that signal our Hub sent to the client and after we receive that notification we can toggle the Dom so that is the basic flow that we have covered when it comes to signalr and that is what we covered in the signalr typical flow now as I've said before it does not always have to follow this order but you need to make sure that you are configuring all of these points so this can act as a cheat sheet when you are working with signalr so with that in place let's continue from the next video now that we have seen one example with signalr I want to type little bit more into the different transport protocols that we have as I've said before signalr acts as a wrapper on top of this protocols the default one is web sockets then we have servers and events and then long polling it is critical to know some of the differences on how each of this work that way you can architect the application in an efficient way if you have to but before all of that we saw how HTTP requests work client is the only one that can initiate a request and server only gives back a response in a traditional HTTP server cannot initiate a request or server directly cannot send some response without a request and that is where real-time communication comes into picture but one thing that you have to remember here is when a request is received to the server it will take some time to process that request and then it sends a response after the response is sent from the server that connection is dropped it is no longer active so that connection cannot be used again to send any more data that is the critical piece when it comes to http if client has one more request it will initiate a new connection and of course I've said before only client can initiate a request server cannot initiate a response or a request it will just have a response when client sends a request so that is the traditional http so to solve the issue when server wants to send a response without any existing connection we have different protocols the first one is web sockets websockets is the answer to the problem that we saw in the previous presentation and good news is that in today's world all of the modern browsers supports websockets now you might be thinking that how can websocket solve our problem if you can see in the presentation here the connection is not a one-way connection it is a two-way connection and it stays open so whenever a client has something that it wants from the server or it wants to notify it can use that existing open connection and send that message and server if it does not want to respond back it does not have to but let's say after an hour or after some time server has some notification it does not need to open a new connection the connection is already there it will just use that existing connection and send data to the client so that is the best case scenario that we have but what if for some reason websockets is not supported in that case we have something called as server sent events let's see how that works so in case of server sent event a client will have a request to the server and then server will not give a response back it will rather create an event pipeline using that Communication channel that server creates it will be able to interact with the client so the servers and events that server is creating it is only one way it is not bi-directional like we saw in websockets so whenever a server has to send some message to the client it can use the event connection that it has but if client has to send something to the server it has to use the traditional HTTP request so client communicates with the server to traditional HTTP request but server uses the event connection to communicate or pass data down to the clients so the first fallback to websockets is servers and events and let's say in worst case scenario there is some situation where servers and event is also not supported then you can fall back to Long polling let me explain how that works we have a client and a server in traditional HTTP client sends a request and server response back and closes that connection but when it comes to Long polling the connection does not close it always waits for a response from the server and then it waits so server will not have any response it will just stay idle until it has something that it has to send back to the client now it does not wait for unlimited amount of time there is a timeout which is about 2 minutes so in two minutes if server does not have any response that connection will time out but at the same time client will initiate a new request and then it starts waiting again so client will basically have a channel which will always be open if it times out in two minutes it starts a new channel so that way server would always have a connection when it has a message it will send back so let's say this time server has a response it will respond back and client can trigger notification or use that and after that response client will again open a new connection and so on and that is why the name long calling it just opens a connection and waits until the server responds back now long polling has been supported in browsers since a very very long time so if nothing works then long polling will definitely work in your situation so with that we have seen websockets servers and events and long polling websockets is the best one available and it is the fastest because the connection is a two-way Channel and it is always open a fallback for websockets is servers and defense where the client will start a request and server will have an event connection to send the messages but in servers and events client cannot use the Event Channel it always has to use the traditional HTTP request and last but not the least is long polling where it initiates a request and keeps on waiting until server has a response and if it does not it times out and establishes a new connection right away and websockets is the default route when it comes to signalr but you can also change the default transport type in signalr which we will see in the upcoming videos with that brief overview on the transport type supported by signalr let's continue from the next video in order to send a notification to all of the clients via something which is await clients which is inside the Hub itself dot all Dot sundaysync but when it comes to signalr we have multiple options with clients and I want to walk you through all of them so let me switch back to the presentation here and you can see we have a signalr connection let's say we have multiple browser open here so we have ABC and XYZ all connected to our signalr hub so all of them will have a bi-directional channel to communicate then what we want is let's say the tab a here is sending something to the hub and in the response here we want that Hub to send notification to all of the connected clients to do that we will use the same method that we did before we will have a weight clients.all.send async that will send this particular notification to all of the connected clients but let's say we have a different situation here in this example our tab P has invoked some method on the signalr Hub now in the response here we only want a notification to be sent to the caller so for that we have a different method which is await clients.collar dot send async so rather than all we will be using caller this time it will only send a notification back to the caller that is B in our case then let's say we have another situation in which a is sending a notification on the server but in response we want to send a notification to everyone other than the caller so for that we have clients.others.centre sync that will send a notification to all the client other than the one that invoked the notification next example is let's say tab B is sending something over to the server now the response we only want to send to collection a how can we do that all of the connections that we have in signalr are identified using connection ID now how will we get this connection ID do not worry about that right now but if you want to send a message notification only to tab a you can do that using clients.client and then in the parameter you have to give the connection ID of the a tab that will send a notification only to that particular tab similarly in another example I'd say B is initiating a request but it wants the response to be sent to a and C in that case we can pass multiple connection ID inside clients.clients and then we have a comma separated list where we can write all of the connection ID where notification should be sent so you can see when we have to decide where to send the notification we have multiple options when it comes to signalr but that is not it let's say we have B here and then we want to send to all of the users other than a and C using connection ID we have something called as all except so it will send notification to all of the clients except the connection ID that we have in parameters so accept a and C it will send the notification to everyone else so that is when we are working with clients and connection ID but when we work with asp.net and we have the identity we can identify everything based on the user itself so if a user is logged in let's say Ben has to connection A and B Sam has connection c and x and Jess has connection y and z these are the identity users so if you are logged in using the identity you can uniquely identify all the connection based on the user ID how to do that we will see in the upcoming videos but that is something that you can do with signalr so in this case let's say our server has user specific notification an example could be someone wants to export in Excel and the Excel is going to take quite some time so when they hit the export button we display them a notification that it is processing and once processed you will see a notification so then user can browse the website and when the processing is done the server can send a notification to the client that hey the export that you requested is now available and if that user has two tabs open we want to send notification to all the tabs so in that case we want to send notification to all the tabs of that particular user to do that we have clients.user and then in the parameters you have to write the username or the user ID we will go into more details but that is how you can send notification to all the types of user Ben at gmail now with users you can get more fancy let's say you want to send notification to Ben as well as Jess so in that case you can say clients.user and you can pass a list of all of the user ID or user email so with that you can see we have identity that we can build in with signalr and we can get pretty fancy but let's say you have many users in your website and based on the roles you want all the users in that role to be notified so for that we have something called as groups in signalr we can group all of the users and then we can send a notification to a particular group so all of the connection in that group will be notified let me walk you through the presentation on groups in the next video now that we can see our first Hub in action and we have multiple methods on that as well I want to point out one little detail here when we are invoking any of the help methods you can see we are using send on the connection but as I was talking before there is also something called as invoke so what is the difference between send and invoke when you are calling the Hub methods from the connected client in JavaScript that we are using right now to give you a straightforward answer when you use send you do not get any response back from the server but when you use invoke it expects a value or rather it waits for a value to be returned when the request is successful so let's take a look at that with an example we are calling the new window loaded in our user Hub here right now it is not returning anything but rather let's return a string so right here we are returning back total views and we are passing the value as well perfect so let's go back to our JS file and on the method here we can use then that way we are waiting for a promise so then we will wait for a value let's call that value when we receive that we just want to lock that so let's do console.log and let's lock the value here rather than send here first let's try invoke so with that let's run the application and let me press F12 for the console window here perfect it displays the total fuse is 1. if we refresh here you can see it is getting updated so perfect it is logging everything that basically means that whatever is being returned from The Hub here it is able to capture that and we are able to use that right here but if we use send here then it does not get value back from The Hub so value will be undefined let's run this and check that out let's press F12 here and grid you can see the value is undefined here so that is the main difference that we have right here now for some reason on this function if you had to pass parameters you can always pass them right here we do not need that but let's say for some reason we wanted to pass some string parameter here I'll just pass my name right now then from The Hub when we are returning back the value here I'll just say from and I'll have interpolation let's add the parameter here string name and let's pass name as well so that way we are able to pass parameters to HUB from our client code if you want more parameters you can just add more commas and add all the parameters let's run the application and whoops we have to change this from send to invoke let's do that and let's run the application this time in the logs you will see the name that we passed in the parameter and perfect you can see it is working as expected so with that we have seen the difference between send and invoke and how you can pass parameters to your Hub methods with that in place let's continue from the next video let me show you how you can change or select the default transport type for your signal or hub so that would be done when you are creating a connection inside the JS right here when you have the with URL you can pass more parameters here so let's add a comma here and right here you can see we have the transport type so if we go to signalr dot we have the HTTP transport type Dot and there we have all the transport types that are available we have long polling we have server sent events and websockets websockets are used by default in the modern browser but let's say for some reason if you want to use the servers and events you can pass that right here with that change let's run the application in order to see the change here if we press F12 you can see in the logging here it displays SSE connected which is the server sent event if we close that we can change that to Long polling if for some reason you want to do that that could also be done so now if we press F12 here and if we see it logs here it does not display that we are using SSE or websocket it just says connected it does not display if you are using SSC or websockets or blog polling one way to find out is if we go to a network Tab and Let me refresh here you can see the status of all the call and one call stays pending that is long following it will basically wait for about 2 minutes or 1.5 minutes and then it will close this connection and it will open a new log polling connection so let's wait for that and perfect you can see that this connection has closed with a 200 and it opened up a new connection which is pending you can see the time here as well and if you keep on waiting it will keep on Closing Connection and open new connection once the time passes so that's long polling in action now let me close this and switch this back to websockets and let's run the project this time if we examine the logs here you will see that it has been connected using websocket and perfect that looks good if you go to the network Tab and if you refresh here you will not see long folding you can see the user count is connected with websockets now so that is a brief overview on how you can change the transport type using signalr now there is also something called as none but it does not make sense to use that because then you will not be using signalr I will leave this as websockets and that looks good one more thing that I want to point out is when we are using signalr you can see there are logs that are being displayed in the console window now you can change what is the level of logging that you want for your signalr application let me show that quickly on how that could be done when we are establishing the connection for that we have something called as configure logging and inside there we have signalr DOT log level and we have the multiple logs level right here we have critical debug added information none which will be useful in production and we have something called as Trace Trace is the most detailed logging that you will get with signalr so if something is not working and you cannot figure out you can switch that to trace to see what's going on we can keep that as information for now we will not be diving into logs right now but down the road if something does not work with the course we will definitely take a look at that so that being said I can comment out the logging I just wanted to quickly show you that that feature is available if you have to use that with that in place let's continue from the next video now that we have seen basic with signalr it's time to take one level up and learn something different with signalr for that let me first close all the tabs that we have open here and let me pin the solution Explorer I like to create a static detail to store all the constraints in my application so let's add a new item here that will be a class file I will name that SD for static details and I'll make this a static class here inside there I want few properties the next functionality that we want to implement is we want to implement an online boarding system but we will be using API calls for that so anyone who has access to that API if they enter that that will automatically count as a vote so basically we want to build a race system to see which is the favorite Deathly Hallows in Harry Potter so first thing first we will create constant for Bond Stone and clock next inside the static detail let's create a dictionary string will be type of Deathly Hallow which can be one stone or cloak and the integer value here will be the number of words that they have received inside the Constructor here we can initialize everything to be zero so we are adding the dictionary of Deathly Hallow raise in there we are adding cloak with a count of zero we are adding stone with a count of zero and we are adding 1 with a count of zero so initially everything will be zero this is just the basic setup next thing let's go and work on the same index View now rather than typing all the HTML and CSS I have provided that in the Snippets folder so if you go to the course detail you can download all of the project resources inside there there is snippet Section 3 we have race let's copy this div here and make sure to paste that inside the container let's just paste that let's run the application and see what we have here perfect so right here we have the deadly Hollow rays and we have invisibility cloak Resurrection Stone and Elder Wand in order to vote you have to go to this particular URL you can see the port number that I have is 7001 but what I have is 7170 I like to change that to 7001 that way it's easier to remember in order to edit that we have to go to properties and launch settings.json we have the 7170 for https let's change that to 7001 and save it let's run the application to make sure that works and perfect now we are running on Port 7001 and inside there we have a home controller but we need to add an action method of Deathly Hallows and we need type which will be a string parameter so let's close this let's go to our home controller and after index here let me add a new action method I will call that as Deathly Hallows the return type here let me just do accepted and that's okay so what will happen is in the type we will receive what is the type user is voting for if that falls within the key that we have if that is a valid key inside our static details then we will increment the counter right here so to do that we will go to our home controller and we will check if SD dot we have the deathly hollow race it contains the key of type here if it does then we want to increment the value so SD dot Deathly Hallow raise of type and let's increment that by one so that way we are incrementing the counter of our Deathly Hallow race let me just add a debugger on the accepted here and run the application now in order to test if this is working or not we will require Postman if you do not have Postman you can just copy this URL go to a tab and paste it that will bring you to our breakpoint and if you examine the Deathly Hallow raise you can see cloak has one vote now let's hit continue here let's copy the URL for Resurrection Stone and we'll paste that here let's hit enter this time the stone will have one count as well that's perfect so if we hit this again this time Stone should have a count of two so great now our logic is working as expected when we call the API our static detail which has the Deathly Hallow raise count is getting updated but our task is to display that raise count and the values right here if we go back and if we take a look at the index.html you can see I have added span for cloak counter Stone counter and wand counter so whatever value we have in dictionary for each one of this we want to display them just like we did in the user counter we retrieve document.getelementbyid we modified the text right there so let's work on that from the next video now we need to implement race for our deathly hallows for that you can use the same Hub that we have and add more methods if you want but I will be creating a separate hub for our deathly handles so inside the hubs here let's add a new class and I name it deadly Hallows Hub let's add that this will have to implement the Hub we will add Ctrl Dart for asp.net core Dot signalr there will be only one method inside this Hub where we just want to get what is the current count of the deadly Hollow race so that will return the dictionary that we have where we are storing the raise count for the deathly hollow race so let's add a public method the return type here will be dictionary of string comma int and we'll call this get race status here we just have to return SD dot deathly hollow race this is the method that needs to be invoked from the client so we will have to add the JS file as well from where we will be invoking the Gateway status to get what is the current status of the race but before we work on the client side our Hub setup is not yet complete we need to add that inside the program.cs and we need to register a route for that as well so we'll say app dot map Hub we need the class name here and inside there we need to pass the route route will be hubs forward slash Deathly Hallows with that our Hub configuration looks good for the Deathly Hallows next thing that we have to do is inside home controller where we are modifying the Deathly Hallows right here we need to invoke some method to notify all the clients that are connected to the Deathly Hallows up that hey the race count has been updated you need to get the new data let's do that in the next video now first we need to create a JS for the new Hub that we created so let me copy the user account that we have paste it one more time and I will rename this to Deathly Hallows we will change the connection name here to connection that Lee Hollows and then we need to make sure the URL is correct if we go to program.cs let me copy this go back and we'll paste it right here let me add a forward slash there and that looks good we do not need websockets here that is explicit so let's go with the basic with URL after that let me copy the connection name and we want to invoke some methods now for this particular race we only want one method that is responsible to update the UI in index.cshtml we have all these pants here so basically we want to be notified when a method is called that way we can update the UI we will call that method as update Deathly Hallows count and that time we want to receive three parameters we want to receive the clock count we want to receive the stone count and we want to receive the bond count when we receive these three we can get all of them by document by ID so let's do that index.cshtml we have the clock counter let's get that it will be clock span let me paste that two more times here next one is Stone counter and we have the wand counter we will rename the variables here that looks good now if you want you can cut three of these and just paste it at the global level right here so we can use them we will modify the clock span dot inner text is equal to clock Dot tostring same thing we will do with stone and wand so let me do that real quick here foreign so here we are just updating the inner text of span based on the count that we receive on the call of this update Deathly Hallow account now so far what we have seen the on methods that we have we typically invoke them from fulfilled or maybe the Hub method but this time the method that we have here will not be invoked from the JS directly it would rather be input from the controller when we invoke the Deathly Hallows action method so how can we invoke that from controller we remove everything else here in the meanwhile we don't need this let's keep fulfilled but we don't have any method and the connection name will be connection deadly Hollows so now we just have one method in our JS file and this is the method to receive notification from hub now the next thing we need to work on is how to invoke this method on HUB inside our home controller let's take a look at that in the next video now if we take a look at the previous Hub that we created user Hub you can see we were invoking methods to all of the clients from The Hub itself but this time we want to invoke that from the home controller doing that is super simple thanks to dependency injection we will just be injecting the ihub context on the deathly hollow Hub that we created let's press Ctrl Dot and add the using statements we will be adding that independency injection so let me do that perfect let's go back to our action method right here so once we update the Deathly Hallow raise count based on the type we want to send a notification to all of the clients that hey something has been updated with the Deathly Hallows and if we take a look at where we are consuming we need the cloak Stone and font as parameter so let me copy this method name here and we will say await underscore deadly Hub Dot clients.all now you might be wondering why are we using dot all or what is exactly a client do not worry we will get to all of that all basically means that we want to notify all the clients that are connected that hey this method has been invoked and these are the parameters so on this we will be using send async and we need the method name followed by the parameters three parameters that we want is Cloak Stone and wand count that count is inside static details.deadly Hollow rays and the key here will be SD dot cloak comma next will be shown followed by wand and perfect it's easy as that with that in place let me remove the debugging point and run the project right now right now we don't have any values here let me copy this open a new incognito window and let's paste that we pasted cloak here but you can see nothing's happening let's debug this and see what's going on let me add a debugging Point here just to make sure we are hitting that press enter here yes we are and the clock counter is four so that is actually working but I think I know what's going on I don't think we have added the JS for Deathly Hallows and of course that won't work so we will be adding deathly hallows.js and let's run the project one more time now when you are testing the signalr application in the debug mode and if you have the previous tab open let me show that like this one I didn't close it and I just rebuilt the solution it is common to see this error message so if you see this don't worry just close all the tabs here press OK and run the project one more time perfect you can see the edit goes away now let's open the incognito window here let's copy the URL for stone and let's paste that it's our breakpoint let's continue and grid now you can see the counter is getting updated let me remove the debugging point so you can see if I press 2 it updates I press that one more time let's copy the URL for cloak here and that's working but right now there is one issue let's open a new tab here and let me copy the URL localhost and let me open the same URL you can see even though there are values here they are not being reflected here if we go back to the URL and run this one more time then the values are coming along but the first time the page is loaded in a new tab it doesn't work I want you guys to fix this we have used the method to make sure that when this is loaded it gets the correct value I want you guys to pause the video and think about how we can do that I will show you the solution in the next video I hope you were able to figure out the solution on what needs to be updated so that when a new connection is made it automatically loads the current race count for the Deathly Hallow raise that is pretty simple and we have already done that in other pieces of our hub we basically need to take advantage of the fulfilled method so when the connection is established we want to load all of this div with the current value of cloak Stone and wand how can we get the current value that is simple as well if you see inside our Hub we implemented one method get rich status and that returns back the deathly hollow race dictionary so let's go back here inside fulfilled we will use our connection Deathly Hallows on there we cannot use send because we are waiting for a response and from that response we will be fetching values so we have to use invoke here and we need the method name if we go to our Hub the method name is get race status let me paste that we have a promise so we'll use 10 here variable let me call that as race counter goes to and we just need to assign values so let me copy this paste it one more time here this will be inside the race counter in there there will be cloak Stone and wand let's paste that here and that's all that we have to do let's run the project and see this in action everything is 0 here let's copy the URL paste it and refresh the page a few times the cloak is for now let's copy this and open a new window paste it here perfect you can see now it is loaded already and if we go back or if we copy some of the URL here let's paste it here end grid you can see everything is working as expected so with that our deathly hallowed race is functional and working as expected hope that gave you a good foundation with signalr if you are interested in more advanced topics and more projects with signalr I have a complete course on signalr on.netmatchedway.com in that full course I will be building eight projects and all of them will Implement different use case of signalr I have a video of demo in which I will display what will be the eight applications that we will be building so take a look at that and if you want to advance your journey with signalr I will see you later in the course signalr the complete guide but I hope you have enjoyed the free video and do not forget to like the video and subscribe to my channel good luck and happy coding
Info
Channel: DotNetMastery
Views: 6,111
Rating: undefined out of 5
Keywords:
Id: pl0OobPmWTk
Channel Id: undefined
Length: 93min 59sec (5639 seconds)
Published: Mon Aug 01 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.