An Opinionated Approach to ASP.NET Core - Scott Allen

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
good morning everybody how are we good good it's good to see some familiar faces out there my name is Scott Allen and this is an opinionated approach to asp.net core what I did to prepare for this presentation is go back and look at some of the projects that I've been working on to the last year year and a half and just take notes on what I liked and what I didn't like that we did or I did and I came up with the list of 56 items which I thought was a little bit too aggressive for a one-hour session so I cut it back to a list of 50 items which means we'll be moving along pretty good and so some things I'll cover pretty quickly but if you have any questions you can always email me and I went through that list then once I got it down to 50 items and I broke it into some different categories like how do I want to organize solutions and projects what techniques that I liked what didn't I like how to organize startup code and like the code that goes inside of start-up CS to configure it your application some tips about and opinions about controllers about writing client code because we're all using JavaScript code now on the client about writing c-sharp code with asp.net core views and writing unit tests so we'll just get started with some of the boring things like solutions and projects so we can build up a crescendo and have a very exciting finish yes solutions and projects how do you organize them with dotnet core I rather like the approach the Microsoft is take in if you look in any other github repositories for any of their projects you'll see things like a solution file that is right in the root of the directory so it makes it nice and easy to be able to find that solution when you clone the repository and just go into the folder and double click that and there's always a top-level source folder that can contain one or more projects and a top-level test folder to contain one more unit test so if you really look around a lot of the open source projects that deal with dotnet core they follow the same sort of pattern so I want to use that same sort of pattern even for business applications that are not as a source it just make sense to people that are accustomed to this environment now and then I'll throw in a few additional folders so I might throw in a folder for documentation reasonable and the one thing to be careful about here we probably experienced this is if you go into a solution like in the window here and right click on a solution and say add a new solution folder the solution Explorer in visual studio doesn't faithfully represent the physical location of this files on the file system that folder that I create the all these folders that I create are just logical containers and if I add a file to it it just goes into the root of the project or somewhere so you just have to be careful to right-click and add these folders and then go out to the hard drive and do a make directory to create that physical folder and then add items from that folder some of the other things that I like to check in if it's an open source project for example or if it's a library and I want to demonstrate how to use this library include a samples folder Microsoft does this quite often in fact one of the best ways to learn about some of the features of the middleware and the various components to go into asp.net core is actually go to the github repository and look at their unit tests and look inside of their sample for for example the mmm ESPN app security samples contain how to use things like cookie authentication middleware at a low level and those are interesting to read because sometimes they're better than the documentation and they give you code that you can just start playing with some other things that I always want to check in are some scripts development scripts to help developers work from the command line so if you're using something like entity framework or and you have to run migrations then you might want to do that from the command line which means you run dotnet EF migrations ad and all that stuff what I will do is create a script folder and check some scripts in so the developers just need to go to the command line and type add migration and an email of migration and behind the scenes it takes care of all the parameters that have to go to that dotnet executable and you can write this in PowerShell you can write there some bash you can write commands files whatever your environment that you're developing in whatever works and whatever your team is happy with in an example of like ad migration would be I just type ad migration foo and it will go out and do the net EF migrations ad it will do the dot nest dotnet es database update and then I'm just ready to go with this thing I'll also check in deployment scripts so if you're using Azure one approach might be to download the azure resource manager template and a PowerShell script that azor can produce when you just right-click on a resource group and say I wanna or go to the automation script for a resource group and say just give me a script to automate the deployment of all of this I will take those templates in that PowerShell file and check it into a deployment folder inside of Visual Studio and that I can use inside of a build process or my deployment process and developers can use it locally when they need to set up an environment and Azure to be able to work with the project and you might also consider it to like tear form which is very good at automating infrastructure across multiple platforms so it supports Azure and its port AWS and it supports a number of other environments builds I also believe should be checked in the source control so if you go out to use a build system in the cloud something like a fair or something like Visual Studio King services in the cloud there's a way to graphically define your build environment where you go into the UI and you select a couple check boxes and you say here's my solutions build and it just does a bunch of magic behind the scenes but as far as app there goes anyone use out there it's a nice system you can go into a play and you say okay I've set up my configuration now gives me a yeah mol file that describes the configuration that I just entered and I can download that file and check it in the source control and now all of my build configuration even though I can't build quite like a player locally my build configuration is at least under source control and it's version controlled and I can see what it's been changing and what I'll typically do is just come up with a PowerShell script to do the build dotnet builds so far have been reasonably simple you know you can just do not never store dotnet build net run my tests dotnet packed and then developers can also use that script locally if you want to build if we need to debug something that went wrong in a fair anyone using visual studio team services formerly Visual Studio online some working name like that they have that nice graphical build environment where you can just say I want to add another build step and drop in something that says build my solution star that SLM and I think that's very good but I would like again a script that I can check into source control for that build and I would like I would like something where developers locally can use that same script to build on their machine and that way I know that when that script is checked in to be s online that it has a reasonably good chance of working there and you can do that by going into a task catalog there's various tasks in there just to run a PowerShell script or a command script and there's even plug-ins for cake and tea sake if you use those types of build pools and descript everything kind of avoid this graphical environment for anything but maybe the simplest projects just the kind of information you were expecting by the way we're going to see some people wondering about it I do believe that trading too many projects as a problem sometimes with thought net solutions I like to start with just a core set of projects maybe one for the web application one for my core logic one for unit tests and then just see where it goes from there too many projects have a tendency to make special studio unhappy once you get over a gigabyte of memory it starts to slow everything down let's talk about startup 2 for a minute when I look at a startup top CS file in an asp.net core project I think that it has three responsibilities the three responsibilities are typically configure the configuration system in other words tell me if I'm using app settings that Jason and environment variables and all of that and then there's configuring the container which is that configure services method and then there's the configure method which is building your HTTP processing pipeline is putting all the middleware in place so that your application can process HTTP per class and I've seen a few startups ES files and non-trivial projects start to grow a little bit out of control so I came up with some opinions about that first of all a lot of the examples that you look at for asp.net core for some reason they will do this logging configuration that you see here at the bottom they'll do that inside of configure right before all of the middleware is configured and to me that always makes no sense the startup method the configure method is for middleware so I usually move all of my logging configuration into the constructor for the startup class so we'll set up our configuration and put in the different JSON files that we need and then just configure the logger right away and it's ready to go throughout the rest of the startup file the other thing I believe is to keep it clean so inside of configure services when you're configuring the container for asp.net for some of the services that you add are quite complicated they come up a lot of options so for example this first line here add customized MVC that replaced 20 or 30 lines of configuration that used to be inside of here that would do things like provide a custom configuration for the razor view to make it look for folders in a specific file there's all these configuration options for NBC what I would prefer to do is to go into the startup ops ES file and just be a high-level overview of what this application is using so I'm using MVC I have some security features I have mediator I have some data stores and then each of those methods is just an extension method defined in another file to move all of this code outside of the startup file so add customized MVC is just an extension method by service collection and it all just works that way the one exception to this rule is in middleware but so I do believe when you're configuring middle layer and try to the configure method again I want to be able to glance at it and see a high-level overview of the modules that are installed if you have to do any special configuration for that middleware passing options objects and things like that I would rather make an extension method to do that but I do allow the configure method to branch so I want it to be apparent that if we're in development we're using these three pieces of middleware but when we're in production we're using this different piece of middleware that will behave a little bit differently and I I think that starting another thing that I've had some success with is making use of my net web application as an executable because in.net core I can run my web application from the command prompt and ostensibly that's to launch it as a server so it listens on the port but you can also exit before it actually starts running so there's some things that you might want to do particularly in development that your web application can do other than just responding to HTTP requests and then an example of that would be perhaps Auto migrating a database using some migration scripts or feeding a database if I'm in development and I just created a database and it has no data in it and again if you go out and look at several solutions to they're sort of out there on the internet a lot of people will do those sort of box do that sort of work inside of the startup class which kind of makes sense because that's where the application starts or it sounds like where the application starts but really the application starts and static void mean and if I can do work like that inside of process BD commands before the application actually starts booting up and listening to web requests I would prefer it to happen here and I have an example of what process DD commands could look like which is this and I just want to call your attention to the top line of code if you can see it you can see in the back oh yes so what this code wants to do is before we even get into the startup class I want to be able to do things like drop a database and recreate it and do the migrations in order to do that I am going to need to get a reference to a service code factory so that I can use that to get a reference to the repository the entity framework DB contacts whatever you're using for data access and it's very important to actually use this I service scope factory an instance of that if you're doing any side of any kind of work outside of an HTTP request because if you have a dependency registered in the caner that is not supposed to be a singleton so it's a transient dependency or so well it's go to an HTTP for class let's say or created for instance if you get one of those things outside the scope of an HTTP request you can end up with a singleton for the lifetime of the application and this I service code this bit of code right here that gets a nice service code factory will help you avoid that situation will create a new scope will go out and get the dependencies that we need and then we'll do things like drop the database migrate the database see the database with data making any sense okay and to facilitate that I would probably check in a script to the scripts folder so a developer when I'm at the command prompt I can just type recreate DD and it will go out and dotnet run my application and just pass along the parameters so it'll drop the database migrate it feed it and then I actually want to stop I don't want it to launch the server when I do those commands Oh for parking arguments oh yeah you could do that if it got complicated I was trying to do the simplest possible thing that would work until it got too complicated yeah so the question was what I use any of the libraries for flushing command line arguments and things like that and this could be very helpful yes longer recommendations I really liked fever log how many people have used that a few so it plugs right into asp.net core there's a new get package you just download and you write some code to configure sphere log in fact the startup code we looked at earlier was configuring sphere log and there's two nice things about it first of all it's structured events so there's a special syntax here in sphere log that allows you to given some objects like position I actually went to serialize that entire object into my log and sira log will take care of that that's one nice feature the other nice feature was fear log is it has so many sinks that it can go to you can write to a sequel server database you can write to a rolling file you can write to add your table storage there's a list of 20 30 or 40 additional NuGet packages you can install just to have sphere log write information somewhere that you want aqua dotnet actors all sorts of things so we fantastic and you can control all of that well here we go through JSON configuration or through configuration and code so this would just be a way of telling sphere logs I want to write to a rolling file so it's going to be the format of the file so to be log - and a date Jason and after that everything that this log will go into that file for the day so asp.net core comes with a container where you can register services you can register them as Singleton's you can register them as transient and it's really pretty good for a lot of applications with everything you need but you could consider using a more fully featured container something like a structure map or an inject something like that because there are some scenarios that are quite nice for the container some features a fully featured container can provide that are quite nice things like all the discovery and decorators decorators are a big one so a structure with a you got like poor there's no way for me to say given us interface I agree when you construct an instance of that I also want to decorate it with this other class like the cashing reader will suck them out you can do things like that and set up interception and also I have Diagnostics structure map provides a nice Diagnostics where you can basically ask it how are you configured and what will happen if I ask for this how are you going to resolve this service forming and structure Maps fairly easy to plug in that's actually an example of decoration anytime you resolve an eye widget decorate it with a widget folder and we will use a widget but at one time it'll be decorated with a folder going quickly so project structure once you get inside of a specific project what are some things to look for a few years ago Jimmy bells are did a presentation at NDC I think we're at NDC owsla though about asp.net applications implemented with vertical feature slices anyone ever see that one it's a good presentation to watch and feature folders in general anyone here feature folders this is something I started using after I saw Jimmy's presentation and Curtin talked about it a bit I have a hard time now walking up to an asp.net MVC application and seeing top level folders of controllers views and models it irritates me it's a what Uncle Bob might call the screaming architecture like the layout of the project of screening that this is an MVC application I would much rather organize the application around the features that it's going to implement so if I'm building an accounting system I might have a I want to have a features older that would provide me account management administration and actually this is for golfers apparently maybe my API that some Java Script uses some shared stuff but I like this for a few reasons one is it really allows me to think about partitioning my application by feature instead of artificially putting views in one folder and controllers in another folder and it's very easy here now to keep it controller and the views that that controller is going to use in the same folder as well as any view models that that controller that are specific to that controller and it's a very nice organization because it makes things easier to find and typically when you go in to make a change in an application you're working one a feature and so to go into a feature folder and have nearly everything that you need right there I think it's been advantageous the other thing I like is it can mimic the hierarchy of the UI so if I actually look at the UI for this application someone clicks on the top-level admin link and then they're given another menu that says do you want to manage this or manage that or manage this and so I can have nested folders inside of there but there can still be notice this admin controller the kind of controls that top-level feature how do you do this in asp.net core it requires very little codes and by the way I've had several frustrating attempts trying to rewrite those account controllers in asp.net core and I'll get as far as creating a log in log out controller and the register controller and trying to break it out it's just very cumbersome someday that'll be a new get package that I can put together I hope the code to implement feature folders is relatively straightforward and what I did one day is just put it into a new get package and publish their own new gap its ode to code add feature folders once you install that package when you're inside of configure services all you do is all you need to do to use this is to say services MVC add feature folders and now you can place your controllers and views inside of a top level features folder make them so controller code I like to think of controllers as purely facades so that they should do as little work as possible and have as little a little code as possible inside of them which I'll come to in a minute I do like the routing attribute route in asp.net core their first-class feature now they're very flexible they don't have some of the quirks that were around in MVC 5 and so every controller that I write now will use a rel attribute say to reach this controller you have to go to admin / manage mash map is slash and then an action that's inside of here and I like this for a few reasons one is I can make parameter names like season ID match up with what the action is actually expecting I don't just have to have a generic ID parameter which I often find very confusing when there's an ID parameter to every action and I don't know if that's supposed to be an account ID or a golfer ID or employee ID what is it supposed to be and if you I'm assuming a lot of people have used asp.net core and you know that these special tokens for square brackets that allows asp.net core just to replace the name of this controller inside of that route so you don't have to hard to manage matches inside of there I'm a big fan of mediator so another Jenny product of Jimmy Bogart mine what mediator allows me to do so here's what I went from a controller I mentioned this earlier I want to control her to be a facade I want to control her to only be responsible for receiving an HTTP request and sending out a response but doing nothing in between just dispatch something and I actually really liked the web api back when it back when it was web api to when you actually we're working with abstractions like HTTP request message an HTTP response message because that's what i think a controller is really doing it's receiving overclass and sending out a response asp.net core we don't have those types unless you install the web api compatibility shim but i'm okay to live with this is a controller that takes a command that's been be serialized from the incoming request for me and now all I really want to do with that command is maybe I'll do some basic checks like model state is valid Jimmy doesn't like that but I'm okay with it all the work though all the work happens in meteor so I don't want the controller touching any sort of business service or repository or context or do anything other than maybe with a logging service I just want to dispatch things through mediator tell me anyone using mediator whew so check that project out it's really easy to set up what you do is you set up I don't think I have any code here unfortunately you basically create queries or commands you dispatch them using mediator mediator will find the associated handler for this particular command and it will just do work and return you a result it's perfect throw away the account controller yes this is trying to lift the account controller it Scrolls off the bottom of the screen just trying to lift the manage controller that's the exact opposite of what I want a controller to look like just range and reams and reams of code inside a controller action it's very difficult to look at a lot of people asking you about cross-site request forgeries in aspx or and yes obviously it's still a problem so if you have an app and a lot of people ask me how how do I if I if I'm building an API with the asp.net core how can I get a token to my JavaScript ur to send along to prevent a fee surf at at so this is something you have to worry about if you have an application where the authentication happens implicitly and automatically so an example would be cookie authentication so you're building a full web application and a part of that web app application our API endpoints the JavaScript calls and because you're using cookie authentication the browser will automatically authenticate the user by sending that cookie along another example would be Windows authentication it happens there too so how do you get a cookie into JavaScript I usually set up an xsrf token controller this is just injecting the int anti for jury service and I can walk up to that service and I can tell it to get in-store tokens that'll actually do two things right there the first thing it will do is issue a set cookie header to the client to make sure that there is a cookie would be one part of the xsrf sodium and it will also return to me a data structure that will tell me the request token that my JavaScript needs to include as well as the header name that I need to place that token into so just return that as JSON back to my JavaScript client and now it can send along that request token header name and I can just decorate my API endpoints with validate anti forgery token an asp.net core takes care of the rest so to compare the cookies to the requester and make sure that everything is protected embrace security policies policy use if you probably know that asp.net core did a a radical rewrite of how security works some of it I think is actually I'm not too happy with and it's kind of weird having an authentication property on the HTTP context I always thought was a little bit weird it seem to me like authentication should just be another service that I can inject I don't know if they'll change any of that in the future but there's some discussions on github that indicate they might be changing that in the future security security policies our policies that you can apply to say I want to check that this user is an admin or is authenticated or has an email address that is in the domain of my company and you can encapsulate that rule into an authorization policy like so just by requiring claims I'm doing a build to turn it into a policy and once you build one of these authorization policies they become very easy to use in an authorization attribute which I'll get to in just a second and for those of you that haven't worked with claims botnet core is very oriented toward claims that was a move that started a few years ago even though the full dotnet framework but it's just the idea that a claim can be any key value ter so what is my email what is my name what organization is a am i associated with and I admin or not those are all claims that you can add and if you have custom claims that you want to add about a user in there's extensibility points where you can go in and add additional claims at the point where the user is authenticated you might need to do a database query to do that and that's exactly what it was designed to do but then once you have that once you have understanding claims you understand security policies what I don't want to see in a dotnet core application is someone to using the authorized attribute and passing in a string that describes which policy they want to use I would much rather create a custom authorization attribute that is very clear that user is admin so that's something that I could decorate a controller or an action and behind-the-scenes I don't know what policy is using I don't really care when I'm just implementing the controller but behind the scenes I have some flexibility now as to what claims that will actually check and what policy that will actually use so custom authorized attribute let's talk about views how many people still use HTML helpers any asp.net chloride hip nobody OSU I always liked asp.net MVC but I always thought that was mmm excuse me the absolute worst part of the MVC framework HTML helpers tank helpers are much better tag helpers for those that haven't used them their process on the server side but they are a lot like angular 1 directors well they sit in your HTML rate the razor engine can detect them and you have the ability to inject logic and change the markup when these anti forgery sorry II type forgery when these are tag helpers are in place tag helpers can be attributes because also the elements and they're relatively easy to write as long as you're doing something simple and I encourage people to write their own tag helpers to take care of removing some common markup that might be inside of your views so this would be a custom tank helper that looks for an element my dash environment and I could set name properties on that also embrace view components anyone using to use components in dotnet core such a few review components or any feature in previous versions of the asp.net if I had to render a a hunk of markup inside of a larger view if it was using the same model as its parent view it was easy to use a partial view and just say render this partial and here's a model to use but if I want to render of chunk of HTML that's based on a completely different model and I want to unassociated with the parent view there was a thing HTML dot action which would call back into the controller action as a child request and it worked most of the time but there were some situations where child actions child actions just became very weird child actions are basically gone in this version of core what I can set up instead is a view component so view component is almost like a controller because you're going you're going to have a method invoked not as part of an HTTP per class but it's a request from from view and this method in though can return views up sent well but pretty much always return views but they can return anything that's an IV component resolved and the way I could use that is let's say I want to encapsulate all this HTML into something where I could just say render the main menu and this thing could inject its own services that it needs to look up things in the database and find out information about the user there's meaning view component can do that and all I need to do to render this main view component from a razor view is to do a weight component dot invoke async that's what I have to do in 1.0 that's a really ugly syntax but that would find the view component called main menu call the invoke method pass I can pass parameters there too and it just spits out whatever HTML does that view component told it to if you're using 1.1 there's a tag helper BC that allows you to render that view component and is really quite nice now it looks looks nice inside of the view too so it's just another way to decompose a complex view into simpler pieces and the advantage of the view component there is that it can again be completely independent it can inject its own services and figure out its own data model to use client code every asp.net core uses JavaScript these days chances are you're using javascript that might be starting to use things like a script approach the echo script 2015 thought it was over the jet lag but maybe not how do you package and bundle that stuff personally right now of all the tools that are available I prefer web pack it's just a tool that I think works well with both the JavaScript code as well as there's some asp.net integration now that will talk about how many people using web pad good note any anyone else using something else like roll up or browserify now so maybe I'm preaching to the choir use webpack one of the reasons I like webpack is I think the configuration although it's a little bit difficult to understand it first at the end of the day it's a little bit simpler than some of the other tools that are out there basically you just need to tell web past what thousand I'm looking at so look at j/s files what modules do I want included I'm going to be building a bundle that includes react here and what's the output where do I place the output what j/s file and it also has these new plugins this one unfortunately names this dll plugin and it has a sneek plugins that can do things like uglify the code minify the code determine keep track of what modules i've included here that's what this dll plugin does keep what keep track of what modules have been included in this bundle so that when I build a second bundle with my application code these modules are not included that's the idea build one file with all the stuff that doesn't change from bender's those other files that contain my application code that are changing all the time and I like personally to use multiple configuration files with webpack so I like to build have one configuration file to build my vendor bundle one to build all of my test code one to build all of my application code and just there's a couple different opinions here that are going on one opinion is that a lot of people will use other tools like a test runner so that when their XP ting their unit tests the test runner will actually do the compilation of module bundling of things like typescript files I like to do it all with lead pack and then the my test runner I don't have to worry about loading plug-ins to do that the neat thing about web pack is it's executing in their JAF so if I need to do things like go out and find all of my TF files that are inside of these features folder I can do some programming there to just find them all JavaScript services was a project that was recently released by Steve Sanderson and some others he finished and working for Microsoft but of not Jes name and it works really well with webpack so basically what you can do with with JavaScript services it's a piece of middleware that you can install into your asp.net application so that if you're using webpack to build and bundle all this javascript code it can do hot module reloading by talking to that piece of middleware so that when you save when you update a JavaScript file or a typescript bond you save it to the hard drive web pack detects that and just communicates with my asp.net application directly and says hey send us a new chunk of JavaScript down to the browser and just that need logic disappears in the browser and I don't lose any State and things just magic just happens and it's really easy to use you just install the middleware and what happens behind the scenes is that this middleware is the one that will actually run web pack for me based on my configuration files that I have available the only downside to this is that it happens silently now inside of my asp.net server so something goes horribly wrong for some reason this web pack you'll occasionally get into these situations where the the hot updates don't come over and you have to refresh the browser and sometimes restart your server but it's worth it because it makes the rest of the development cycle so quick I use karma as a test runner even if I'm not using angularjs karma was a test runner developed by the angular team but it works with anything and you can use different test frameworks like unit Jasmine mocha so I use it for like react based projects it's my opinion that this is the best test runner that is out there it requires very little configuration basically just need to tell it what files to load and it'll just run all my tests and as I've already built all of my tasks from tight script into JavaScript the configuration can really be just as simple go out and find all of the J's files load them find out what I specs load them and now it will automatically launch Chrome and run my unit tests there's a lot of things in that core that require the command line particularly when you get to client code and using things like NPM and tools like WebP at I don't like the built-in command prompt in Windows so I tell people do con EU that's fixed con nu or commander Cmdr that's probably what I have running somewhere around here but it doesn't want to come up area it can show me things like the current branch I'm alone and the project so it seems that I'm inside of a git repository now on the branch sprint QA there's nothing been modified but if I were to touch a file that would turn red nice little indication the other next thing it does which won't be a big feature for anyone that uses something like AI term on Mac OS is that you can have split panels on it and this is really nice when I want to run something like a web pack build over here and watch it and a build for my test over here and watch it a my unit tests down here and just watch for red to flash by to see if a unit test field I can have all the lives inside of one window at a time and I can even write a little script so the developers can launch that process so this is the syntax to launch con email and tell us to do an NPM one run watch in one window then do an NPM run test watch in a new console that is split horizontally so bring up this window and then NPM on karma in a new console split vertically so bring up this window and now I have those three windows ready to go only downside to this make make sure you put all of this on the same line so don't actually put line breaks in you have to stretch it out across to the far right of the editor client code layout I've struggled with this a little bit quite honestly but there's been some nice things that have happened recently in the type's pro type script world and the web pack world that allow me to place my client code wherever I want to so in an asp.net core project but let's say I'm building something with react or angular 2 I could have a client folder and inside of the client folder place things like not only my CSS but also my script and I can have modules in here components and models and services and you might say well what about feature folders well typically what I've been trying lately is that this client folder which is a top-level folder in my project will contain the reusable things for the application so the things I need to invoke services and API is back on the server but in the features folder I will have a little script file that will bootstrap the components that are needed that particular feature at least so in the features folder just lift up CF HTML file it's a little bit fancy it's not a full spa but it needs to include this list that main TSX file you need to have that functionality and this but this list file might pull in a bunch of stuff from common components and models and services hopefully this is all making sense another thing I've started to feel very strongly about is using NPM only so I want to use NuGet for everything that's net and I'm going to use NPM for everything that's Java scope and a lot of Microsoft developers we've kind of been encouraged to use Bower over the years and I think there's a lot of that still hanging around today I haven't used our in about two years now what a lot of people don't realize about NPM although there's some scenarios where it's not particularly good goes but it can manage client-side libraries so if I went to NPM install bootstrap the CSS framework I can if I went to NPM install jQuery I can I can certainly npm install angular 2 and that means if I have everything controlled by NPM I don't have to worry about NPM and Bower I don't have to worry about even typing anymore because typescript types have moved over to NPM repositories so I can NPM and slow all types for Jasmine and reacts and all those things that I need so use NPM forget about Bower if you can and by the way a lot of people say well how do I tell the difference between what what needs to execute on the server and what needs to execute on the client that it just doesn't bother me jQuery o go to the client and karma is something I use on the server but it all comes down to NPM I have been resistant to tight scripts for a long time I tried using it but I really got the feeling that it was designed to write when J s programs for Windows and I wasn't doing when J apps but a few things have happened recently which have made me accept type script I've started to like it a lot more it's actually a couple things that you can see in this TS config file first of all no implicit any still allows you to kind of opt out of type script so if I don't want to write type annotations everywhere I don't have to another piece and my drawing tools not working but that's okay another piece in here that is quite nice is model resolution model module res resolution of note is wonderful because now if i npm install a library like react or angular q and I start writing type script when I write an import statement type script automatically looks under new modules and will find those modules I don't have to do anything special or any other configuration that's quite a mint quite nice but if I do have a problem this trace resolution flag will actually tell me everywhere the kite script is looking for something that I can either find or not find so when I write an import statement with es2015 or text rib it'll tell me where it's looking I can also customize my environment now so one of the problems I have a type script in the past is you just run into weird problems where you use someone's library that is using promises and tight script would complain about not knowing what the promises and you'd have to ensure typescript that you are using a promise library if promises don't exist now there's this Lib configuration where you can basically just tell typescript look i'm program in the browser so assume I have all the Dom types I'm programming with es5 to make just assume that I will have all of the es5 API is available and by the way I'm also just assumed that I have promises available so it does complain if someone uses them and then the other piece that's really wonderful is this pass so with with pass that three you can tell typescript I want to also include this client script folder when you're trying to resolve a module so if I say something like import my list widget or imports too from my list widget type script will know to look in the nude modules folder but also to look out at the client scripts folder to try to find that widget and I have a lot more control over what we're type script is looking for things it's made a lot easier to work with so now it's just a problem of do I like all the type annotations and if you use typescript in the past and you've struggled with either the PSD utility or the Taipings utility trying to get pipe definitions to typescript all of that stuff is in the app types repository that you can use with NPM now you don't have to install any extra tools all you need is NPM and I can install NPM install app type slash Jasmine and poof typescript will understand my Jasmine tests now no additional work needed so all those things are good I do something that maybe is a little bit odd I don't know I do all of my c-sharp work inside of Visual Studio with resharper and I have Visual Studio code open to the same solution folder so that whenever I need to add a type script or echo script 2015 stuff I can do that in code just code to me feels looks still a little bit better than Visual Studio for editing JavaScript it's very good and those plugins you can get to do all sorts of wonderful things with your tight script and equus code a lot of people ask me where do I place my client code and where do I build my code to and my opinion is that the client code that you cannot send it to client because it hasn't been transpiled should be kept outside of the www root folder or whatever folder you are using to serve files and then when you build it with web pack or whatever tool you choose you build it into the dub-dub-dub the root folder and just have a consistent naming scheme we're going to put it in a distribution folder I like to call it assets and it's inside of here where everything that I've built with web pack exists I think of it as my bin folder for JavaScript ah another little thing that I liked that we did in one project was we would need to instantiate some react code to run on a page and pass it some parameters and was just going to do a few simple things on that page but actually come up just with the data - parameter and serialize my model into that HTML attribute so that react to easily grab that data and not have to go back to the server and now what about unit testing I think having a single unit test project for your solution or your application is a fine thing all depends on your project in your solution Microsoft takes the approach where they want get one unit testing project per production project right so they have a lot of test projects which I think is fine for open source projects like that and open source projects where different projects build into different new gets and there have to be very public about it but for a business application I think it's okay to have one test assembly but just has folders for each of the projects out here that I need to test whether it's three or five or ten I like using X unit with dotnet core I think it's extensible it's open source this was ceremony they do a good job keeping it up with all the changes and I like the vocabulary action is the best I like writing facts instead of decorating things with test method but that's just my opinion I try very hard to avoid mocks in my unit test and if you go out on the internet you'll find lots of debate about that I'm not going to cover it here but I simply I refuse to use a mocking library and that's my opinion I don't like mocks what I do like is what some people would not call a unit test but let me explain this slowly so first of all out there one of the pieces of infrastructure that Microsoft provides in a github repository and as a nougat package as a thing called the asp.net for test toast anyone uses just it's a wonderful piece that you can use inside of your unit test so what you want to do so ostensibly what asp.net Court éstos is about is it's about this situation I have to start a class that configures a bunch of middleware how would I ever test that request and information are flowing through the middleware correctly that's something that the asp.net core test host can do it can basically set up an HTTP processing pipeline and you can send off a request through this test host it just stays in memory it doesn't actually have to open a socket or go anywhere and it's a lot like an Web API when you had that in memory channel that you could route requests through an example of using it would be that I had some different code here what if I want to test a bit of functionality that I want in my application like an ajax login redirects to the return URL and turn an ajax login redirect if it's an ajax ajax request I actually wanted to return with a few hundred status code and the redirect instruction in the location header how could I test that little bit of thing well I can instantiate an asp.net core test toast it's relatively simple in this example it's wrapped inside of a method called create server but I'm going to place some little we're inside of create server some cookie health education and send a response send a request right there so send async a request to example.com make it look like it's an ajax request and then i can write a search against the response and here's another example create a server create a client issue an HTTP GET request to this URL see if i got that ready write status feedback so this asp.net core test toes is one part of my solution let me tell you about another part if you are using entity framework or and has this in-memory provider anyone using that I'm curious anyone using es core anyone avoiding es yeah on some projects I use and it's okay but this in-memory provider is actually quite nice I can say I want to new DD contacts and I can add things to it and I can query this DB context and all the data stays in memory doesn't actually get a sequel server this is not to use as a production in memory database they make that very clear it doesn't support a lot of scenarios and it will break on you and it doesn't quite obey the semantics of what a real relational database would do its sole purpose in life is to give you something that you can write unit tests against the entity framework with the one thing to be aware of make sure I have this one of slide ah yeah let me back up a second the one thing to be aware of is this different people approach the in-memory provider with different expectations of how it should behave some people expect that if they create a new dbcontext object that they would have a new in-memory database but that's not how EF in-memory provider works the way it works is you create your first DB context and yes there's a new in-memory database now and you add things to it you can query it and if you create another dbcontext over here in a different test it will use that same database which isn't quite what we want for tasks but at least that's what some people think but in reality it is I need to be able to call the way I would use this as I call into a component that's in my application that uses the entity framework it's going to instantiate a DB context and it's writing data it has no idea that this is just in memory but once my application component is finished in my unit tests I want to be able to instantiate a DB context and query that in-memory data that it's stored and so that scenario works every dbcontext you create will you sustain in memory database but you can can can clear out that database between tests what you need to do is just configure things correctly with the internal service provider so that every time you when you explicitly ask for it excuse me this class that I have set up DB instance it will create a new didi context for me that will reboot the in-memory database that's being used so clear it out between tests and that's why back here Andres unit tasks I will just construct a new instance every time this class is created therefore every unit tests will have a new in-memory database to work with but that makes sense so where I'm going with all of this is that the combination of the asp.net quartet toast and the es in-memory provider actually gives me the ability to write from what some a lot of people would consider integration tests so I'm going to instantiate my entire application or maybe instantiate my entire controller and I'm not going to try to mock anything out or fake or stub anything out I'm just going to use this in memory es provider so that when I tell my controller to create something I'm going to go in and make sure that thing got into the database somehow so just I begin a test now it's more of an integration test it's the controller that's going to use mediator and it's going to use command Handler and all these things are going to be going on but it's very little code to give me a reasonably high expectation that my application is actually working because it's exercising the whole thing and really the point of unit testing controllers when you use mediators is on this new point they're just orchestrators at that point there's hand messages around so this gives me a nice high level view of is my application working or not and now just a few simple tips top T char code so if you're using dotnet core and you want to go cross-platform simple tip would be always use environment new line instead of hard-coding a / r / r / n there's how to work across platforms always use past combine when you're building up a fascinating - a file that's on the file system and be aware of the different environment variable names that are used on Linux vs. Mac OS versus Windows like if you wanna get the home environment get the home directory for a user and then last thing kind of unrelated to this I've started to have an intense dislike for the convention of applying the async suffix to an async method does anyone else have that just like at least one person so I think it's useful if you have legacy code that has synchronous methods so a method like get account and now moving forward you need to provide two different methods you need to keep that synchronous method there so you don't break old clients but you need to provide an asynchronous version for people that want to do a sync programming so fine adding get account async method because the only differ in the return type and we all know you can't overload c-sharp methods just based on the return type but if you're not in that situation you're building a brand new API something that does a sign out tenant I don't want to see the async suffix there I can look at this method and see it returns a task and that's enough for me to know that it's asynchronous and I really think this boils down to and well and there you can see the Microsoft API and up async this really boils down to I saw this blog post a couple months ago about a talk that the orange juice trip did on channel 9 where he said when I'm designing the C++ language for new people for new features people insist on loud explicit syntax and I think when a single wait was introduced in c-sharp we wanted loud explicit syntax to say this is an async method but we've reached the point now that this is pretty much an established feature there's a lot of people building AP is now where they don't offer synchronous methods they're all it's only async and I would rather have the terse notation and not have to type out sign out tenant user a thing in fact I wish there was an easy way to get rid of tasks and the async keyword too but it's just a dream anyway that's all I have and a couple hopefully within a couple of weeks I'm going to list all these things out in a blog post so maybe and with links so if you want to find out more information because I sift through these things too fast but otherwise you feel free to send me an email and I guess I had a few minutes for questions okay I'll be hanging out thank you for coming [Applause]
Info
Channel: NDC Conferences
Views: 18,113
Rating: 4.9080458 out of 5
Keywords: ndc, ndc london, scott allen, asp.net, core, web, .net
Id: 6Fi5dRVxOvc
Channel Id: undefined
Length: 55min 49sec (3349 seconds)
Published: Tue Feb 14 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.