Intro to SignalR in C# Part 2 - Beyond Chat Applications

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
signal r is for more than just chat applications in our last video we saw a standard demo for signalr where we connect multiple clients to a chat hub so we can see just how signalr worked and see the internals of what's going on now in this video we're going to extend that demo by adding a second hub this will trigger the counter on the blazer page from our wpf project just to see how you could trigger and send other types of data besides just text now if you don't know me my name is tim corey and my goal is to make learning c-sharp easier i do that by providing videos here on youtube multiple times per week plus i have a weekly podcast i also provide courses on c-sharp web development and much more on imtimory.com the profits from those sales are what pays for the free content here on youtube so that everyone can have a great education in c sharp not just those who can afford it now in this video as with most of my videos i'm gonna create some source code if you'd like a copy of my source code use the link in the description in fact we're gonna start with source code from last time so when you get the source code you get the completed source code but if you want the starter source code for this video go to part one and get that source code all right let's start off in visual studio and again this is part two so we're starting in the middle don't expect to start from the beginning if you want the beginning go to part one they'll make a lot more sense at that point but what we're going to do in this video is we're going to move beyond that idea of signal r is just for chat where i use it for actual coding things that we need in our case we're gonna do is we have a counter page and this is the the standard sample page it comes with blazer either kind of blazer and this has the increment counter button we click on it and it's going to change the current count but we're going to do something a bit different instead of being on this page and clicking the button we're gonna be on this page but we're gonna even take this button off that button goes away so we will not have an increment counter button but we're going to use our wpf client to trigger this button now why would we do this well what if we wanted anybody to have a vote button maybe we have a whole bunch of wpf clients out that have a vote button and anytime anybody says yes i want that they click the vote up button and it the system will have a web page that's displayed by a are visible to all that shows how many people have voted for a given topic that might be a use or maybe we're going to send other data but this is our our demo so we have a counter we're going to change this from our clients and the the the blazer server project is not going to be a client it's just the server it's not going to be able to trigger its own counter okay so that's kind of the setup so let's go to our hubs we're gonna right click on hub or hub folder right click on the folder and we're gonna say add new class and i'll call this the counter hub and we'll say colon hub which control dot to add the using for the microsoft.asp.cor.signalr we have one method in here public task add to total string user we'll still pass the user in so you know who who voted for it or who anchoring the counter but int value oops lowercase value notice that's an integer not a string and return clients dot all now i could say only a certain client but i'm not going to do that um in this case because of the fact that we're going to broadcast everybody but not everyone's going to listen to it i want to show up how to do that in a more advanced video it might get into how do you filter out certain clients and how do you only send a certain people but in this case we're going to say clients.all send async and let's say counter increment and the user and the value so again this is an integer not a string and this is kind of the event that will be triggered on the client now i did say that the um blazer is going to be only a server but it has to be a listener client and that's kind of my bad there it's a listener client but not a sender so it'll listen for these events but not send out events so let's save that we now have our new counter hub which means we need to go over to our program.cs where we map our hubs and we map a new hub app.map hub and this is not chat hub this is counter hub and we give it a path so we can say counter hub is fine we could call whatever we want to call it but we have to know what this path is in order to connect to it on our our xaml side on our jpf site okay now let's let's go to the let's go to the counter page first since we're already in blazer and we're going to create the listener here so it's going to listen for those events at using microsoft dot net core dot dot client and we're going to inject nav navigation manager call it nav manager and implements i async disposable which a lot of this is the same from the other demo so we have our counter and we have our code and in our code we're going to say private hub connection that's nullable called hub connection and then we're going to have a protected override async well let's do a override uninitialized async and then come back and add the async it's easier that way get rid of our boilerplate code and we're going to have that connection so hub connection equals new hub connection this is this hub connection builder sorry this is the same code as what we did previously on our index page except for this particular line or with url nav manager dot to absolute uri this is the difference here slash counter hub so we're connecting the counter hub not to the the chat hub and with automatic reconnect and then build so on actual async we're going to connect to our counter hub and then we're gonna keep this really simple we're not gonna do a lot of crazy stuff here we're not going to do all of the the wrapping and the try catching all the rest we're gonna assume that works and just get to the meat of what's different to call the counter hub versus the chat hub so hub connection dot on this is the the difference here too string int how is it string int well because we're connecting to the counter hub and that has a string and int that's the method so on counter incremented all right spell that correctly make sure you get that correct okay that that string has to correspond to this right here we're listening for this particular the counter incremented where i pass in the user and the value i'll call it value because it's an integer and we're going to have the arrow curly braces semicolon at the end and inside here we're going to say current count plus equals value so add the value to the current count which is going to change the current count value and then because this can be a different thread we're going to have to say invoke async state has changed and we're gonna await the hub connection dot start async so we set up our listener for that event and what's gonna do and we start the connection to our hub again we're not wrapping this in a try catch here because the fact that we're just doing um a quick demo to show the differences we're not going to try and do all the setup and we do all the setup it takes a long time thus the last video being too long to be just one video so with the start async we're done and then i'm going to actually come over to my index page and again for time sake just grab this right here the dispose async copy it and the bottom down here we're going to paste it in that way we have the the proper dispose there for disposing also note i am i don't have anything to enable or disable uh or say what the connection state is we just assume that's that's properly connected okay that is my counter page that's all it is it's just going to listen for that event now event hasn't been called yet how to get it to be called well we have to write some extra code in our wpf client which is what's going to do the actual calling so let's go to our wpf client and in here let's go right below where this list box is we're going to put some more text in here so we're going to say stack panel orientation is horizontal and grid.row is 3. so it's after we have so far and we have the um also the horizontal alignment that's the things inside we center we have a button the name is going to be open counter so as opens the connection to the the counter and we're going to have the padding let's say it's 20 and 10 i believe we'll eat 34 and the margin is 20. and inside here we're going to say open counter connection that's our first button and there i have one more button so let's copy it and paste it afterwards now we have two buttons we have to give a different name before it shows up increment counter and we should put the text in here of increment counter so in one line they have an open connection have a message we're going to say open connection and then increment counter which we're going to hard code the values going to increment the counter by again try and keep this simple so let's first open the connection so in here we need to do is we need to [Music] open the counter connection we already have our our setup here so i'm just going to copy the try cache because it is nicer to have that but i end up with a message in the same message window so it's a little bit again a little bit lazy just because of the fact that i have one message window that gets all the messages but it's good enough for a demo wait we have to wait a counter connection we don't have yet so let's set up a counter connection let's go back to the top we have a hub connection here let's create another hub connection hub connection counter connection and then in connection i'm going to copy this and paste it and we're going to say counter connection and this is the counter hub so make sure you have counter hub there not the um the other one now again we're not going to set up all of the um the events here for reconnecting and reconnected and closed we're going to assume that it's open when we say open it so right down here we're going to come down here and say wait counter connection dot start async done that will open a connection to our counter our counter hub sorry come back over here to the form double click increment counter inside here let's do our our try our catch exception ex and then again that same you know throw the message the exception on the window in case there is one but then here we're going to say await counter connection dot invoke async the method add to total put comma and we're going to pass in two arguments let's go to the next line the first argument is going to be our wpf client which will be ignoring even who the user is at this point our second argument is one okay and that one right there is going to be the value we're sending in notice it's an integer we're asking that integer into the add total which go back to the counter hub add the total takes in a user and a value so we're passing a user and a value which then gets sent to all clients who are listening to the counter increment cool that's it we're done we've separated out now because the wpf product isn't listening for the event that's triggered the send all async it's not listening for the counter increment on wps submits we don't care on the wps side what that counter increment value is we are just saying to the server that's all we care about is send to the server let's see a one-way connection send that value up to the server and then the server sends it out to all listeners which happens to just be the counter page so we're going to do the start multiple here wait for it to start and we have our wpf project which by default starts in the index page let's go to the counter page notice there's no button to increment the counter we open the counter connection once it's done now we increment the counter which i have to do on faith but anchoring the counter nothing happens cool oh it's it's open but it's not actually triggering the event we're going to find out why in just a minute so let's go back to our code because that should work so what we're doing here is on the increment counter click work we are saying hey invoke the added total which if we go over here add to total make sure we get the the um value is correct so we're gonna put some break points in here see what gets triggered so put a break point in the hub and we're going to put a break point here just well this should happen because we're hitting the click now the other thing is i do want to say here open counter is enabled as false just to disable the open counter once reconnected that is visibly shows us that something happened to open the connection so let's try this and then let's go to the counter page and let's make sure that let's make sure we've actually started the connection so on initialize async we are listening for the counter incremented let's go back over here counter incremented ah here is the difference actually the breakpoint away so this is where strings come to bite you and you can use you know have a library or something where you use uh string constants or something else to make this easier that'd probably be a good idea but in my case isu strings which this says counter increment and this says counter incremented this should be increment so if you don't have a listener nothing happens let's start this again so wpf app is here we have this app over here and we go to the counter page because remember you have to open the counter page up for the counter to be listening for that event and let's zoom in a bit more on this page so the counter is a bit bigger okay open counter connection it grays out means we've connected to the the counter hub increment counter see that so now you click the button over here in wpf app and it increments over here if we remember we before came to this spot right here and we grabbed all of these which is that's the um the bin debug net 6 windows folder i can copy these and then i can go over to our temp wpf i can delete all these or just i could overwrite them but whatever paste them in and now i can open up an independent wpf client so now i have the one debugging from visual studio and independent one i can connect as well i can increment from there or the other one just fine now this one the ones independent is still doing count by one but if i shut down all of this and i go over to my wpf client and i change the event instead of saying one let's say three so the one that's going to be in debug mode is going to increment by three but i'll still use the old copy which increments by one on the um on the other page on the other wpf client so here's the new one and let's start up the old one as well so open counter connection on both so the bottom one's the old one top one's a new one increment count on top one notice three six nine twelve the bottom one 13 14 15 16 so we can have different clients that send different information it's all good they both connect they both send their information it all works we can even have a box on the wpf screen that was a number box we could put whatever number we want and that would add to our counter total so the point here is to show that we don't have to rely on signal r just send strings we can send other data types and have more complex interactions based upon those data types we can even have a login system or something else where we send in that login information and then say hey only these users only the admins can update the counter by more than one but anybody else can update the counter by one or lots of different logic things we could do with this setup but i want to show you the fact that you can create different types of hubs you don't have to have both the the listener to the event the broadcast and the broadcaster on the same on the same uh application you can have them on different applications so in our case with the counter the wpf client is the the client that sends the broadcast that says here is what to add to the total and the the blazer project is what's listening for the broadcast and says okay i'll add that to the total so they can be separate they don't have to be connected and you don't have to send in strings you can send in other types of values and it will still work so lots of really cool stuff you can do with blazer i'm sorry with signalr in blazer or in wpf or other project types you can connect with a console app you could have apps that will open up connect to a signalr hub send some information close back down so there's stuff i can they can do that as well or maybe open up for a little bit send information listen to the responses they get listen for a little while and then close back down there's lots of stuff you can do with signal r for real time communication it's up to you how you decide what you want to do with signalr just note that whenever you're using signalr the clients that are connected are continually connected now this is a very very low bandwidth connection when you're not actually talking or doing anything it does send a ping back and forth and it's a very very again just bytes of data um just saying hey i'm still open and making sure that connection is still open so that when it is no longer open it knows that and tries to reconnect but it also uh whenever the data is being sent across it tries to send that data in as efficient a format as possible so that we're not clogging up your network but again if you run this on your server your network card has to be able to handle a lot of connections potentially so just note that's the case but again your server should probably be able to handle 10 to 20 000 concurrent connections so if it can't handle that many maybe your server needs to upgrade but even if not you could go to the next step which is azure has their own signalr service you can offload the work onto so that you don't have to be hosting it locally in your web server so what the signal our service does in azure is it hosts the server side where it listens for anybody broadcasting an event and then it sends out the broadcasts to whatever clients you want to saying okay here's that message i just got so that can really allow you to scale up how many clients you can do with signal r if you want to get to massive sizes but for the average person for the average company you will not need to scale up signal r you just use well not unless you're abusing it so with that what questions do you have about signalr now you may be saying well tim you know i asked my question last week on part one yes but i'm recording these two videos back to back so i didn't get your question yet for from part one so what questions do you have if you you know you had a question before that i didn't respond to or maybe you have a new question now or new thoughts leave them down in the comments or just what you thought of signalr and and how it might be useful in your organization or your code again don't abuse it not everything needs to have a constant open connection things can talk to the server and poll for data or you know connect once in a while they don't have to always have constant connections but for those things that really do when you have to have the latest information for example if you're playing a game of checkers with someone across the internet you need constant interaction you can't refresh the page all the time waiting for the next move that's where signal are be great you know if you want to have a real-time strategy game again you need to have real-time communication so make the right choice of when to use signalr it's not a for everything solution but when you need it it's a great solution for connecting again using the web standard websockets with the fallbacks if your your device does not accept web sockets okay so again let me know in the comments what your thoughts are on signal r and what more you want to see whether it's you know further videos whether it's a full course on signal r what are your thoughts on this and i'll try to answer as many as possible or at least read them and then if if i can i'll work them into future content for you thanks for watching and if you want the source code for this use a link down the description as always i am tim cory [Music] [Applause] you
Info
Channel: IAmTimCorey
Views: 26,266
Rating: undefined out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# course, C# training, C# tutorial, .net core, vs2022, .net 6, signalr asp.net core, signalr tutorial c#, signalr tutorial, signalr, web sockets, long polling, wpf, blazor, signalr core
Id: -JzWg-Kwu7g
Channel Id: undefined
Length: 27min 58sec (1678 seconds)
Published: Mon May 02 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.