Intro to Blazor Server Side - Includes SQL Data Access and Best Practices

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
blazer is a shiny new buzzword in the c-sharp community but what is it and how do you use it in this video I'm gonna walk you through a blazer server-side application we will look at what Blazers server-side is how it works and how to make use of it including how to hook it up to data access code before I proceed I do want to point out that in the description there are links to get a source code for this video to sci-fi mount my mailing list to join patreon and to get access to my courses if you're looking to make a career I see sharp or want a better in your c-sharp career my content can launch you forward faster check out all I have to offer I am Tim quarry calm or sign from my mailing list to hear from me directly now if you haven't come across 284 my name is Tim quarry and it's my goal to make learning c-sharp easier one of the ways I do that is by teaching context there are a lot of tutorials out there that teach you what to do I go a few steps beyond that to show you when to do it why you should or should not do it what pitfalls to avoid and what the best practices are basically I could array for the real world if that's the type of training you're interested in subscribe my channel and hit a little bell icon to be notified when I release new videos ok let's go to visual studio and we're going to create a new project now we're going to do blazer server-side so a search for Blazer and we have this blazer app here now this is released this was released in dotnet core 300 currently run net core 3.1 so this is production ready this is blazer server-side not blazer client-side there is a difference and we'll talk through that hit next and I give us application a name so blazer demo UI and blazer demo app hit create and it says I have a solution that name already on disk don't overwrite the existing solution no let's do blaze or app instead of blaze or demo app that should be good and it says blazer server app okay so this is what we'll use is a blazer server app now a difference between server side and client side is that server side still acts a lot like a razor pages application or MVC application in the fact that the server does all the c-sharp work there is no c-sharp it comes down to client really or at least not the same way now what happens instead is we keep a connection open from our client which is the web browser to the server and so any requests are made that request goes up to the server and gets run there Blaser client side will take an actual dotnet runtime down to the client and run c-sharp code at the client level we're not going to do that here we are uncie sharp on the server not the client the benefits are there's a lot less a download and it's a really fast connection the downsides are that this is not offline capable it cannot run when the server is not available so you can't have a PWA a progressive web app that uses blades or server side and has offline capabilities ok so just note that that this is not offline capable but otherwise this is a really fast really great option and the only one that is production-ready today dot dot net core is going to release a version of Blaser client side that should be ready around the may 20 20 time frame and that point then you can have the option of server side or client side into paint a situation you can choose one of the other based upon your needs and the needs of your client the nice thing is we have both tools in the toolbox so not everything has to be solved the same way okay so we're at a select bladed server app we're at configure for HTTP we're not going to add authentication or docker support now says dotnet core 3.1 hit create and this will build out for us our blazer app this blazer app looks a lot like a razor pages application or MVC application in fact if you're from familiar lot of same structures which helped make this an easier transition into this type of application for example we have startup this is where the application is configured so we have things like our services here we have our our building phonemic routing and endpoints and HTTP redirection but we do have this one additional entry here that says map blazer hub and that's where the signal our hub is mapped okay now signal R is the communication mechanism that we use to connect the client to the server so whenever a web browser opens up its gonna have a connection probably a WebSocket connection back to the server it's a very fit efficient low bandwidth low impact connection you can have thousands of them per server but that's has going to connect the client to the server is through signal R and so that's kind of the background that's where that gets loaded right here where it says Maps a blazer signal our hub to the default path alright so that's a one tweak we see here we also see up here our under our services we add server-side blazer alright so that is the additional service we add up here that's indicating this is a blazer application now this does mean that you can mix and match other things like razor pages if you want to put a razor pages or MVC in here you can do that it's just like any of the other applications you just add in the services you need and add in the endpoints you need and and the routing will take care of itself because you'll you'll put in that routing information all right so it's very very similar to MVC and razor pages program CS pretty much the exact same thing whereas building it out we're saying okay build and run done that's it all right so what are the differences well one of the differences is the pages end with dot razor instead of dot CS HTML so app dot razor this is kind of the main page here and it says okay I want you look at the app assembly program dot assembly which is basically blaze or demo UI as we're looking for and saying if you find route data then go to that route data and the default layout is main lamped so the saying is when someone requests a route if you find it then go ahead and pass that route data in and the default layout if they don't specify one is going to be main layout which is in shared a similar concept we have in razor pages but this again as a dot razor pay just mainland now the cool thing is this is if it's found that route is found if it's not found use the main layout as the layout and then inject into that a paragraph it says sorry there's nothing at this address this is kind of your page not found or 404 now let's look at the main layout dot razor pretty similar to any other razor page except the fact that we have things like nav menu that's interesting and we do have the app body ok that's where the inserts of the by which were used to gets inserted but where do we get the rest of the stuff so you may say well where is the CSS files and the JavaScript files this main layout doesn't have them so we are under the pages folder there is host CS HTML and inside there you will see this layout page it looks a little more familiar it's more like an actual HTML file so we see the doctype is HTML we see a language is English let me see the head section and in the head we see there's the site dot CSS there's bootstrap and then down here we have a script for underscore framework slash blazer server j/s alright so what is that well this is kind of built in server JS file that we'll use to communicate back to the server this is kind of the glue that holds things together it's me the one that talks to through the WebSocket to our our third signal our to our server to get the information or to call information or to save information all that will happen there and this is the way it call that is through this j/s file which we don't have to modify alright so this is our design surface for our application let's close all this down and let's look at an actual page so really look at the let's throw the counter so there's two pages here that actually do something and Microsoft has given us a nice example in this application so we can see different pieces the counter and the fetch data are the two pages that actually do something as RAZR pay or as blazer pages okay a little confused because it this is a blazer application and because it's a blazer application the extensions we use are dot razor which is very confusing because razor page applications use extensions of dot CSS HTML so razor page applications use CSS HTML blazer applications use dot razor yes it's a little confusing but it is what it is so there's two raiser pages that are of more importance in this file as examples the first one is counter dot raiser okay and this is a very simple example of a blazer page the very first thing it does it says hey I'm a page so at a page and then it says here is my path now if you're familiar JavaScript frameworks this is similar to how JavaScript frameworks do it where the the actual you know single page application has paths and you can have what looks to be a different page and it's just a different path on the same page well it's the similar concept where you declare this is what the path is to this page its slash counter now if I made that slash I made this up well then the URL would be our our our localhost colon you know 1 2 3 4 5 whatever the port number is slash I made this up instead of slash counter so this is how we determine what the path to this page is going to be which means if we want we can actually say slash data and create that path for us next we have our HTML and then afterwards we have the at Code section think of this as the code behind for our blazer page unlike razor pages which have a separate page model that kind of acts as the code behind is a separate separate bit of code blazer pages have the code right on the page I'm not a huge fan of that by the same time it does encourage you to keep your code light keep it small and focused just on the UI if you have hundreds of lines of c-sharp code a blazer page you've probably done something questionable at least okay a I'm not saying it's wrong I'm saying you need to question it you know think through am i doing too much in this code could I put this into a class library or could put this into units a class file and call it okay so think that through when you write your code you may have dozens or even even 50 lines of code but when you get around a hundred unless a page is doing a ton of stuff you're probably putting too much code there's too much c-sharp code on the page so just a kind of a a rule of thumb to think through now your HTML mixes with your c-sharp like normal so you have your at symbol and then you can put a variable the unlike with with razor pages where that's the code behind the page model through a referencing we're referencing here this this current count is a private int right on this page and let's be very clear on that this is a private integer and this page has access to it so these are private this is local just to this page but this page does have access to this variable so these two things are in direct connection so the current count is just this variable which is a private integer it starts off at 0 now we have a button a very simple button with a that says primary button it has an at on click and this is kind of frustration number 2 and that is with razor pages we have this new syntax where you say ASP - and we have a number of different options and that's where all of our commands come in ASP - well with Blaser it's not that way we have to learn new set of commands a new witness of way of doing things so it's a little different so for a click event it's at for our c-sharp code at on-click now if you you see here it does have that in the menu so if you were assay at you can find it here you know on copy on click on drag and drag start on drop so there's a lot of different options you can do and it does show you in the list it's just not the same as what razor pages does or what MVC does it's again a different syntax so just know you could have to learn a new syntax a new way of doing things for blazer apps but at the same time they are different so it makes sense that they're different it's just one more thing to learn okay that's just all I'm saying so at unclick and this is a method name so when the click event happens call this method increment count well private void increment count that's the method in fact if we do a ctrl J here it would find that intellisense so it knows what the available methods are and we can call that method by us putting it in here so when this button is clicked that says click me it's going to call this method that says increment count increment count simply takes the current count and adds one to it that current count is a private variable which is currently being displayed up here that's going to increment that number so we'll see that so let's run this page and see what happens there are launches application I launched it in kestrel you can launch it is Express it's up to you doesn't really matter I just prefer casserole and seeing this output here about what's going on in the web application and here we go so here is our web application it says hello world welcome to your new app and let's click counter to see that page we just talked about so first of all up here slash counter that's our URL and it says current count is zero we have this click Me button that says well click me I click it and it changes the value to 1 2 3 4 5 6 7 okay every time you click it it changes that number now if we go off and come back the current count is 0 because we wiped out that page when we left it all right now let's look at what's going on behind the scenes so we hit f12 to bring up our developer tools what I'm gonna do is I'm gonna move this screen off of your viewing area so I can show you this in full screen so under our network tab this is we're gonna see everything's going on with our network and currently I'm I'm showing all I'm gonna do is i refresh the page which will reload everything come back to the home and I'll hit refresh now that's a full refresh which means it's downloaded everything we need all right and with that we have a total of six hundred and thirty-five kilobytes of data transferred what is that data well if you look through let's sort by size we have the blazer dot server j s the xhr file and the script and those two are 210 kilobytes and then we have bootstrap top man which is 152 kilobytes and then favicon is 31 and so on all the way down to our actual page this is all of our information about our our document okay now what is how we gave us information if we look at the console let's actually look at the network I'm not gonna change anything okay so you got 10 requests right now let's come over here I'll go to counter watch number of requests didn't change I clicked the counter click Me button I clicked it 15 times still 10 requests still 635 kilobytes transferred so what's going on how does this work but how I even see any network traffic is it seem like there's no network traffic even happening let's move us off and look here under type and the one right down here that is an underscore blazer and it says question mark ID equals and this is a WSS connection which is a WebSocket connection if I click on this notice its needs a binary messages and there's you can't really see it over here he's it's so tiny but there is a scroll bar and this thing scrolls for a long time which may seem really intimidating like man there's a ton of traffic coming on in this WebSocket connection no not really because if you look at the length 3 bytes not kilobytes bytes this is a binary message there's a total of 3 bytes long this is our stay alive message that's really all it is now let's clear this and then I'm gonna hit the click Me button ok when I did that it came through with three messages these first three right here so 292 bytes 149 bytes and 27 bytes let's look at them all right if we clean the first one we see dispatch browser event as its event handler and it says mouse right here it says Mouse and then down here it says it's click event and then a screen x and y position to where I clicked it and the information with a click okay then the next so that was up then down came this J has dot render and it gives us information including right here it says 16 which is the current count number we're on so I that's the display now yes this is ugly because it's binary I'm using a hex viewer to view this as somewhat readable content this is really binary transfer because WebSockets are all about really efficient transfer of data in fact that transfer of data was a hundred and forty nine bytes so with a 292 byte message we sent up a event saying the mouse has clicked the button here's the x and y-coordinates gives you all the other information you know and which button it was all the rest that's what went off to the server what came down from the server was a hundred and forty nine bytes and that's the response saying okay put this value in this spot so it didn't read it didn't return the whole page which is what a typical server-side event does it just returned the value it needed and then it knew where to put that value on our page to render it so really efficient very very efficient very quick and in some ways faster than even a single page application might be because it's not rendering the whole page it's not reprocessing all the data on the page it's just target at one piece of information now some cert single page applications do that and do it efficiently as well I'm not trying to say this is better than I'm saying this is a really efficient way of doing it just like the more efficient single page applications do okay so that's what's happening behind the scenes now this is still alive notice if you scroll down here we got a lot more going on a lot more less three byte messages to kind of keep alive saying yes I'm still here yes I'm still here kind of paying back and forth practically okay now if we go down to the next page I want to look at fetch data this gives us a bunch of information which if we look over here that was three point four kilobytes down but that's the expected since what it did it rendered all this information this whole page essentially including this data and this is real data or real ish okay so let's look at this page now notice there's not a lot of calls back to our server pretty much it's pretty quiet because that it what it does it just does those calls back and forth over the the signal our connection so let's go fetch data fetch days a little bit more stuff first of all at page saying yes is it this is a blazer page and here is the URL slash fetch data now we have a using statement the top you know what using statements are in c-sharp code they just make life easier so instead of saying blazer demo you I dot data dot something we can just say that whatever the dot was you know the in this case down here it is weather forecast so it's actually blazer demo you idea dot with our forecast it short adjust weather forecast the next one's a little interesting inject inject weather forecast service and then it has a name after at forecast service what's going on here well this is dependency injection which is why it's called inject so if we go back over to our startup and look here at our configure services we'll see add singleton for weather forecast service so this was put into two pansy injection as a singleton now the fetch data page says I want that singleton therefore I'm going to inject it alright so this is the equivalent of have a constructor that asks for a weather forecast service it's just we don't have a constructor on a blazer page therefore we inject it so this is the variable name is forecast service now I'm not a huge fan of forecast service because it is it is Pascal case and it does have the underscore not a huge fan of that I would prefer to see us use a similar naming convention to c-sharp and we'll do that when we do it okay so now we have just some basic HTML a set up and then we have an if statement if forecasts what's forecasts well forecast is a private array of weather forecasts all right so if forecasts equals null meaning we've not yet instantiated or not yet put values into it then we're gonna display and it's kind of cool this loading right here so say you have a connection to a weather service and we're gonna load data in but it's kind of slow maybe doesn't load right away mean it takes 3 4 5 seconds to load our data we don't want to show the users weird blank page so we can say hey if it's null then go ahead and show the loading indicator which could be a gif it could be a spinning icon it could be a little guide data ditch okay that was what I did back in college and you know about 25 years ago but that's what you can do okay some way of telling the user that yes this thing is loading the page now once the forecast is no longer null that's the else to it then do this let's create a table with all the information all the header information then we have a for each again if you've done razor or yet razor pages or NBC you probably know this structure here at for each and then create your each row create a row for each of the forecast items and then just display the date of temperature in Celsius and Fahrenheit and the summary information okay that's all it is now where does this information come from well down here firstly you have our private variable to hold the information but then we have this protected override async task on initialized async so as a number of methods that are available to us as page events so if you say protected override and then hit space we see on after render on after render a sync i initialize on parameters set on parameter set async and and should render okay and of course you also have I initialize async so there's our our options for the events for this page in this case they've used the on initialized async and said that the forecast variable she loaded loaded from the forecast service dot which forecast service was was injected dot get forecast async and pass in the date/time dot now for when you want the forecast for all right and that's gonna wait that and when it's done it puts the value into forecasts which then updates this page to show the else which is this table all right let's look at this forecast service which is the weather forecast service with our forecast service and this is just kind of simulating data access and saying get forecast async got a random generator and that's gonna generate random information for the temperature in Celsius and then I believe here for the ok temperature in Fahrenheit is the conversion from Celsius though it's always in sync nothing weird like you know 55 degrees in Celsius and Fahrenheit let me kind of odd alright so this is how we get the temperature in Fahrenheit to match the Celsius one but random temper in Celsius a a summary that's based upon a random value from this summary array so it might say freezing when the temperature in Celsius is 55 which is in very very hot all right so yes or not that match that's okay this is just a simulation of a call to a service so as what's happening here all right so if we run this again we'll just see us in action just again to kind of get the the other end of it and see it after we've Kerry viewed it a little bit so the fetch data this gives us notice 75 degrees and warm 11 degrees and bracing is this Fahrenheit I'm more familiar the Fahrenheit 11 degrees in mild even though 11 degrees is bracing okay now I did get this one right 123 degrees Fahrenheit over 51 Celsius is hot yes yes it is it's very very hot but medium blazing but that's okay this is just simulating fetching data force all right so that's kind of an overview of how Blazer works but let's actually make use of it and create our own page to go through some of the pitfalls and processes you might normally do so I said let's do this I'm gonna hook up to a database I already have in sequel and we're going to read people information first name last name email address and then we'll do is we'll also have the same page we'll have a way to insert new people into the list so have a loading from the list in sequel and a insert which is going to save right to sequel so it's kind of like a full data access for Blaser server-side so let's start and the way that you should start with all data access and that is Korean class library and the reason why is you do not want to tie your UI which is our blazer application directly to data access that's unwise so let's go a c-sharp and we're going to look for a class library you will do dotnet standard dotnet Stanners important because it works across a lot of different platforms more than just dotnet cord us so don't as standard if you can is the best option hit next and we're a call this our let's just call this our data access library and we're going to delete class one and in here let's let's shrink down some of these things in here we'll do is we'll create a class for sequel data access then it creates me very very basic something I've done me for a lot of my different demos because it's just it's so quick and easy to do and it's same time so powerful we're going to use dapper so use the version right now is 2.0 point 30 and inside here we're going to create first of all a constructor and the constructor regret ask for an eye configuration control dot which we need to install a package Microsoft I extensions that configuration died abstraction which what I do and then config control dot to create initialize a field underscore config now if you don't if yours doesn't do underscore you should watch my visual studio configuration tips video that will talk you through how to do that actual Studio editor tips I believe but that will walk you through how to make that kind of tweak to your system alright the other thing I want to do is I'm going to store in a public property so prop string let's say connection string name and by default it's gonna be default and the reason I'm doing this because this is a really quick and easy data access library I'm gonna say that by default it's gonna access the connection string called default and if you want to change that you just changed this property right here if you want you can get more in depth with these libraries I do in the tIMCO retail manager series but this is basically the same pattern we're going to do but a little simpler for this demo the point is not to teach data access if you want to learn about dapper you can watch my connecting c-sharp a sequel the easy way video or my advanced dapper video this is more about getting something in place but the same time I don't want to skip over it and leave you questioning what's going on so we'll talk through it but talk through it kind of fast public async task which control dot to add using system three net tasks and a list of type T load data and load data is gonna have to be a generic have T and u as the options string sequel and you parameters as it's going to take you in two different types actually want a sequel which is a a sequel string and then a parameters which is a generic type it'll return a list of T a generic type so string connection string equals underscore config dot get connection string and then pass in connection string name notice that the Intel Akkad is kind of showing me what to do there with the starred values making life a little easier for me using ID be connection control dot to add using system data connection equals new sequel connection control dot add actually to install package system data that sequel client and we're a say connection string notice the star there to make my life a little easier okay and then inside our using statement let's move this up a little bit we're going to save our data equals a weight connection dot query async control dot add are using dapper so query async of type T and pass in our sequel and our parameters so this is doing it is going to query our sequel database and it's going to pass in our sequel statement in our parameters and then get back a list of type T actually an ienumerable of type T that's what this is going to be right here this data we want a list of type T so we're going to return data to data dot to list control dot to add the using system dot link so this is our load data let's do to load data we're not gonna do store procedures just regular sequel statements really quick and easy little statements oops not open safe now public async task save data of type T string sequel and T parameters so the parameters can be anything wants to be their generic string actually just copy this right here get the connection string actually is copy this whole thing the difference is inside of our using statements so a weight connection dot execute a sink sequel and parameters what this is going to do is save you this is an execute statement which is going to run an insert a update a delete something of that nature where you don't need to have data clean back and it's going to run whatever sequence it and we give it and then parameters and return nothing except for the fact that the task itself saying yes is complete so that's saved it now it's asking for I configuration well we're going to put this in a dependency injection so that's gonna come through from our front end and we already have I configuration built into our blazer application now I do like to have an interface let's do a quick actions refactoring and extract interface I'll hit OK I haven't put this in a folder Dubey if I should or not I'm not going to alright so right in the root here and let's add a new class here and let's call this people data make it public and also going to need to have a model here for the data so let's do this let's create a new class inside the models folder and it'll call this class let's call it person model make it public and we have three properties in here first name last name email address all right that's it so now in our people data let's have a constructor CTO are inside here right ask for an eye sequel data access where I call this DB control dot to create initialize our field so now we have accessed this isequal data access we're having a public task control dot at a using summit their task of type list of person model controlled on to add our use into it for that so this is going to be get people pretty simple stuff string sequel equals select star from DB o dot people that's got our database table name now where's your database well I've got a little database here and sequel server object Explorer let's load this so let's let's add a connection here don't have a connection evidently to my local DB and hit connect there you got a local DB inside here let's look for the person database inside the tables I have as people ok this is I'm not sure when I create this person DB but in here we have first name last name date of birth if they have one and email address all right so there's our records for this table we're only worried about the first name last name an email address will ignore date of birth so get everything from people which means it's going to return back the date of birth even though we don't need it now the beauty of dapper is it's okay it's just going to ignore that column and not do anything with that data but it's more efficient to select say select first name last name an email address from DB o dot people just so you know unless a star is fine and then return underscore DB load data of type person model and whoops also dynamic is a second type and say sequel and new empty anonymous object so that is our parameters which we have no parameters it's getting us all the people so therefore that's all we need again this is a really quick and easy call to our database we're not doing anything that's you know really in-depth here we're just in a basic select star from so get people we also need an insert person so public tasks insert person and we'll say this is a takes a person model called person like so anyone I say string sequel equals this is a little more complicated we have an @ symbol to beginning so in do two lines insert into dbo dot people first name last name email address to enter on a tab over so it's kind of in line and say values and then a little trick here I do I copy this and paste it by so I call at the end but then I put the @ symbol in front of each of these because I typically match up my variable names to the column names so that is easy to create this insert saying that because I just copy and paste those values now I can say return underscore DB dot save data sequel and person person which is what's the model being passed in that's my parameters it has first name last name and email address sequel is this statement right here where it's going to insert the values from my person object into these three spots that's all there is to it now I am saying here just return save data which save data is an away table task I'm not awaiting it I let it go right through I don't need to await it here there's no purpose for a waiting here there's no purpose protein extra stress on the stack correct extra work on the stack I'm gonna let go through right as a task same thing up here I'm just returning this which is returning the whole task this is not a sink this is actually it's passing the task through asynchronously it's a little trick there to make life a little easier by doing one less a wait they don't need to do all right so now we have that let's again go to people data quick actions refactoring extract the interface for that so we have an interface called I people data and now with this we can come over to our startup and in here we can say services dot add transient for I sequel data access control dot to add our using statement add a reference to data access library and add these intimate and then say sequel data access is the type and then services dot add transient and this is I people data and that's going to be a people data object transient me if it's going to create an instance every time we ask for one singleton creates one instance for the entire application now I don't want to forget I often do I'm going to app settings JSON for my blaze or UI I'm gonna add a connection string here I often forget this connection strings plural inside here I say default and then in here what's my connection string well sequel server object Explorer person DB right click and go to properties and then the properties we have down here connection string double-click ctrl-c ctrl-v save you a lot of typing and a lot of guesswork as to what things are alright that's my connection string I am using integrated security equals true which means you can go ahead and copy it so you want it won't work on your machine unless you have the exact same spot and it would be your database not mine because it's using integrated security so just note that if you give us source code you may have to change this the connection is trained to be your database not mine okay so we have a connection string we have the mapped services that we need now let's create a page for our ours our people our inserting people okay now I could create the page right underneath pages I'm gonna create under a new folder and just to kind of demonstrate that this is totally different totally separate from the routing of this I'm gonna call this my pages now that's not a great name for a real data access but this is a demonstration just to show you that this this folder has no bearing on anything when it comes to Blaser pages so let's right-click on here and say add this one you get wrong at least once every time you bill its application for a while I do still and the reason why is because the first option is a razor page which my brain always associates with dot razor but that's not what a razor page is a razor page is a dot CSS HTML page with a page model behind it that's not we want instead we want new item and then in here you see the blazer symbol and it says raise or component which again confusing because you have a razor page razor view and rays are components but that's the one you want raise your component notice a dot razor as the extension in here let's give this a name of just people is fine add and so now you have this this page it's very very simple I'm going to add a few things to it first I might say that this is a page and that it's going to be slash let's call it slash data slash no notice that slash data slash my folder structure of my pages this is just to demonstrate that in fact this page path is totally separate from this folder path now best practice would be to name your folders after the paths and then put the items that are in that path in that location so if we rename this folder from my pages to data that would make sense but again this is a demo purpose just to show the disconnect here now I'm gonna add a few using statements here just to make sure I have everything I need first of all using I want to say data access library and then another using statement for data access library dot models and that's it for now I'll probably add another one soon and then I want to do I want to get access to my data access so @inject and I want a I people data I'll call it D be actually underscore Phoebe this is my database essentially now if I had one one i'ma call this people database or people data even but I call underscore DB just to be simple and it's kind of obvious I think so let's start off with a little bit of modification of the HTML let's say this is the people page that's an h1 tag and then it creates a h4 tag it's a little smaller I'm gonna say current people I'm gonna have that that if statement that says hey if if no people a list I don't have any people object yet so let's create one of the let's come down here and we're say private list of person model or I call this people I'm not gonna initialize it and instead I'm gonna come down here and say protected override and say the on initialized async now I hit tab it tabbed over again which frustrates me but a tab back if you hide more than one line and hit shift and hit tab it moves everything back one tab indent and if you hit tab it out dents it want everything 1 so just in case you didn't know that that right there now in here I'm gonna say people equals underscore DB dot get people now actually I want to say a weight and this should be async task so I'm gonna a weight the get people call now I get people is gonna call my sequel data access and do a select star from DB o dot people when it's done it's gonna map it over to my people and put it into this object so one of this page loads it fell load of people into this list alright that's in theory what's going to happen let's come up here and start writing code to that effect so adds if people is null then our paragraph tag and REM I'm still is right from the example loading don't like it I think it's simple clean easy and it works but the else statements we're gonna have our table and actually a class in here let's say class equals table and tabled striped those are bootstrap CSS commands that allow us to have a right table which is kinda nice I'm gonna have a header section TR and side here th let's have first name last name and email address there's my header row and now I'm going to have my body and then have my app for each and say for each person in people so I loop through all of my people in my private list and here I'm going to say each one gets a row and I'll have data of that row at person dot first name at person dot last name and at person dot email address there's a three entries are three properties for our person object let's see if just this works now this is again sequel data access but I do want to point out one more time this is talking to a class library this class library can talk to asp net core raiser pages or mbc they can talk to winforms WPF console applications xamarin projects it can talk to any of these so just note that this same data access it's identical data access will work with any of your c-sharp applications so don't think this is specific to blazer okay let's start this and let's see this page and echo up you know what it's gonna start but I'm not gonna see his page in action I don't have a link to it so the path is dia / people let's go to our shared and go nav menu I like this the nav me is on the side and it's totally separate from our rest of our application as far as it's not in main layout we just have as nav menu and the nav menu in here we can modify our navigation let's put after fetched it when I copy this whole thing paste it and I'm gonna say that instead of fetch data it's going to be slat arms let's say data slash people there you go which match is our data slash people route all right and let's not do oh I - list let's do control dot here oh I is it's a open source icon library and we're say there's a one for people so I use that for the icon instead it's a fetch data it's going to be people right now we can run this we can hack actually see an icon on our navigation as well so you've started up and now we have as people entry click on it and you suffer the briefest of seconds make it positive you can see it you saw the hey we're loading but now we have records from the database these are actual people from the real database go back and come over they're still there because every time it loads from the database but it's just getting back just the data it needs so it's a really efficient connection now I'm gonna take it up a notch let's close this out and you might say well how would you insert people in this this page or into this list and I am so glad you asked I'm going to show you how to do that let's start by creating in our blazer UI I'm gonna create a new folder and call it models notice I'm using the the model right from the data access library but now to create a new model and I'm gonna call this display person model and the reason why I want to add some UI specific code to my model so let's start with our person model I'm is gonna copy this for sake of time and I'll paste it in here I'm gonna add some stuff to this first required control dot add our using statement for system component model dot data annotations and then next I'm gonna say hey you know what a string length the max length a name should be is let's just say that a max name length is 15 that's way too short but I want to show you these error messages and then error message is going to be first name is too long I'm almost gonna say you know what let's have a min length as well min length is 5 again you shouldn't have a min length on a name or if you do is she one character maybe two but probably one and then the error message then I say one because there's the actor my a Q well Q would be her last name now that may be a stage name I'm not even sure but doesn't matter that would break your system so but this again is for demo purposes so first name is too long oops too short I was looking up top let's copy these three right here I'm gonna paste him on top of last name I'm gonna change everything here to say last name instead of first name for email address I'm not gonna write length I'm gonna say required but I am going to also say this is an email address which means it's gonna make sure that's formatted as an email address so this is a front-end model this is a model with specific error messaging for the front-end for the user to see and it's much more specific to display and validation and those type of things rather than what you might see for just data access so that's we're gonna have a separate model this is actually pretty common to have front-end models that are your display models and to have back-end models which your data models so just know that you will have some applications that do this can idea transfer from one model type to the other then we're gonna do a little bit of that here now that we have that done let's go back to our people page and add a using statement at using this is blazer demo you idot models it's gonna access that model without having a full path to it then down here our code we're at a new private variable private display person model recall this new person equals new display person model I'm gonna instantiate it right away okay note that I did not instantiate the list right away I did instantiate this new person right away next I come up here after the people page h1 tag but before the h4 tag for current people I'm gonna put a new age for tag and here I'm going to say insert new person so you're gonna be able to insert a new person above the list of the current people now forms are a bit different we're gonna open up a new tag called an edit form and edit form has a model that model is at new person all right that's the the instance we just created so right down here this display person model new person that's we're saying right here is the model for our and then on valid submit here's here's a tricky bit okay I said on I have on submit on valid some in on invalid submit be very careful you get the right one I only want the valid submit meaning that they have put in a proper first name last name an email address you could do more than one of these events and say for invalid submit do something different but you don't want to do that probably for the default case the most cases so make sure it's on valid submit now I will tell you that one of the the problems I had was it was never submitting right my form wasn't working right couldn't figure out what was going on turns out I had accidentally said on and saw valid submit up here and hit tab that's on invalid submit meaning only worked when the data was incorrect I was putting correct data in and not figure out why it didn't work nothing seemed to happen my code wasn't getting hit when I is only when I put in bad information that I found that my code was being hit so just note make sure you have the right one on valid submit and we're gonna say recreate a method down here let's create a method real quick where I say private void for right now insert person like so and then up here will say add insert person alright that's our method to call when a valid submit happens close our tanks and then in here we're going to say first of all data annotations validator that's gonna validate our data annotations what our data annotations well they're these things right here okay it's going to run those validations and then we're gonna have a validation summary at the top what's this this is a message it says hey this stuff's not valid what is it the cool thing is I don't have to do anything I can just say validation summary right there and it's gonna put those messages to the user in that spot without me having to format them or anything else it just happens now inputs text again a little different because this is a c-sharp form more than it is an HTML form every of this ID will say ID is first name and then at bind value so what's the value for this well it's going to be new person dot first name now this is a really simple little for I'm not gonna do anything complex like putting the labels on it and all the rest is really basic just enough to show you that this will work alright so last name and let's make sure that we change this to be last name it will change this to be email address and then down here we're gonna have a simple button that says well type equals submit and let's say the class equals BTN VT and - primary it sounds good and submit is fine alright very basic form not we're about the formatting of this I'm just gonna have a simple form so what is this form do let's come down here to our private void insert person I'm actually gonna change this to be private async task because I'm going to insert data in for our person at the weight that but first if I were to do that lets with you oh wait d underscore DB dot insert person passing the person model well how about new person no that's not gonna work okay it's got a red squiggly because cannot convert from display person model to person model these are different models so how I convert well I could use a tool like Auto mapper but in this case I'm gonna do it the manual a person model P equals new person model let me say first name equals new person dot first name last name equals new person dot last name and email address equals new person dot email address I said I call at the end and now I can insert P which is our mapped person now this only happens if this is a valid person so you have to worry about the information for our new person being correct it will be correct next after insert in the database I'm also going to say people which people is my list up here then display dot add P they're saying wait Tim why are you doing that why are you adding to the list directly the reason I'm doing that is because that list is not showing anything database specific it's not showing like the ID of the user or the date time that's inserted or anything else they be specific to what's in the database that I don't have when I created this person so I can kind of cheat this is not a bad cheat this is a good cheat and what I'm doing is I'm not doing a whole new call to the database and loading all the people again I'm just adding this person to the end if that didn't work for you you can just take this call right here this whole line copy it and overwrite this line right here with that line and it will update from the database after you've inserted the record so either way will work my way is just a little bit less work on the database side a little less data transfer across the wire and nobody gets hurt alright but now don't forget new person equals new display person model wiping out the information from the last insert okay with that being done hit save I think that's all we need to do to wire this up let's see it in action let's see therefore I intend to because yeah how it goes I usually forget something okay people there's first name last name and email address I told you wasn't pretty it's just basic stuff now if I said Tim and hit tab notice right away it says hey the first name is too short it puts a red outline around Tim okay well let's let's instead do something but look how about Tammy that's five letters cool now it's green how about Joan like that four letters nope last thing that's too short well over I said like this lots of characters now last name is too long notice it says change along just fine now I said test email address is not a valid email address okay so now I can change this to be Tammy and Joan's Dodds Co all right now it's valid I hit submit watch what happens after Bilbo there's Tammy right down the end okay it was immediate was quick and if I go off this page and come back to it Tammy still there because Tammy's in the database now not just inserted manually let's page unlike the counter which I have to go away and come back it's wiped out again and every time you fetch the data it's a little different okay like native 14 fetch it again and now it's 47 that's because these are all just dummy data it's been generated and wiped out this data is stored in the database so now you've seen how Blaser server-side can interact with actual real code that talks to a real database and does so in a really efficient manner where you have that nice client side interactivity where you see things pop in the page and the page doesn't have to reload the whole thing and it's not read downloading redrawing the entire page and you at the same time I ain't right ain't javascript code this is what Blazer really excels at is allowing us to stay in c-sharp writing our c-sharp code that we're good at and yet gives us that functionality that has been purely the domain of JavaScript okay so this is giving us kind of best of both worlds where your team can take the expertise it already has and reuse it in a client-side display manner in such a way that is much more interactive that the user wants without having to be much more expensive to in your team okay one things I hear a lot from brand new c shirt developers or CTO developers who are getting into web is I say okay well can you teach me angular or can you teach me react or can you teach me view or and the list goes on of these JavaScript front-end frameworks and what I typically push back on is do you know c-sharp yet because learning something like angular or view or react you have to learn JavaScript first and in depth you can't just say I'll learn the framework you have to learn the code that is the framework JavaScript and if you don't learn that be really in dangerous territory okay because it may work for a while and all sudden the magic breaks and you have no clue why and you're kind of a creek besides the fact that frameworks change a lot and so if you base your life on one specific framework that's gonna change if you don't understand the structure behind JavaScript and how it works and how to read way the new framework is working and how to keep up with that then you're gonna fall behind and you're actually be a worse place than you were to begin with so there's a lot to learn when you go down the JavaScript route I'm not saying don't go to a JavaScript route I've done it and I love JavaScript it's a great language for a lot of things but when your team is heavily invested in c-sharp and they don't have the skills necessarily to be also heavily invested in JavaScript then a blazer server-side is a great option because you can't necessarily have the full depth you want in both areas okay when you start getting really deep in a Java Script you'll probably lose some of your skills in c-sharp it just happens your brain is only so big maybe yours is bigger than mine I don't know but I have found personally that I forget how to do things in one way because I've been doing so long the other way and then it's this kind of context switch all the time between is this JavaScript and the way JavaScript does things or is this c-sharp and so things like blazer allow you to reproduce or remove that context switch now you can still use JavaScript in blazer so there is a shot today but there are ways to bring in JavaScript libraries and really do the same things you were doing before where you have mapping and all these other cool things that JavaScript can do and yet also mixing your c-sharp code so it's not like you're saying this is against JavaScript or this is the turnit if to JavaScript it is in a way but the same time it's not it's not a walled garden you can still bring JavaScript into this it's just it reduces the stress and the need to have JavaScript for sometimes what is really simple little pages like this this can do very complex things but often times I find that people spool up frameworks and tooling and all the rest just to have a simple set of pages so just note blazer server-side great option for things like this where it's simple it's easy I can put you know testing users test ads one two three dot-com and I hit submit my page refract doesn't have to refresh or redraw it's just there I can't even put sorts in here if I wanted to to sort these entries all without heading back to the the server and reload a whole new page but you at the same time I'm using c-sharp to do all this okay so this is a really a kind of game changer in our industry that allows us to be more efficient in our team training in our team development and in being able to do more things with c-sharp so that I'm going to wrap it up and I give you a source code the source code is in the description down below is a link to get that email it to you if you have any questions I'd love to hear them down the comments any thoughts on this you know way thing the pros and cons are what are the areas you're looking forward to doing this in just note we are gonna use this probably in the timko retail manager and we'll talk more about that next week I believe when we cover what's next for timko retail manager that's coming soon I think it's next week and we're gonna kind of go over there's a few more times in a few different ways so might even have a start to finish course that uses blazer as part or even hold the whole you interface for the applications so this there's a lot of different ways to use blaze you'll see coming down the road because this is a pretty important technology alright so thanks for watching leave the comments down below will you thought I appreciate a thumbs up as well if you enjoy the video as always I am Tim quarry [Music] you
Info
Channel: IAmTimCorey
Views: 157,455
Rating: 4.9450655 out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, course, training, how to, tim corey, C# course, C# training, C# tutorial, wpf, asp.net, .net core, Blazor, Blazor Server Side, Server Side Blazor, Client Side Blazor, Razor Pages, asp.net core, asp.net core 3.1, .net core 3.0, .net core 3.1, asp.net core 3.0, sql server
Id: 8DNgdphLvag
Channel Id: undefined
Length: 80min 30sec (4830 seconds)
Published: Mon Dec 30 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.