Blazor Web Apps - Goodbye JavaScript! I'm in love with C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] [Music] hi everybody and welcome to thismonths.net user group i'm going to be talking about blazer web apps and why we can pretty much say goodbye javascript now as a net developer i find there's a few pain points that we have to go through when setting up a new web application when it comes to frameworks like angular you know if you haven't used it before it's got a fairly steep learning curve and it's very opinionated so if you want to do something just a little bit different the framework just says no you can't do it you have to do it only the way that i say you can do it and sometimes that can be quite annoying with react for instance it's maybe a bit more flexible you can do different things but it doesn't come with everything that you need to build a full application like you do with with angular you have to start pulling in packages from other places to stitch together your full application now i find these javascript frameworks they rust pretty quickly what i mean is after i do npm install and my first production build it's just about time to update everything again because there's a brand new version available and javascript not everybody's favorite but you know it's dominated web development for about 20 25 years and you know for a long time now it's been sort of the only choice that we've had there is typescript it's a whole lot better you get a lot of similarities between typescript and c-sharp in fact it was written by the same person anders helzberg he wrote c sharp and typescript but we still find a lot of these weird javascript tricks around the place and it just doesn't sit well with some c sharp developers now it's also when we build our applications and we need to tie our back-end api to the front end we need to translate our c-sharp classes our models into typescript interfaces just so we can serialize them send them across the wire and deserialize it on the other end in a different language totally different language i find that's a lot of effort for something that should be fairly trivial there has to be a better way then to debug our applications using visual studio visual studio code you can debug the backend api um and then when it comes to the ui i have to use the browser and jumping backwards and forwards between the different tools to debug my application it does get a little bit annoying and i hope there is a better way first a little bit about myself my name is william liebenberg i'm a solution architect at ssw and you can find me on twitter i have a blog site called azure gems and you can also find me on linkedin so i started programming when i was about five years old and when i mean programming i mean uh copying text from my dad's programming book and typing into the computer and seeing something happen on the screen it's very exciting i had no idea what it actually meant but it was cool now my first computer was a spectra video 328 it had a massive eight kilobytes of memory and i could load games and other little programs from cassette tapes so this is long before um cd-roms and the internet was out so this is what we had you know this is sort of like my xbox and my little programming computer everything all in one really really enjoyed it so then many years later i i moved over to develop professionally using c and c plus plus and i spent a bit of time writing games and graphic engines um and then you know this is also when our ides were fairly low res compared to today's standards but you know we felt like we could rule the world with our source code and the applications that we're writing back then and then along came.net i started with net version two i skipped version one because i thought what's this crazy new technology uh it's not gonna last but hey look many years later we've still got net and we love it and i fell in love with azure around 2014 and not a day goes by now that i don't do something azure related in my day-to-day job it's definitely got something for everyone so if you haven't used it before just go check it out so today's agenda i want to dive straight in i want to show you how easy it is to build a blazer web application in five minutes then i want to cover just a little bit of history to sort of explain why we have blazer it's very very interesting and then i want to convince you about why you need to use blazer in fact you know i'm just going to say you have to use blazer it's awesome then we'll look at how to use blazer in the enterprise when you talk about enterprise you can almost not talk about clean architecture they go hand in hand so we'll see how we can use blazer in the real world and then also then just see how we take our blazer application and and run that or host that in the cloud what are our options so to get started we can open up visual studio go file a new project and choose blazer application or we can go and use vs code and just use net command line interface to spin up a brand new blazer webassembly application i'm going to do that right now i'm just going to go over to my console and go net new blazer wasm webassembly um i just need to give this a name so i'll give it laser dot net user group yep that should work so this is going to spin up a standard template or standard project it's gonna you see restore a couple of little uh nugets for us and in a moment that should be done and yep now i can open up vs code so let's go to blazer net user group and open that up all right okay here we go here's our application i'm just going to give this code a moment to load itself it's got to prepare a few things might show a couple of pop-ups for us but let's look at what we have in our application so like all good programs we have a main method and basically only four lines to get a blazer webassembly application up and running we've got a webassembly host builder we're adding some adding a root component called app and we're sort of identifying it with another app tag and as a text value and then here's something familiar um add scoped so this is dependency injection so we're adding some pre-configured services into our application builder so this is a http client that's pre-configured to point to our base address and that's it then we'll have everything we need to start running our application this is just asking me if i can want all the debugging assets i'll say yes please give me that stuff all right and while it's doing that very familiar cs project you can see that this is dotted standard 2.1 there's a bunch of webassembly nuget packages being brought in and a new http json package so this is the http client that runs in a browser and underneath that it uses the the fetch api to make our web requests for us and finally we see here they've got their razer language version version three so blazer uses razer for its markup language so they took the words browser and razer put them together and we came up with blazer true story so we saw earlier that there's this app component and here it is so this has got the main router for our application so any component or any route that we give to our application this will resolve that and figure out where to go and what to display so if there is something that is found a a route that resolves into an actual component use this main layout type to display our components now if there's anything that's not found so you know we typed in a weird routing to our application it would say sorry there's nothing at this address nice and simple in this in this class or in this component sorry we will be adding a whole bunch of other stuff you know we can add our authentication checks whether they are logged in or not logged in and we can redirect them to the right place and there's online offline mode for instance if we're dealing with progressive web apps but yeah so this is a very important file as we add quite a lot of overall cross-cutting concerns into our application right here we also have this underscore imports file and this is interesting because we can bring in by adding a using statement um an entire component library so we can reuse those components in our razer files without having to again add a using to our files now this only applies to the razer markup files as we'll see shortly you don't you still have to use your normal using statements when you're writing a plain c-sharp class and again to hear something very familiar a www root we have an index.html file and we see here it brings bootstrap in by default just all the bootstrap css i've got some custom application styling and here's our app component that's being rendered inside of the html index html and so this is this is where um once that component is loaded it's going to replace this with whatever is resolves out of that whatever route we give it it's all going to render in here so we'll replace this with our our ui code and very importantly what makes all of this possible is the blazer webassembly uh javascript runtime framework so you know this this lets us essentially load the dotnet uh webassembly runtime and then we can run all our custom c sharp code all the dlls that we give it just standard uh c sharp or dot net standard 2.1 dlls and they're running the browser it's going to be very exciting um so something else let's see we've got a a a nav menu and there's a main layout so we see here it's a sidebar with our nav menu and um here's a special sort of body render fragment so we can see that this is a layout file so when when the router resolves an address for us it's going to know which component or which page you want to render and we're going to take all that content and render it in this render fragment called body so now i've mentioned the nav menu we'll be looking at this a little bit later as well we're going to add a couple of links but we can see here that there's a link to a page called counter with a href of counter same with fetch data so we'll look at this so here in pages we've got a counter component counter dot raiser you can see here's got an at page directive with slash counter so that's a route to get to this component and we can see that there's a it's printing out a current value there's a button with an on click event that says increment count and if f12 into that intellisense works hey um we get to this method that increments the count by one every time we click on it so this is normal c sharp code um it's just sort of tucked into this little at code directive uh on this component the razer component and um then you know fetch data it's a bit more of a complicated thing shows us a table renders a data by looking through a list of forecasts and as we can see here that when the component is initialized it loads some data from currently just a uh a json file but we can't actually call any sort of http endpoint to obtain information and inside of our code there's a sort of nested class called weather forecast so that's a concrete type of what we're going to use to display this information all right so we should have everything we need now if we go and press f5 application should just run and [Music] here we go so it's got the browser open when the first time you run this it does take a moment for a whole few things to to download and when it's done voila here we have a blazer single page application we've got the homepage got our counter page that we saw before this is what it actually looks like when we click on the button we can see the numbers increasing and we have the fetch data page cool so very simple application it's got a couple of things in it um and what else can we look at so um if we open up the dev tools i can straight away see there's a little blazer highlight here that says it loaded six megabytes worth of resources which is quite a bit and if we if we dig into that we can see here that it's downloading components.forms or dlls actual net dlls microsoft extensions and components and system.drawing there's quite a lot of stuff in here but what is but different here is this is net.wasm or webassembly you can see it's about 780 kilobytes in size so this is the net runtime that's been compiled into webassembly as a minified code that is responsible for able to take a normal.net dll and run it in the browser you know it's yeah certainly amazing we're going to see how we can use a lot of our favorite packages even packages that existed before blazer can even run them in the browser right now we also see there's this cool little uh debugging hotkey shift alt plus d all right so let's try that out shift alt d and okay so what have we got here it says it can't find a debuggable browser tab but it gives us a hint there's a command that we can run from there if you go windows plus r so you can run this command that will open up a new chrome or you can even use edge obviously that has a remote debugging enabled so if we just run that cool we get a second instance of chrome so don't close the one behind it if you do it stops everything um and then again we just try that hotkey that opens up devtools but a slightly different version of devtools because if we go and look at the sources tab something very special now we actually see all the c-sharp code for our application in the browser that's interesting you know here's our nav menu it's all the markup here's some c sharp code uh here's the code for our counter that's pretty cool and look at that we can set a breakpoint so when i when i go to my application i'm going to go to the counter and i'm going to click the button and look at that it's stopped on this line and what we can see here some interesting stuff we've got the call stack and we've got all our locals here if we expand that you see the current count is zero so let's just make it go one line further and go continue now the current count is one awesome cool and it's reflected here it's one so if you try that again again break one's hit see the current value is one move over one line now it's two so awesome we can actually debug a dot net the c sharp.net application running in the browser with all the c sharp code available in the browser that in the devtools is really cool really really cool um it's definitely going to solve a lot of my pain when i want to build my applications now let's just undo these and make that continue running and uh yeah the same for all the other components so it's all there all very cool if we can dig a bit deeper into seeing you know what is really uh there here's all the dlls and the sizes and things that we saw from before um you can see there's quite a lot that goes into running a blazer web assembly application in the browser but when we publish our application you know for uh for release it's a lot smaller so all the unnecessary coders are stripped away and sort of just the bits of the framework that you need are then bundled into your uh application cool so um i'm i'm gonna close these for now i'm gonna go back to visual studio code and let's see what else we can do all right um so what use is a component if you can't reuse it so you see we've got this counter one here and it's got a route called slash counter and from our nav menu that's where it goes okay so it goes to the counter route but what we could do just sort of just to prove a point we're going to our main page here we can delete that for a second and we can then go and add counter we can see already it's discovered our counter with intellisense so and the code completes working cool all right so our counter is there now i'm just going to build my application i'm just going to start this up in a slightly different way because um you know what this does i'm going to do netwatch build and as soon as i make um sort of code changes it's going to watch for any changes and it's going to rebuild my application and all i need to do then is just refresh the page in the browser it's not quite the same as the live hot reload that we have with react and angular but it's sort of halfway there the live hot reload for blazer webassembly is coming in a future.net version so that's very exciting okay that's built i'm going to press f5 and just launch the application again and now here on our hello world page we have the very same component and it works in exactly the same way very cool very cool all right very nice so uh i can close that and i want to show one more thing so we can actually this uh code that we have here we can also debug it in visual studio in visual studio code so i'm just going to set that breakpoint here so the bright red means it's going to work and if we launch the application and so we set it on the uh the counter increment so i'm going to hit that button visual studio code should highlight for me there we go we can see here i'm just going to open up the debugging tools and i'm just going to close all that make it a bit bigger so now we can see we're broke on this line we've got the current count and just like before if we just put a break button on the next line continue and we can see that should have gone up to one cool so very much exactly the same debugging experience we can actually debug the whole application uh in videos code or in the browser you don't have to keep jumping between the two you can stay in one place if you really wanted to and here we go it hits it again cool all right let's let's let continue okay so it's very easy to see that in debugger applications it's easy to add components and um you know we'll just look at a hint of the routing and how to add links to our pages so i'm going to go back to the slide so that's how we build a blazer webassembly application in about five minutes nice and easy you can do it with visual studio or with visual studio code and the net command line all right so next we're looking at a little bit of history how did we end up with blazer why why is it there so it all started with net framework version one in 2002 this is exciting you know like i said it came out i didn't think it was going to be a uh you know an amazing technology but sure enough many years later we're still using.net.net core and it's it's definitely my favorite then silverlight came out in about 2006 and that was a a plug-in for the browsers where we could write some c sharp applications and the silverlight plugin would then run that for us in the browser so that's pretty cool um you know net in a browser uh it's amazing but then jquery also came around at the same time and then something interesting happened after this apple released their iphones and then also the android phones came out and the html5 spec was basically finalized and now it meant that everyone with a phone in the hand basically also had a browser with them but the twist is that the iphones just refuse to run any plugins in their browsers now you couldn't load silverlight as a plugin to the browser so we couldn't run any of that.net code on the phones um and now then with html5 being finalized and then also angularjs came out it kind of meant that everyone was sort of able to use this new uh awesome web pages written in angularjs and similar frameworks on their phones on their laptops or desktops and but you couldn't use silverlight in any of the scenarios and basically then in 2011 with silverlight version 5 that was the last version and rest in peace no more silverlight and no more c-sharp code in the browser then yeah react very popular it came out 2013 the very first version and it came out the same time as assembly.js now assembly.js was pretty neat because you can take c or c plus code and run it through a particular tool chain which let you then run that c or c plus plus code in a browser so it takes that code and compiles it into byte code that the sort of optimized native javascript runs in the browser and pretty much at near native speeds so it's really fast in fact it's so fast that they took the unreal four gaming engine ported that to asm dot js and ran it into browser it's really really cool and then we've got net core a couple of years later 2016. very cool and webassembly not long after that so webassembly is a little bit different um now it opens the gate to not just sort of c or c plus plus but uh other languages f sharp and um ruby or rust and you know there's there's now uh the ability for every type of language to run their code in the browser and all the browsers then also supported webassembly so safari edge firefox and chrome all run webassembly and then blazer got announced by mr blazer himself steve sanderson just as an experiment um to see you know can we take c-sharp and compile it down with webassembly so we can run it in in the browser and uh you know so this was just an experiment it was very exciting um and about two years later uh dan roth announced that blazer is an actual preview microsoft's going to give us a good crack and see how it goes and so that was in april 2019 and very shortly after they said hey look blazer server we're going to support it now with.net core three and so we've had blazer for a little while but in in blazer server it's a little bit different to blazer web assembly but blazer webassembly it was around but then was actually officially released uh in may this year with dot net core 3.1 so we now have blazer webassembly and uh it's it's pretty damn exciting i quite like it a little bit into the future we're going to have blazer lts so when things become long-term support so with net 6 it means that blazer is actually going to be around for a long long time so now like i said blazers are awesome and you really need to use it i'm going to show you why i'll give you one very good reason why that is because we can write our c-sharp code in the browser and you know for me that's almost just enough to convince me to jump in right now and start using it but i'll give you a few more reasons there's no plugins required whatsoever it's not silverlight blazer is definitely 100 not silverlight it's very different uh it just our code runs directly in the browser without any plugins it's a fully net based single page application framework that we can use to write yeah applications very much that we're used to with angular and react but with less pain and something that's very familiar to a lot of net developers would be the razer templating engine so if you have an experience from the mvc uh error area you can then use razer with blazer to then you know write client-side applications so there's no more server-side rendering but client-side it's pretty cool and you can add all your own very your very own c sharp code that runs alongside your razer templates in the browser so we get a full.net text stacks and all the very much familiar tooling that we've always been we've been using and one really cool thing is that we can share code between the server and the client so we don't have to take our server-side models and translate them into typescript interfaces we can just literally take the same code from the server and run it in the client and there's no more headaches and we actually get to use all of the existing.net nuget packages as long as it's net standard 2.1 so all our favorite stuff like siri log and mediator uh fluent validation all of those libraries we can take them you know from writing our backend applications and actually use them in front-end application really cool and blazer is built to be stable for many many years so once we hit lts it's there for good uh it's definitely going to be a long-term technology and it's it's not like the rusty technologies from the javascript world don't change so often i think blaze is going to be stable and they'll be supported for many years okay so webassembly or wasm for short it's a standard web technology that is now you know supported by the major browsers for a few years now since 2017 um and it takes our code and compiles it right down to bytecode and we transmit that in as binary whereas with javascript it's all sort of minified down in but it's still text so it is transferred as text it can't get any smaller than that so you know a the same sort of webassembly application will be a lot smaller than a javascript application once it's compiled and the benefit is that they run at very near native speeds so it definitely can get a speed boost from running a webassembly application and webassembly still has the same security sandbox that we're used to with javascript so when you're running code on the client side you can't dig into the the windows registry or mess with files on that computer whatsoever this is not allowed and we're used to that with normal javascript applications so and this is no different but we don't have to use just c sharp there's other languages so f sharp python rust or and c c plus plus all of them are supported by webassembly so you can write code in those languages and then run it in the browser it's really cool so which flavor of blazer do we need to choose on the one side we've got blazer webassembly and all the logic that we write is executed on the client so we offload that compute from the server to the client yeah some really good benefits in doing that and we can see in the diagram here that we've got our.net code and our razor components running on top of webassembly and with all the user interactions it directly sort of updates or incrementally updates the dom for us based on those interactions so it's nice and fast it's very similar to how angular react and view work so single page applications and they have all got their own ways of manipulating the dom but essentially it's the same thing clients hide logic with blazer server the story is a bit different all the the logic is executed on the server and all the rendering is done on the server and it just transmits the the dom update to the front end application uh using signal r and it's got some ups and downs with that but so for me the downside is the further away from the server your client is then you start introducing latency which you know if you have a sluggish web application it definitely doesn't give a good user experience so the pros and cons about blazer server there are definitely some pros to blazer server because there's no initial download size so you see with the blazer web assembly application from earlier downloaded a whole lot of dlls and there's a minimum download payload size of about 700 800k for the net runtime so you don't have that with the server side flavor of blazer because it's the rendering's done on the server it basically just spits html out to the browser and it renders it so it's fast to load you can run it on pretty much any browser from any era you don't need any modern browsers so you don't need to have one that supports web assembly and one of the other benefits is that all of your code all your business logic stays on the server it's private um you know it's definitely no way of linking that out to the client whatsoever and you have the freedom of much bigger security sandbox where you can work on files on the server you have pretty much got bare metal access to to that hardware the downsides is like i mentioned the latency signalr for each user interaction you know that communication overhead can build up especially over long distances and we also then have the responsibility of making sure that those connections uh remain uh active so if the client connection is dropped essentially the client applications there that doesn't it can't do anything can't react to anything it can't receive updates and can't send updates so you know definitely have to do that ourselves which is a bit of a pain and you know we have to maintain the client's state on the server so it has the copy of the dom for each client and that can lead to some fairly big amounts of memory being used up um so it's a heavy application it's a heavy framework and it means it might not be able to scale as big as uh what we'd like and certainly like i said there's no offline support once that connection's dropped that's it your client applications can't function so now let's look at the the pros and cons of blazer webassembly assembly again it's a bit different to blazer server in fact the difference is that we can run our.net code in the browser so it's not server side it's all client-side and running at native speeds we can share our code we don't have to translate anything from c sharp into another weird language it's plain c sharp there's no dependency on the server-side technology so even though we'd like to use an asp.net core back-end it doesn't matter you don't need to use that can be completely standalone on its own an application running in a browser or it can be a standalone application with a node.js back-end um you're not tied to any back-end technology whatsoever and these applications can scale because it's a static website you can put that on the cdn and get that much closer to your users than you can with you know a big clunky server and it's just nice and easy and then pwas progressive web apps they're also supported with blazer web assembly and what that means is we can have offline support um and you know we can install the application as an icon on the home screen on the phones or on the desktop on their computers and yeah a lot of the cool things that we'd like for cloud applications the downsides is it does have initial download size you know at least 700 kilobytes plus all the additional application dlls that we want to use we do need a modern browser so you have to support webassembly in that browser we're limited to the browser sandbox but you know we're used to that already so it's not really a major issue the tooling for blazer web assembly still needs to mature just a little bit sometimes the intellisense just seems to stop working and you have to close everything down and start back up but it's not a major problem not really and we're missing the live hot reload so this is great for productivity so even though we don't have it now it's coming but at the moment the alternative is we have sort of got auto rebuild uh the only difference is we have to press f5 in the browser to get the updates it's not going to automatically do that for us but like i said it's coming so which one should we choose we've got blazer web assembly which is sort of the lighter sorbet flavor or blazer serve which is a heavy chocolate ice cream with extra cream and a cherry on top for me i'm going to choose blazer web assembly i like the the lightness and the simplicity of it i basically can focus on just writing a single page application i don't have to worry about managing so much client state and everything else so i'm going to go with blazer webassembly so you're thinking already get to the code all right so let's look at some component anatomy this is the basic layout of a component we start off at the top with the directives this is where we say um use add page to give the the component an address so we can route to it we bring in any sort of other component libraries or class libraries that we want to use with the using statements and we can then inject services using the at inject directive now there are a few more for instance we can say which layout we want to use for this file etc then in the middle we have our markup code html markup and some razer code which allows us to just decide what we want to display and when we want to display it based on some conditions so we've got some nice flexibility in the rendering there and then finally we've got the code so the atco directive can take in a block of c sharp code and it is pretty awesome so that's the basic layout of a component and this is as simple as a component gets what we have is just a heading and a paragraph with a message that is bound to the message string inside of our code so when the page loads it's going to read the value from message and displayed on the screen now the difference between a component and a page is just by us adding the at page directive and giving it an address that's the only difference but what is really cool is let's say we've refactored our components a bit but you know there's a route out there that people might link to for an old component that we've replaced so we can actually give a one of our pages or one of our components multiple addresses so you can actually have a second one a completely different name but it'll still route to this component so it's pretty nice some people like to take their razor files and split them up so we have on the one side on the right hand side have just the view or the markup code and on the left we've got the code behind the c-sharp now the way that we actually have to make this work is first of all we always have to bring in the components of the asp.net core component using a using statement and then we can make our class a partial class for this component and the names for the component and the razer.cs and the razer file that will have to match that is the way that then the compiler will pick up all the relevant files and stitch them together so just like all the other frameworks our components they have life cycles they have a lot of methods that we can use to react to things happening to our components and we can decide when to load data or when and when not to render the component and what to do once it's rendered already so there's a lot of options here and you can build some really complicated components and build some really rich uis data binding very important so in this example we have a one-way data binding just with a single at symbol to the title field in our code section so see making sure that the names match so when the page gets rendered it'll render that title field now what we'll have next is a two-way binding we've got an input text box and we've bound the value of that text box to our title property or the title field but the the default event take place is the on change event which means once we've tabbed out of the input box or once it loses focus that's when it will update the title value but you know that's a bit clunky sometimes and what we want is to be able to update the title as soon as we type so for each keystroke we want to update the title and again we can do that with data binding a two-way data bind we start off add bind to the title and then we can specify which event we want to bind on by using the this colon notation here to specify the on input event so now each character that gets input into the input box will straight away update the title value pretty nice so parameters um what we do with parameters is that we can give an optional parameter to our component via the route or the page directive and we can see here the text route or text parameter sorry is bound to the text field and it must have a parameter attribute it's the only way that they can be linked together and we can see there in the on initialize method we can see because it's an optional parameter we're saying hey is this text null if not use that text otherwise just replace it with the default value so if no one gave this component any optional text it's going to say blazer is awesome otherwise it's going to render whatever it gives the user gives us and then we bind that to the at text field there in the uh in the view we can add some constraints to our parameters um in the previous example we just had a plain text field but now we can actually make sure that for this id that we're expecting we're going to make sure that it's an integer so we can specify the type on our route as well and we see here then again it's a parameter we have to have the parameter attribute for this id but now it's guaranteed that this will always be an integer and we can databind to it and it'll display the correct value we can also use a whole bunch of other types not just text or string and integers we can use daytime gurus longs booleans you know all the reference types are there we can use them in our constraints uh handling events so if we've written a component that you know allows us to react to uh an event inside of it so in this instance we've got a product title printer that gives us an on-click um callback that says um once once this on click is fired i want you or you can at least call whatever method you want so in this case i've got a method called clicked it and it receives a string value for that product you can discover that the intellisense just shows you what it is it's nice and easy you don't have to go and dig through the code to find out what the method signature is um and then yes we're just going to print out the product name of what was clicked on so this is then what that product title printer component looks like we have a couple of spans that shows the title and the description and then a button that when the button is clicked with the on click event handler we then invoke our on click event callback and we pass in the title property to that callback which is then received by the calling component and that's it so that we have bound a method from a calling component to the event inside of a component nice and easy very important we've talked about routes before and now we're talking about navigation so how do we go from one page to another page we do that by injecting the navigation manager and what we do is so in this example we've got a button once we click on this button we're going to call the navigate to where the page method and that method it uses the navigation manager and there's a navigate to method there and we just give it a component or page name and straight away it routes our users to that component pretty simple now dependency injection very important this is where we can take care of setting up all our services that we want to use in our application so they're pre-configured ready to go as soon as our components receive them they can just start using them so they don't need to know about the particular config or in this case the the address for the http client that's all taken care of out of the way we just get to use it so in our component we have to inject services using the at inject directive we give it the type in this case http client and then we'll give it a variable name http and then we can go and use it and in this case it's just calling a rest endpoint to get some weather forecast information cool but things are a bit different when we work with the code behind approach we don't see the at inject directive anywhere now what we have to do like all code behinds you have to bring in the asp.net core components namespace and then to inject the service we have to do it via parameter injection we use the inject attribute on our service in this case the again the http client and you'll notice there's no constructor injection there's only parameter based injection but for our normal c-sharp classes or services that we write inside of our blazer webassembly application there you can use your familiar constructor injection it's only for the razor component that you have to use the inject attribute and then you know it's available and ready to use just like normal now logging very easy we can just use console.writeline and it certainly works that's very very easy but it's also very boring i think we can do something a bit better with logging so out of the box for blazer webassembly you know this asp.net core is available we can use the i logger all we need to do is we can set up the logging level that we want to blog at so we can make it more noisy or less noisy depending on what we're trying to do and we inject an io logger for our component into our component and then we just use it logger dot log warning and does the job nice and simple but we can do one better we can have to use serialog for logging in the browser pretty cool right so i'm going to show you how to do that i'm going to go back to vs code and i'm going to go and add a new page so this is our nav menu where we were before excuse me and i'm going to add a new page but um before i need to do that i'm going to bring in a couple of new get packages just open up a new terminal here dot net add package siri log all right so that's just going to download serial up for me cool done i'm going to add another one so it's just a special uh so cereal is all about syncs so i'm going to add in a serialog syncs dot browser browser console and this is a pre-release let me just make that a bit clearer so this is a pre-release nougat package so you have to specify that exact version so it's uh you see it's a version one zero zero dash dev dash zero zero one two all right i memorized this one by the way took a while okay so that's in now so we can just confirm that we'll look at our cs project file and close this and we can see hey cool we have a couple of new package references all right so back to the nav menu i'm going to grab some code that i'm prepared i'm going to put that in here so essentially we're going to have a new new link on the side menu we can see here that the href is logging and the title for this link is login so we need to go and add a new logging dot raiser file and all the razer files should start with a capital letter that's in the documentation it is absolutely required now what we need to do very first is to give our login page a route i'm going to call this slash logging so this is what we put in the href for our nav menu next up i'm going to bring in serialog cool and i'm just going to add the um at code section so what we can do now i want to add a couple of buttons that i can click on to log messages i'm just going to put them here they've got three buttons to log a message a warning and an error we need some code to do that so what do we do so we've got the three buttons and they all have an on click event to a method and here are all those methods just nice and simple log information log warning log error okay so my build should be running yep so it did save everything and then rebuild it so and applications running so i can just tab back to my application hit f5 to refresh now we see we've got a logging page and oh sorry nothing at this address what did i do so we got logging then i must type logging let's have a look um login logging and where's my nav menu logging what happened what happened l o g g ing all right should be all right let's double check let's reload this application ah there we go now we've got three buttons log with serial log and log warning and log error so i'm going to open up the dev tools again so this is where we should see our messages click here no okay i must have a little error in my compilation what did i do no that's calling the right methods uh let's see mr demo you need to work oh i know exactly what the problem is we forgot to set up serilog here we go so right at the beginning of our application we actually have to set up serilog so let me just grab that little bit of code here we go so this might look familiar so we just want to create a logger with new log configuration on to the minimum level of debug we're going to write to the browser console that we brought in and we'll just say create logger now it's got the red squigglies so if we control dot using serial log cool so now our application should rebuild in the background refresh that give it a second here's our application and now oh look at that it's working hey we're using serial log in the browser i needed this button a moment ago but yeah that's exciting serial lock in the browser now why why is serialog so special for us which it's just console logging at the moment but serialog's got the ability to add multiple syncs so we can actually send our logs back to the server or back to some other log ingestion service that we can then use to analyze the client-side logs and you know improve the application over time so definitely a whole lot better than console.writeline and you know this is something that existed long before blazer did and you know now we're running it in the in the code in the browser very exciting so you can check out nicholas bloomheart's page here about sierra log and blazer and show you some really cool examples of how to set up logging to a remote service give it a go very cool so moving on next we have forms and validation so we have edit forms so the built-in controls in blazer that gives us a few callbacks so for instance in this case we've got a we can specify our model first to say you know this is the model in our code block that we're trying to bind to so any change or any information added into the form is persisted in this model but it'll only happen if it's all validated and once it's validated we can call it a validate handleval valid submit method okay try and say that fast three times um so like i said here's the model and we can add a data annotations validator so we want to guarantee that the information being added into this form is in some sort of correct shape emits some minimum requirements and if they don't then we can render that summary here at the bottom using a validation summary component so the way that we decorate our components sorry our classes is just with these data annotations so make sure that the field is required and say that the string length is you know no longer than 16 and if it is longer than 16 we can then give it a custom error message okay so i'm going to show you how to do that real quick so if we go back to our application we go back to vs code and let's see i want to first off i can bring in a new file i'm just going to add a new razor component and i'm going to call this edit forms dot raiser and we're going to give this a page directive of edit forms all right now what i want to do is i also just want to paste in my form so i've got one prepared from the slides put that in here and exactly all we saw before when i have the model to our blog post which we'll add in a second we've got handle value submit method which is going to live in the code section i'll bring that in as well here we go so on the valid submit we'll get the blog post model and it's going to just print out some of the values that we've entered into the form so that doesn't exist yet so let's go and add that class i'm just going to add it right at the root level of this application so blog post dot cs okay so the code for this nice and simple we actually still have to just bring in um make sure we're doing everything in the right name space and there we go says blazer net user group here's my class just format that i've got some red squiggles to bring in the data annotations name space and that should be it okay cool now finally i want to add a link to our forms validation page look you see on the c-sharp programmer everything starts with squiggly brackets uh let's format that a little bit better so we can see it's called edit forms and just be very sure that they actually these things are case sensitive so let me just fix that up that should be lowercase or lowercase fantastic all right so we save that we go back to our blazer application i refresh the page here we go forms and validation cool and here's our edit form you see if we go straight away click publish you see here's the uh the validations that have failed excuse me um and those are rendered in that validation summary um block at the end bottom of our form you see everything that is invalid has a red highlight over it so let's just add something for the title click publish and yep it's gone away add something in there so on change it revalidates everything and so for instance here let's just put something that's nice and long see if it complains yep slug is too long cool so and then if we click the publish button nothing's happening so if we just make sure that everything validates it's still too long let's put something in there all right let's click publish and then here we've got a valid submission and the information we've typed into the form is displayed in the dev tools in the console very cool but i have a problem with this i'm not a big fan of these data annotations so i'm just going to delete them i don't like them i don't like decorating my my entities with these things it just ties me to something that you know if i want to refactor my application you know i definitely have to either take it away or bring it with me so i'd rather not bring with me at all i want to use something a little bit cooler so i'm going to open up the terminal i'm going to add a new package and this is the blazered fluent validation nuget package fluent validation spell that correctly yeah and what this lets us do is we can actually uh hang on what did i do uh did it to do do i type that correctly and add blazard sorry it's a different thing altogether there you go blazer dot fluent validation excellent there we go all right so i can close that don't need this anymore we don't have to do anything to our um blog post at all we just need to add a new file and this is actually added in the same file we'd need to actually add the validator for this model i'll show you how that's done like this so we've got a blog post validator it's an abstract validator for that blog post i'm just going to add the using get rid of all the red squiggles and here in the constructor we can specify all the rules that our blog post needs to follow for it to be valid so the title must not be empty the slug also must not be empty but we want to restrict the length a minimum of three characters and a maximum of 16 and content not empty cool all right then in our edit forms page what we can do instead of using this data annotations evaluator we can i'm going to comment that out for now and what we can do is use the um fluent validation validate let me just shorten that a little bit let's see we can go and take all that stuff out and then add the using to the top of our file you can see here now we have a using for fluent validation that's it so we can use the same validation summary but the actual validator is going to use a fluent validator all right so that should have built by now i'm going to refresh the page and now straight away i'm going to click publish all right same validation messages here they must not be empty so i'm just going to add something in here and we can see now oh it's already got a really cool validation error message i didn't have to add that myself fluent validation worked out for me it even says how many characters that i actually entered cool all right so here we go all the other ones so we can make sure that there's something in there past that validation and click publish and there we go our information shows up in console so now we've got edit forms and fluent validation much much nicer what do you think about that so okay warning incoming javascript so even though you know blazers all c sharp and dot net we can still run javascript in our applications let me show you how [Music] all we need to do to run javascript is to bring in the javascript runtime in this example i've got a button that calls my paul js method that's in my code section and then on the right hand side you'll see here i've got in the index file a a global method reply to.net that says i love you blazer so as soon as my users clicks this button it'll invoke the reply to.net function and return a string value we're going to bind that to the js text value which we're displaying in the markup here so pretty cool you can still run javascript in blazer and what it actually means is that we can still bring in npm packages into our blazer webassembly application and then wrap them up into a blazer component so we can reuse that really rich npm ecosystem out there as well as our nougat ecosystem so we actually have the sort of the best of both worlds which is really cool so yeah definitely you can run javascript in the browser still with webassembly blazer and net everything everything's working together very nicely everyone's friends and yeah cool so you're probably thinking i need to show you something really really awesome and i'm going to show you how to build a markdown editor very very quickly and i'm not going to give away the code hints first but let's just do this here so what we want to do is again i'm going to bring in another couple of packages so uh this one's called markdig this has been around for many years and it's a very popular library that people use to take markdown files and render that into html i'm going to add one more one more package this one's called markdig.syntax highlighting yeah what this allows us to do is if we have some a a code block in in markdown so c sharp or powershell or whatever we want to use then the markdown is going to add some syntax highlighting to our rendered output so it's pretty cool all right so those have been added don't need that anymore so just to get to our page i need to add one more nav link so let's see what we've got here paste that in fix the formatting uh so this is going to be editor i'm just going to rename that to markdown editor then i need to before i forget go and initialize the markdown pipeline and the way we do that is we've got the code here so we just want to inject uh set up the dependency injection for the markdown pipeline bring in the using statement there we go so we've created a markdown pipeline builder we're going to use the advanced extensions so we can render lists and all sorts of things and tables and also want to bring in the name space for the syntax highlighting extension and i'm just going to build this pipeline and register that as a singleton so that means if we have a razor component i'm just going to call that editor dot razer because that's the route that we want to give it editor that's what we specified in the nav menu file so i'm just going to add the add code section and what i want to do is i want to have a text area on the left where i type in my markdown my raw markdown and then on the right hand side is when i want to show the rendered version so the way that we need to do that is also we have to bring in the um like sorry inject the markdown pipeline mark down i'm gonna have to add the using first okay then i can inject the markdown pipeline and we're just going to call it pipeline pipeline there we go um now i know i'm also actually going to use serialog let's arrange that a bit nicer here we go okay so i've got some code pre-prepared and let me just grab that and put that in here for you all right like i said here's a text area on the left and we want to have some of our rendered code on the right hand side so i haven't added the c sharp code yet but i've got two fields i want to bind to one's called markdown text the other one's called preview now uh in in the code section uh i'll bring this bring this code in for you all right okay let's just format that all okay so just to make it clear i've got a text area and then i'm databinding the markdown text field towards and i'm making sure that i'm binding to the on input event so as soon as i hit a keystroke it binds to my markdown text string and updates the view and i just got to fix the typo here i'll just call this html to render that's what i actually want to render so the way that this works is that i call the markdown pipeline sorry the markdown uh static helper to html i'll give it the markdown text if there's no text in there just make sure that it's an empty string because it doesn't like nulls and we just give it the pipeline that we set up and inject it into this component now i know because there's a small little bug that happens when you have a certain bit of bad markdown and it just throws a null reference exception and we're logging that as well so we'll see what happens and so that is all we need that is going to give us a markdown editor in the browser let's see so i'm going to go back to the browser i'm going to refresh my application and let's see all right we have a markdown editor awesome okay nothing in this address editor what did i do wrong editor demos no matter how much you plan all right so i've got editor there it's called editor nav menu uh then i call editor i think i did everything right is it building let's double check uh next one yeah it built let's just refresh that again might be going a bit too quick ah here we go all right here's my text area so if i'm typing in here i can see on the right there's some there's not quite markdown rendered mark the answer h okay so h the uh hash goes to h1 okay heading all right so it sort of works it's not actually working totally correctly so what we're getting on the right hand side here is the actual html but i actually want to render that i don't want to just see the html now the reason for that is in our component what we're doing is we're basically just displaying the html string that's it we're just displaying it as a string this is the html that we get back from the markdig to html method now there's something special we can do in razer we can actually cast this string into something special here we go so if we cast that to a markup string and we just build our application what's going to happen now if we refresh what's going to happen now if we go ah here we go we have markdown being rendered let's try that again we've got heading two ah it's working very nice item yes we've got bullet point lists it's all working and go look mom nobody yes i mean js very cool so you know we can do something really cool like i said i want to do some some code so if i go cs you see here we've got a bit of error being output in the console um and if we didn't catch that error it would actually sort of you know crash our page which is not nice so if we catch it there i'm just logging it i'm not rethrowing it don't yell at me but it's just to catch that little bug so now if i actually go and write oh some c sharp code and it's doing the syntax highlighting for me as i type let's make a little cool method here on our hello world class um let's call it wave and let's see can this do something special can we yes we can add emojis look at that we have c sharp being rendered as markdown in the browser and all happens very easily with hardly any code how cool is that really really cool let's make it bigger as you can see it there we go awesome very very nice so i'm very happy with this so just to recap a markdown editor in blazer will require two packages mark big and a marketing syntax highlighting we set up the mark big pipeline with just a couple of lines of code and set up a text area where we can have some text input and we convert that to html that we want to render with the static method and then we just use this very special markup string that takes our text and injects it directly back into the dom as actual markup uh instead of just plain text so that's really exciting very nice so now the hard bit of you know parsing markdown and rendering is done and we can add some custom controls to you know add our formatting and you know some rich editing for our markdown files so not too much effort and you've got a nice full-blown markdown editor so what else can we do with blazer so i didn't cover this in the in the code but we can do some state management um so right now everything we do is in memory and if we go and use dependency injection with some sort of an application state class that's also going to be held in memory so what that means is that if you go to another tab or a new window that state is not shared it's only for that that particular tab it's in memory if you close that tab it's gone if you navigate away from that page then it's going to only be available to that application as long as it's still in the same tab now the way to solve that is we can use local storage or session storage so those packages are available if you want to store something a little bit more secure we can use protected storage but just to be aware that anything that is on the client side so it can somehow be unobfuscated and inspected so you know try not to put connection string to your database or anything secret in there even though it's harder for someone to try and get to that information they can ultimately still get to it so just be aware of that but we can go a little bit further we can use blazer state and blazer redux so if you have followed the ngrx patterns in angular you can use blazer redux you can get all your actions and reduces and sort of keep that immutable state running through your application and you get that the normal redux tools in in dev tools so you can rewind and replay the the state of your application it's really cool and it's a really nicely written written library blazer redux so i think anyone that likes that sort of stuff should give it a go i don't talk about layouts and theming but certainly uh you get all the components you need to do that for your applications and you can also do some component unit tests using a library called bunit like the name loads it's very similar to sort of x unit you can write facts and theories to test your razor component what this library does it makes it much easier to set up a host to render or to execute your components and then you can just go and use the familiar assert methods to test and make sure that the applications do what they're meant to do now just like with um with the angular world and react there's a lot of component libraries out there and they're starting to pop up for blazer as well so there's definitely some really good ones blazered radzen matte blazer blazer eyes they're all free lots of cool components definitely should check them out i think they're all pretty much worth with it and then telluric sync fusion devexpress and all the other big boys um they've got some sort of trial uh periods for their components but definitely enterprise ready they're really good and they're all sort of aiming for some blazer native components rather than re-wrapping existing angular or javascript components into blazer certainly trying to take make use of webassembly's performance to write some really cool components for our applications cool so now we know how to very quickly build a blazer web application we know why we have blazer and we saw a few cool little demos of how to build something in blazer and how easy it is to use now we need to talk about blazer in the enterprise and when we talk about enterprise we always have to end up talking about clean architecture how do we build our applications to you know be testable and uh for to sort of withstand the test of time but blaze's superpower is definitely shared libraries this is something really cool it means that you know the code that i write the shared code i can use it directly in my webassembly uh blazer webassembly application and in my web api so i can take any of the sort of shared models here and transmit them across a wire as is and just deserialize it directly into that concrete type i don't have to be concerned about is it exactly the same shape and add additional weird error handling just in case it's not the right thing this is nice and easy and this is the simplest way of building a blazer um web assembly application with a back-end api um and it certainly is very nice but just to be aware is that you don't you have to be careful when you put into the shared code you don't want to put your uh sort of business logic or your application into the client's hands because you know they they can inspect that code and i ultimately ultimately uh un-obfuscate that and inspect it and see how it works and you know if you want to give away your secrets that's your choice but if you want to be serious about it just be careful um so when we then look at building something a bit bigger we're looking at clean architecture so what clean architecture lets us do is to build the core of application in this case application and domain it's independent of any other frameworks everything inside of core is testable we can definitely describe all that behavior and lock it down with some unit tests and is it independent of any ui so it doesn't matter if it is blazer angular react vue aurelia it doesn't matter application is unaffected um and it also doesn't matter which database we use if it's cosmos or ef core or sql server it doesn't matter there's no external dependency we don't rely on something else to build our application core and as you can see in the diagram all the dependencies point inwards and that is really what sort of allows us to to keep our application core uh you know sort of in a state that will even outlive blazer you know it'll be there forever it's all testable and nothing's going to interfere with it but then like i said we got the shared code from blazer so where does that fit you know some people might be tempted to um for put some of that shared code and use it in application layer um you know so we can have some dtos or something from the shared library in application so that we can hook that up to the blazer ui nice and easy but the problem is um that now our application layer is depending on something external and we can also see that you know we've got a dependency arrow pointing outwards no longer is everything pointing inwards anymore and the problem with this is is that if the shared library changes for any reason you know we're changing the shape of a dto or anything you have in there it's got quite a big blast radius so you're going to have to change application and anything else that depends on application such as your infrastructure so you're going to have to then go and write something to make your infrastructure work again with this new shape of information or your presentation layer whatever applications you have in there so console or web api or whatever they will also be affected so i don't think this is a great way to go because as soon as you start trying to share your application layer then things get messy and i think you'll end up with a whole lot of spaghetti code so i don't think this is a good way to go at all you might then be tempted to take the idea into a layer between application and presentation it almost makes sense but the problem is that you know even though dependencies all point inwards now our infrastructure layer is depending on a shared library and what that's going to sort of lead to is that we have to write all this unnecessary mapping code to get stuff jumping between the layers and i don't think that's necessary whatsoever so what we need to do is keep things simple you know the core of our application is 100 testable it's on its own you know whatever presentation layer we use it's inconsequential it doesn't matter so anything that we want to do to make use of the shared code should happen just outside onto the presentation layer i'm going to keep that just between the ui and our web api for instance so that shared code can definitely live there i think that's definitely a much nicer place for it to be even though it looks like there's a an arrow that points both ways that's fine i think you know if that's what you aiming for that web api for that ui uh and if that suits your needs i think then that's fine to do it that way but we can go and make it just a little more simpler so we can instead of writing that code we can actually generate that code so just like how we do that with angular and react et cetera using in swag we can generate a c-sharp client instead of a typescript client there's a few other options auto-rest and open api but there's something new coming which is very exciting and that's in c sharp nine so we've got source generators so we can actually generate a client that will consume our api not just through you know controller actions and so forth but even if we want to give them a particular way to call mediator queries and things in the front end and implement the um the redux pattern for them you know we can actually have that all ready to go so all that the view or our components need to rely on to bring in this client and then it's all abstracted away so they don't need to know that it's calling http or it could be grpc or proto buffers whatever it doesn't matter um you know so we wanna we can actually go ahead and do some really cool stuff but we have to wait a little while for the source generators to be generally available it's in preview at the moment but it certainly is looking very very exciting if you want a few more resources about clean architecture check out jason taylor's clean architecture solution template on github it's a net cli template that you can spin up a whole new project and it's got everything you need to get going with clean architecture if you want to just read a few more rules about it you can also check out the ssw rules the clean architecture page so we know now how easy it is to build a blazer application we know why we have it i've convinced you now it's super easy to use and that you should use it and just look at a little bit of architecture and what we should do for building something with blazer in the enterprise and now i just want to look at how i'm going to take our application and run it in the cloud it's very easy so all we need to do is because of the static website we can publish that to azure storage or to github pages it's just dotnet publish and we have a bundle bundled application and we copy that to the storage account and we're pretty much good to go we can then actually you know go a bit further and go completely serverless we can add a cdn onto the storage account so we can get our application spread across the world nice and close to all of our users and if there needs to be an api you know most people would default to an uh asp.net core api but we can also use azure functions and we get that elastic scale so because we're going to write some really awesome applications and a thousand people per hour is going to sign up to our website so we need to use something that scales really quickly and azure functions with cosmos db for instance we get that global scale happening pretty easily so i think that's a pretty good combo that we can make use of so the application that i wrote all the code examples and things that we showed earlier you can find that if you scan this link you can access that application on your phone or on your laptop and inside of that we'll have a link back to my github repo where you can get all the source code and start playing with blazer on your own and to re-host that it's very easy you just go and create a static website in in azure you spin up a storage account click the static website option copy your files to it and that's pretty much all that's required it's super easy and i just need to sort of highlight a few things that's up and coming with net five it's only a few months away but so here's some improvements for blazer webassembly they're going to bring in lazy loading so when we have really large applications um it means that for we only loaded just a small subset of dlls that we need for that part of the application instead of the whole lot which is you know what's happening apparently so it downloads everything and right it loads everything the whole time they're going to improve multi-threading in the next version so definitely some uh great performance benefits you can add css isolation protected browser storage like i mentioned that earlier in the talk but it's an optional package right now but they're going to sort of bake that into a blazer web assembly they're going to add in the icing eye async disposable pattern so that sort of a lot of asynchronous services that we need now and we need to dispose of them in asynchronous fashion so they can bring that pattern in for us as well drag and drop ability and a really good one is ahead of time compilation so that has been delayed.net six but um you know because it takes a lot longer to build our applications but it optimizes it even further than it is now and we're gonna have some massive speed improvements with um blazer when it comes out with net six that's gonna be blazer lts and also the live hot reloaders was scheduled for net five but they had to delay that to net six but uh yeah it's still okay because we have that auto rebuild and it also gets us halfway there but ultimately hot live live hot reload will be pretty cool to have so in today's talk we had a discussion again about how quick and easy it is to build a blazer webassembly app we know why we have it and then why we need to use it and what it means for enterprise you know we can build some pretty cool applications with blazer and how easy it is to run in the cloud and in summary blazer is awesome i think it makes it very easy now for a lot of back end csharp developers who call themselves full stack developers yeah just a bit more html and css and some razer and hey you can have a full stack on your linkedin profile i think we're going to see some really interesting software architectures coming soon with you know the combination of blazer and things like the source generators and just some new ideas of how we can write really cool really rich dot net client side applications i think it's going to be really awesome to see what comes up and there's some really nice improvements for blazer coming in the next sort of 18 months in net 5 and net 6. and yeah sometime next year i think we're all going to be running really awesome blazer applications thank you [Music] [Music] you
Info
Channel: SSW TV | Videos for developers, by developers
Views: 125,649
Rating: undefined out of 5
Keywords: ssw, software, dev, microsoft, windows, dotnet, .net, java, javascript, TypeScript, frameworks, C# ASP.NET, asp.met, c#, Blazor, Blazor WebAssembly, .NET stack, william liebenberg, william ssw, front end web application, .net core, azure, Angular, React, Vue, how to blazor, what is blazor
Id: Oeh2IJw7Zig
Channel Id: undefined
Length: 86min 14sec (5174 seconds)
Published: Thu Aug 20 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.