🚀 .NET 5 Web API & Entity Framework Core Jumpstart

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
dot net is getting better and better and more important in the web development world nowadays with the latest updates to net 5 microsoft combined the old.net framework with net core one framework and sdk that is free open source and cross platform almost every request i get for new web development projects is asking for knowledge in.net core and also.net 5 including web api and entity framework so knowing the fundamentals of back-end web development with.net can be highly beneficial to your career and that's where this course comes in in a short period of time you will learn how to set up a web api make restful calls to this web api and also save data persistently with entity framework code first migration a sql server database and all three types of relationships in this database we will get right to the point you will see every single step of writing the necessary code and by the end of this course you will have what it takes to say yes to all the dotnets and net core project requests from any recruiter the only tool you need in the beginning is visual studio code which is available for free we will use visual studio code for our implementations and make calls to the web api with the help of swagger ui an interface that lets you consume the api out of the box thanks to the latest version of the.net framework visual studio code is available for windows macos and linux and since the dotnet framework is cross-platform you can follow this course on any of these operating systems later we will utilize the free sql server express with sql server management studio to manage our database we will also have a quick look at sql lite so that you know how to use any database you want the backend application we're going to build is a small text-based role-playing game where different users can register we're going to use json web tokens for authentication and create their own characters like a mage or a knight add some skills and a weapon and also let the characters fight against each other to see who is the best of them all my name is patrick and i will be your instructor for this course i'm a web developer for over a decade now i have worked for big corporations and small teams as an employee and a contractor and i just love to see the way microsoft is going with dot net and how important it gets day by day so i hope you're ready for your new skills and your new projects i'm looking forward to seeing you in the course welcome and thank you very much for joining the.net web api and entity framework jumpstart course this course is meant to teach you.net skills fast and efficiently so you will be ready to tackle any upcoming project with ease this is what you will learn in the next couple of hours in this chapter you will prepare your machine with visual studio code and the.net sdk and then you will already create your first web api with.net and even make your first api call after that you can create a git repository for your project if you want to then we dive deep into the web api you learn about the model view controller pattern and best practices for a clean web api structure and clean code we'll get to asynchronous implementations with async and await use data transfer objects we will cover all crutch operations meaning create read update and delete with the mostly used http methods get post put and delete we'll get to the details later the following section provides persistence with entity framework entity framework is an object relational mapper that will save all our changes in a sql server database we will utilize code first migrations to do that and again implement all crud operations then we'll cover authentication users will be able to register and log in and only see their related entities we will use cryptography to hash the passwords and utilize json web tokens to authenticate the user with every subsequent web service call further on we'll have a look at all types of relationships in a database that's one-to-one one-to-many and many-to-many relationships each one needs its own kind of implementation and finally since in this example project you will create some role-playing characters we will let them fight against each other all by themselves by choosing their weapon or one of their skills in the end one character will have the most victories and that's what we want to display alright you see there's a lot to learn let's start as soon as the.net sdk and visual studio code is installed we can already create our first.net application which will be a web api right away to start i created a new folder called.netrpg for dotnet roleplaying game now we can open this folder with vs code just right click and then select open with code i assume you are already a bit familiar with visual studio code if not feel free to have a look around and while you're doing that it might be also a good idea to install certain extensions you can see on the left side here we can open our extensions i've got some installed but disabled a lot just for this course and the very first extension i recommend is c-sharp for visual studio code by microsoft itself now this extension will also be suggested by visual studio code as soon as you create your first c-sharp application it includes editing support syntax highlighting intellisense go to definition find all references just have a look pretty useful stuff now the next one is c sharp extensions by just creative it might speed up the development workflow by adding some entries to the context menu like adding a new c sharp class or interface for instance all right and then the last one already is one of my personal favorites the material i can theme now this one simply provides lots and lots of cute icons but that's not very important of course i just love this extension and another one maybe you want to install not really necessary but prettier is a formatter for visual studio code so if you want to format your code in a visual studio and maybe another way then i recommend this extension but the most important ones are really the c sharp extension here for visual studio code and then this thing maybe c-sharp extensions for your context menu entries to create a new file and you see shop class new interface and so on all right but now let's create our web api and for that we open a new terminal window let me just close this thing here and then with terminal new terminal or your shortcut you can open a new terminal window as you can see right here and now we will have a look what the dot net command provides as you can see here for now not very much but we can add a dash edge to display some help and this help will be the available commands so dot net dash h and the one that is interesting for us now is the new command right here which creates a new dot net project but we also got the run command for instance and this one well is there to run our application and we've got also the watch command down here which can be used together with run to restart the application as soon as we make changes to any file this is quite useful if you don't want to stop and start the project by yourself every single time you make any changes okay and now with dot net new we see all the available templates and there are a lot as you can see here for instance the plain old console application right on top and further down we finally get our web api here asp.net core web api it's still called core in this case this is the one we need so let's use it we simply type dotnet new and then web api all right now we see some files that have been generated for us in the explorer i would say let's go through them real quick now at the bottom we see the weather forecast class this is just part of the default web api project we don't really need it but let's use this example in a minute now in the meantime we get a little pop-up telling us that we should add some files and of course we want to add them you should see now that this vs code folder with the launch json and the tasks json has been added both are configuration files for debugging source code formatters bundlers and so on but not very interesting for us at this moment so let's have a look at this startup class next now here you can see the configure services and the configure method and the configure services method is here for the apps services or to configure or register the app's services so a reusable component that provides app functionality we will register service in the future in this method so they can be consumed in our web service via dependency injection for instance please don't mind all these passwords right now we'll get to them throughout this course now additionally here you can see a configuration for svega oswego ui this is new with net five before with dotnet 3.1 this was not available here out of the box this is just there to test our web api then directly in the browser before you needed another client to test this like postman for instance but in this case now we will use swagger okay now the configure method creates the apps request processing pipeline meaning the method is used to specify how the app responds to http requests as you can see we're using https re-direction and routing and so on with all these use extension methods we are adding middleware components to the request pipeline for instance use https redirection adds middleware for redirecting http requests to https the startup class is specified when the app's host is built and you see that in the program class so let's open our files again and here now in the program class in the create host builder method there you can see it here the startup class is specified by calling the use startup method now in the cs approach file we see the sdk and the target framework now it's dot net five and the root name space if you called your folder also.net rpg then this should be.net underscore rpg as well we also see a package reference to swashbuckle asp.net core for swagger ui and references for authentication that are also already added you see that under the hood the term.net core is still often used later on we will find additional packages like entity framework in this file now regarding the app settings json files we only need to know that we can add and modify some configurations here more interesting for us is the launch settings json here in the properties folder where the current environment is configured and also the application url and with this url we will find our running web service you can see it down here we will use this one localhost 5001 for the https url or the port 5000 for http all right now the object and bin folders can be ignored for now we find temporary object and final binary files here very interesting and often used throughout this course is the controllers folder the first controller you see here is the generated weather forecast demo controller we get to the details of controllers later but for now it's only important to know that we can already call the get method down here and i would say let's do exactly that in the next lecture to start the application we open the terminal and then enter.net run you see here's already the url we've seen in the launch settings json so let's either open chrome and enter the url manually or just use the link right here and when chrome is open you can see that there's not much to see here but there is another url available for us which would be localhost 5001 for the https one and then just slash swagger and with that we see here the swagger ui it will help us to test our web api but let's forget about swagger for just a second you can already see the weather focus controller here but we can also access the controller with the address bar of chrome now when we go back to visual studio code we can see the name of the controller which would be weather forecast without the controller term we also see this routing attribute here to define how to access this controller we'll discuss how routes work in a future lecture but just for now this thing means that we can access this controller with its name again just weather forecast so we can just copy the name with the forecast then go back to chrome and enter the correct route and finally we should get the results so we just enter the url localhost 5001 and then weather forecast and there are our results now when we go back to swagger you see the controller with the forecast and also the schema here now the schema is actually the weather forecast class that tells us how the result of the web api call will look and now above that's not only the controller it's actually the get call of the web api we can see the available parameters in this particular case there are no parameters and we also see the expected result down here which would be an array of weather forecasts and the best thing is we can try this out right here so let's do that by clicking try it out and then when we click execute we see the request url which is the same thing we have entered in the address bar a minute ago and we see the result we can also see the result in the network tab of the developer tools of chrome just hit f12 and then we go to network we can filter by xhr which stands for xml http requests and then just click execute again and there is our weather forecast call and we see exactly the same result okay great this works now let's move on and build our own web service now there's one little thing we may do before we start with the web api let's create a git repository for our project if git is not installed on your machine please do that first to do that you can simply google for git and then you should already see the good website here and then you can go to downloads and then for your operating system please download git and install it after that on the left pane we go to source control and choose to initialize a repository or we can directly publish this repository to github this is totally up to you so for instance just initialize the repository here and then you see all these changes here and the thing is this is simply too many we don't want to commit the bin and object folders for instance so we need a git ignore file to ignore certain files and folders and to do that we open the terminal again we stop the application with control c and then we simply enter dot net new git ignore and with that we are already good to go you see that lots of file changes are not listed anymore because they are now ignored now we simply add our first commit message like initial commit and then commit all the changes with control and return and then we are done from now on you can choose to commit your code whenever you want to get a clean history of your changes i will do that too additionally you can push your repository to github now as well just click the cloud icon down here on the bottom left and then you can publish your code to a private or a public github repository for instance i can say this private repository here and since i already got the dotnet rpg repository let's call this.net 5 rpg it is publishing the files to github and we are done now i can open this and as you can see here is the repository and now don't get confused by the private label here i will make this one public as soon as i'm done with recording this course and then you can access the source code here of course so far you learned how to create a web api project and.net from scratch and how to make your first api call in the upcoming sections we will create a new controller and models for our role playing game characters additionally we will turn our synchronous chords into asynchronous calls make use of data transfer objects or short dtos and change the structure of our web api so that it meets best practices but first let's have a look at the model view controller or short mvc pattern which is the foundation of all this model view controller or short mvc is a software design pattern that divides the related program logic into three interconnected elements let me explain what every single one of these three elements stands for and how they collaborate we start with the model you could also say the data a character in our role playing game is a model for instance it can have an id a name hit points attributes skills and so on you as the developer know the code of your model but the user won't see your code that's where the view comes in the user probably wants to see a representation of the character in html plain text or amazing 3d graphics depending on your game in other words the view is the graphical user interface or ui to sum these two up the model updates the view and the user sees the view if the model changes let's say our character gets another skill or its hit points decreased the view will change too that's why the model always updates the view now what's up with the controller the controller does the actual work there you will find most of your code because it manipulates your data or model in our case it's the web api that will create update and delete your data since we won't have a view except the results of our calls in swagger we're going to build our application in the following order first the model and then the controller and we will always jump back and forth between those two with the help of the view though the user can manipulate the data hence properties of the rpg character with buttons text fields and so on in a browser game that might be javascript code in essence maybe with the help of frameworks like angular react or ujs or blazer webassembly this javascript code then or c-sharp code in case of blazer uses the controller to do the manipulation and save these changes persistently in the database the manipulated model will update the view which is then again seen by the user and the circle starts all over again well that sums up the mbc pattern now we're going to build our first model the first things we need are new models we need a model for the rpg character itself and also a model for the type of rpg character this means a character class like bavarian monk necromancer and so on so first we create a models folder just right click and then click new folder and we call this models and for the character model we will create a new class in this models folder if you have the c-sharp extensions installed you can add a new c-sharp class with a right-click and then select new c-sharp class and now we call this character and now let's add some properties we can do this with prop and then hitting tab and the very first one would be the id then the next one which is a string is the name of the character and let me give this character already a default value like frodo for instance then the character has hit points so an integer hit points by default this should be a hundred you give the character a strength attribute with value 10 also defense with value 10 and the last one would be intelligence for instance also with the value 10. now we also add an rpg class property this means the type of the character but first we have to create an enum for that so let's add a new c sharp enum called rpg class in our models folder right click again use c-sharp enum and we call this rpg class feel free to add any kind of role-playing class you want to add here in this example i use a knight a mage and a cleric the most basic characters you would need i guess some melee action some magic and of course never forget the healer now when we have the rpg class enum ready we can go back to our character model and add it here with prop and then rpg class we call this and by default i set this to the knights but again this is totally up to you all right the first models are ready let's add a new controller now and make a get call to receive our first role playing game character to add a new controller we create a new c-sharp class in the controllers folder and we call this character controller now before we can start implementing any logic we have to make this thing a proper controller and to do that we first derive from controller base like that this is a base class for an mbc controller without view support since we're building an api here we don't need view support if however we would want to add support for use we could derive from just controller but in our case just make sure to add controller base and to be able to use this class we also have to add a using directive you can either just click control and period for this quick fix menu here or you click the light bulb and then you would also see the suggestion to you to add the using directive for microsoft asp.net core mvc and after that we have to add some attributes and the first one would be api controller this attribute indicates that a type and also all derived types is used to serve http api responses and additionally when we add this attribute to the controller it enables several api specific features like attribute routing and automatic http 400 responses if something is wrong with the model we get to the details when we make use of these features now regarding attribute routing that's already the next thing we have to add actually so below the api controller attribute we add the route attribute like that and you have already seen this we can then add in brackets the string controller this means that this controller can be accessed by its name in our case that would be character so that part of the class name that comes before controller all right let's get into the body of our c sharp class the first thing i'd like to add is a static mock character that we can return to the client so private static then character and then knight as name for our character and that's simply a new character and of course we have to add the reference.net rpg models for that next we finally implement the get method to receive our game character so we start with public and then the return type is an i action result and we call this method simply gets now the return type i action result because this enables us to send specific http status codes back to the client together with the actual data that was requested in this method we can use return okay and then knight and with okay night we sent the status code 200 okay and our mock character back other options would be something like bad request 400 or a 404 not found status code for instance we could choose something like bad requests that would be the status code 400 or not found for 404 but we use ok for status code 200 now now the code is already implemented and i would say we test this so we save this then open the console and enter.net watch run this time because in this case with the help of the watcher when we change the code the app will rebuild itself automatically now while i did this you can already see the arrow here in the terminal or when chrome was opened automatically we see the error here fade to load api definition and back to the terminal we see something like ambiguous http method for action it further states that actions require an explicit http method binding for swagger or open api three point oh so we have to go back to our class here and when we have a look at the get a method and the attribute above exactly there is none now when we compare this to the weather forecast controller here we can see that we could have added an http get attribute but that's not really necessary for the character controller because the web api supports naming conventions and if the name of the method starts with get like we did it here the api assumes that the used http method is also get apart from that we only have one single get method in our controller so far so the web service knows exactly what method is requested still as we now know to help swagger out we have to add the http get attribute but let's go back to chrome one more time and let's try to use the character controller and the get method with the address bar same way we did it with the weather forecast controller before we just have to enter the character controller name here and here is our knight already so i want to make sure with this that this is only necessary for swagger if you're adding some kind of other interface for this web api you wouldn't really need to add this a get attribute but we wanted to use swagger so let's add it anyways we go on top of the method and add http get and now swagger should know that this is a get method we don't see an error anymore and the the website has been reloaded thanks to our watcher and now we see our get method here but there's still one problem now we don't see a new schema and we would expect the rpg character here right so again we have to change something when we have a look at vs code we see that we returned an i action result and you see you have seen already that with chrome that was totally fine you could use it that way but to make sure that swagger knows what we expect here we have to change the return type and for that we can use an action result with the type character and let's save that again and now finally when the app has been rebuilt we see the information we want to see we see our character class here and we also see our rpg class with the values zero one and two so there's still one little thing we can add this thing here 0 1 and 2 may not be exactly what we want so we can change this by configuring the json converter in the enum file so we go back to vs code go to our enum file rpg class and above the definition of this enum we add an attribute which is jason converter for that we need using system text json serialization and then in brackets we say type off and then json string enum converter that's it now the app is rebuilding by itself we have a look at swagger open our rpg class and now we see the strings knight mage and cleric and finally we can test our method here try out execute and here you see the request url and you get our frodo now before we start with a new method let's add another mock character to the controller by replacing this single character with a list of characters because we will implement an additional method to return that list so this would be then a list here of a character we call this characters this is then a new list like that we need another using directive for system collections generic for the list type we can remove our knight here and then we say new character which would be our default character who is frodo and then let's add another one and we call this one sam like that and the attributes should be still the same all right and after that we have to modify our existing get method we now return a complete list of characters so we change the return type here to list character and down here of course we return our characters let's save that and then test our modification with swagger we go to our methods click try it out and then execute and here are our rpg characters we can also see that the expected result here is an array of characters and this is already a good sign because swagger knows what we expect here so this works but now let's add another get method to return a single character so down here we have again an http get method public action results and in this case now just a character we call this method get single for instance and just for testing purposes we return ok and then simply the first character and we save this while our application was rebuilding we can already see that there seems to be a problem with our implementation the terminal says there's a conflicting method or path combination and actions require a unique method or path combination so this means the web api doesn't know which method to use because we have to get methods that's where we have to add routing attributes so let's add one to the first method now we close the terminal and down here we can say route it's the same as above the controller class and then we add the string get all to give this method the route get all so you see with route and then a string we can decide how to get to a particular method and after we save that change building the application works now and it's time to try this out so in swagger we see two methods now get all and the other one and this thing here returns a single character we can try this out again with execute and we get the first one which is frodo and get all here returns all our characters you see that the request url here of the method to receive all characters is a bit different now we use the controller name and then after a forward slash we have to add get all all right but there's still one more thing we can do which is combining the route with the http method and that's quite simple we close the terminal and instead of using the http gets and the route attributes we can simply add the route here together with the http get attribute like that so we just write http get and then in brackets the route we save this and again the result is exactly the same here in swagger now since receiving the first rpg character of a list can get quite boring let's add an argument to our request next to get a particular rpg character we could send the id of the certain character to the web service to do that first we have to add the id to our mock characters in the controller now the default value is 0 so let's just add the id 1 [Music] to sam now it's getting interesting we add a new parameter to the get single method and use the link to find the rpg character with the given id in the list of all characters so first the parameter which would be an integer simply the id and then down here we say characters and then we use first or default the method first or default like that to find the character for that we need a link as i already said we have to add the user directive system link and then with a lambda expression we say c for character where then the id of the character equals the given id which should actually be in lower case like that so with first or default and this lambda expression here the function goes through every character in the characters collection here and then returns the one that has exactly the same id that was given with the method now one more information i want to add here we use first or default because if we don't find the character with the given id here we would return null as result but there's also the function called first and this one would throw an exception if there was not a character found but this is just a side note we used first or default here and we are fine with that okay and now the last thing we would have to do is adding the id also to the attribute up here and we can do that again in brackets and then since this is an argument or a parameter we add id in curly brackets here so this is actually the route we could use the route attribute here as well or we use the combination again and with that we say http get and then the route id in curly brackets to make sure that this is a parameter okay and that's it the parameter in the route has to match the periton name in the function itself that's also quite important of course and now we can test that so we go back to swagger and we already see the new url here with the id parameter and we can click try it out and then 0 would be our default character we click execute and here's frodo and when we now enter id 1 and click execute we get sam back beautiful and to double check you can also see the new request url here it's character and then forward slash and the id of the character you want to get from the service okay so this works just fine and before we implement more methods in the controller let's have a look at the various http request methods we will cover in this course the hypertext transfer protocol or in short http defines as the mdn web docs put it a set of request methods to indicate the desired action to be performed for a given resource to this date we can find 9 request methods in the documentation the most common ones are get post put and delete these are the ones that are covered in this course because you almost always can do everything that needs to be done with only these four let's go over them shortly the get method requests a representation of the specified resource if you're using this request you should only receive data from the web service and not send data to it of course you might want to send certain characteristics to the service like an id or a string and the back end then grabs the proper object from the database but you won't send any objects to the service you have already seen this when you received our rpg characters sending objects to the service in turn would be done with a post request the post method is used to submit an entity to the specified resource often causing a change in state or side effects on the server this means that you might want to add a complete new rpg character to the database for instance post means to put it simply add or create a new object and do whatever you want to do with that object in the backend usually this new object will be stored in a database the put method replaces all current representations of the target resource with the request payload so this is in essence an update of the complete object if you want to change a property of an rpg character let's say just the name for example you would send the whole object to the service and it would overwrite the complete entry in the database of course there can be variations of that process but the standard way is exactly that send an object to the service that already exists and update every property of this object and finally the delete request you note already the delete method deletes the specified resource so you send an id to the service via the url the service usually looks up the corresponding entry in the database and erases it if you rather want to do a soft delete meaning just set the flag so that this entry will not be shown on the client it's actually an update where you would then use the put request method but to make one thing clear nothing works automatically you have to write all the service methods by yourself and define which http request method has to be used by the client you could in fact write a service method that uses gets but then simply delete an object with a given id it's all up to you now how do the kruts meaning create read update and delete operations match with the http request methods in general maybe you know it already to create an object you would use post reading an object is done with a get call updating with put and deleting well with delete of course now that you know the most important http methods let's continue with the web api by creating a controller method to add a new character the idea behind that is that the client in our case the browser sends a json object to the service and the service then creates a new character based on the json data so let's start writing the method we will call the method add character and we will return all our characters so that we directly see the change of our characters list so down here we add a new method again it's a public method of course with the return type action result and then as mentioned a list of all our characters we call the method add character and as a parameter we use our character type and we call this parameter new character now in the body of the function we simply add the new character to the characters list and then again we return the complete list so that we can see that the new character is part of it we add the character with characters add and then new character and then we return okay characters last but not least we add an attribute to this method and that would be now http posed because then we are able to send data to the service it's important to mention that the data or the json object respectively is sent via the body of this request when we send the id to the service earlier we did it via the url now it is done with the body that's a crucial difference all right let's test that now make sure that you run the application if it's not already running with dot net run or dot net watch run and then let's open chrome and have a look at swagger we see a new post method now opening this method we already see an example object we could send via the body and the request type here is properly set to application json because we sent a json object to the web api now let's go to try it out and then for our test we can remove most of the properties and send a new rpg character with just an id and the name to the service and for the name let's use percival and now after hitting execute we see our complete list with the new character percival as a knight now we can also double check this of course in the developer tools with f12 we open them and then the network tab filtered to xhr we can hit execute again and we see our call here and also the result with now another percival but keep in mind we don't store the data persistently for now so when we add another character like we did already we get four in total but as soon as we stop the web service and start it again the list consists of the two initial mock characters and the edit characters are gone currently we are doing all the logic of our web service calls in the controller the thing is if an application or a web service is growing you might want to separate the work into different classes or if you need to do the same work over and over again you don't want to copy your code and paste it into different controllers of course that's where services come in the controllers should actually be pretty simple and just forward data to the service and return the result to the client nothing else to be able to do that we will inject the necessary services into the controller so we will use dependency injection the great thing about dependency injection is that you're able to use the same service in several controllers and if you want to change the actual implementation of a service you just change one service class and you don't have to touch every single controller where you're using this service we'll come to the details when we actually implement this stuff so the client sends a request to the web api the controller takes this request calls the corresponding service method the service then does all the magic like getting an rpg character out of the database for instance and then the result goes back to the controller and then to the client that's it apart from that we can also introduce the idea of data transfer objects or short dtos we already have models but it's common to use these dtos for the communication between client and server the difference is this dtos are objects you won't find in the database this means they won't be mapped models in turn are a representation of a database table when we have a look at our rpg character model later on we will see a table in the database that has exactly the same properties or fields let's say we add the field date created or is deleted that's information the user does not need to see in this case we want to save this information in the database but don't want to send it back to the client that's where the dto comes in we grab the model and map information of the model to the dto there are libraries that do this for us like automapper so we don't have to do this manually apart from that we can also create dtos that combine properties of several models they simply give us more freedom in what we want to return to the client and it's not only about returning data you've already seen the example of creating a new character in that case we could use a dto as well so an object with certain information the client sends to the web service the service then grabs these information and maps them to the actual model we'll use dtos in future lectures so that everything should become clear alright enough with the theory let's build the structure in our project now so let's implement a clean structure now we start with creating new folders so we go to the file explorer here and the first one is the services folder so right click new folder we call this one services and in there i want to create a folder for the character service so let's call this one character service now in that folder we create an interface and an implementation class so right click again and then new c-sharp interface and this one will be called i character service and then we add the implementation class character service now the interface gets three methods and these are in essence the methods you already know from the controller so the first one would return a list of characters and this is the get all characters method and don't forget of course to add some using directives here first system collections generic for the list and for the character we need dot net rpg models then the second method is get character by id which only returns one single character so character get character by id and here we add a parameter which is the id and the last one already also returns a list of characters and this is our add character method methods where we give this method a new character like that and now we go to the implementation class and of course we want to use the interface here so we add it and we see directly an error that says that the interface methods are not implemented and of course we can fix that either by again hitting control and period on your keyboard or you use the light bulb here which is the quick fix menu and simply click implement interface and as you can see the methods have been generated for us but we still have to implement the bodies of course now to implement the bodies we can actually just jump between the character controller and the character service and copy and paste the code but we have to remove the ok method call when we return the result so for instance add character here in the add character controller we just copy this one here and add it here and of course you can already see that we need the characters list but first let's finish the methods back to the controller we want in the get method we want to return all characters so simply return characters and get character by id [Music] where is it here it is we return the character with the given id and we remove the okay function here like that and now finally we copy our list of characters of course like that and down here for the first or default method we add the using directive for system link and this is our service now now regarding the character controller we have to implement some more changes so let's go to the character controller and the very first thing we need now is a constructor and for that we can also use a snippet like prop for the properties in our models and in this case we can use ctor and hit tab to add the constructor and now the parameter we want to add here is the i character service and we call this one character service and again we need the proper using directive in this case now it's services character service and then we can do another thing we can create a new private field for the character service again we hit control and period and then we say initialize field from parameter and then we've got a private read-only variable here and what i like to do is adding an underscore in front of the variable name so we don't have to use this to properly set this value here so now we already inject our new character service into the controller you see this is how we use dependency injection and of course finally we can remove the static list of characters here and regarding the bodies of the methods we have to call this new character service now so the code inside the brackets of the ok statement has to be replaced by the corresponding character service method so regarding get this would be underscore character service and then get all characters then get single would be character service get character by id and then the id and the last one would be character service add character with the new character all right let's test this now in swagger again for instance let's test the method get all and just click try it out and then execute and then we're getting an error that states unable to resolve service for character service i character service while attempting to activate the character controller now the web api wants to inject the i character service but doesn't know which implementation class it should use so we better tell it so we go back to a visual studio code and then we have to go to the startup cs file and in here in the configure services method we have to register our character service and to do that we add services add scoped and then i character service character service which in essence means we want to tell our application that if a controller wants to inject the i character service then the corresponding implementation class would be the character service class and again we have to add the character service reference of course the beauty of that is that whenever we want to change that and use another implementation class for instance we just changed this line and we're done so let's say you want to add another character service called character service 2 you only change this single line and then the application would know as soon as you inject an i character service you want to use the character service to here instead of the character service and with add scoped we create a new instance of the requested service for every request that comes in there are also the methods add transient and add singleton as you can see right here there's add transient and add singleton but we will use add scoped but just so you know and transient provides a new instance to every controller and to every service even within the same request and add singleton creates only one instance that is used for every request now we will only need add scoped now let's take this and go back to swagger again it is reloading and now when we test our get all call try it out and execute we are getting all our characters here frodo and sam and of course we can test this with the other method methods as well let's say we want to get same here execute we get sam and of course we can add a character we can use the default body here because this will be removed anyways when we restart the service and as you can see we now have our rpg character called string all right this works just fine now let's continue with asynchronous calls next what are asynchronous calls and why should you bother put simply with a synchronous call you would give a task to a thread like fetching data from a database and the thread waits for this task to be finished and wouldn't do anything else until this task is done now with an asynchronous call this thread wouldn't wait at all instead it would be open for new tasks and as soon as the other task for instance fetching data from the database is done it would grab the data and return it in our current application this isn't really necessary we have no database calls that take lots of time our tasks are done in milliseconds additionally it's very likely that you have more than one thread available for your application so even if one thread is waiting for a task another thread can do another task but in large applications with lots of users it can really happen that all threads are busy in this case your app won't respond to a request anymore which leads to a terrible user experience and you may even lose users or even paying customers because of this so this can lead to serious trouble and that's why it doesn't hurt to know this and also implement it early in this project now although the methods in the character service won't do anything asynchronous they will later on when we fetch data from the database so let's start off with the i character service interface i have it open already now here the only thing we have to do is add the task type to our return types so simple as that we add task and then the actual type that is returned in brackets and for that again we have to add another reference in this case it's system threading tasks and we do the same for the other methods here so task and the closing brackets and after that of course we have to go to our implementation class the character service and we have to add the task return type here as well like that at the using directive and we have to add another keyword here which would be async to make this really an asynchronous method and we do the same of course for the other methods asynctask and here for the get character by id as well so now we've got asynchronous methods and don't mind the warnings here for now the code will still be executed synchronously but when we add entity framework with database queries later on we will have asynchronous calls all right but now last not least is the character controller again we have to add the task type with the corresponding using directive of course and also the async keyword to every method so we return here a task action result and also we add the async keyword and the using directive the same for the get single method async task and the last one async task for the add character method and then the last thing we have to do in every single method is add the await keyword to the actual service call and that's how we call an asynchronous method and as you can see the warning here at least in the controller is a gone so we had a weight here as well now we are having an asynchronous calls in this method and here as well so the controller is fine now with the asynchronous methods we make asynchronous calls here but regarding the service we will do this later all right that's it we save everything and make test calls again with swagger but they should return exactly the same results again please don't mind that making all these methods asynchronous is not necessary for such a small project but you're here to learn something i guess so that's how you should do it with large applications another practice you might come along in professional projects is to return a wrapper object to the client with every service call advantages are that you can add additional information to the returning result like a success or exception message the frontend is able to react to this additional information and read the actual data with the help of http interceptors for instance and we can make use of generics to use the correct types so let's add that object to our models first in our models folder we create a new c-sharp class and we call this service response now the actual name of the class is service response t where t is the actual type of the data we want to return and then of course we can add some properties so the very first one would be of type t and this is the actual data we want to return for instance the characters then we add another one which i would like to add this is just a flag bool success which by default is set to true so this states if a call was actually successful and then another one the last one already is a string message which is now by default and this one is there to display a message in the front and for instance maybe when you add a character you can add something like character was added or created or if an error occurs you can also display the arrow here of course now similar to the asynchronous implementations we don't really need that now but you will thank me later when you're working on bigger projects where these kinds of things come in quite handy for instance when you catch exceptions in the try catch block a service response like this might help you anyways to make use of our new service response we have to modify the return types of our character service and i character service methods again so let's start with the i character service we simply add the service response class here so this is the service response with the type list character and here we return a service response with a character and here again it's a list of characters and after that again we make the changes in the character service so here it's a task and then service response with the list of the character down here also a service response with list character and then service response character now of course we also have to make changes to the actual implementations of the methods in general we create a new service response object in every method and set the data property accordingly so for instance in the add character we can start with the service response of our service response and this is simply a new service response with a list character we add the new character but then we set the service response data to our characters list and in the end we return the service response now regarding get all characters we can actually copy this thing here and edit we have a service response with the list of characters and we also set the data and then simply return the service response and down here we have a new service response with a character type no list and then we say that our service response data is the actual result so the character we're looking for and then we return the service response here now last but not least we also add the service response as return type to the methods of the character controller so here now it's an actual result of the service response the same here and also of course down here and this helps now to see the proper changes in swagger ui now a first look at swagger already shows us down here two new types a service response for a singer character and a service response for a list of characters we can open this of course and you can see the data the success and the message fields and also here the singer character and here now this is an array or a list you see it in the with the brackets here and then there is the actual character with of course the rpg classes and apart from that when we open a method here like get all we see that the result of the methods look a bit different now the example value here as you can see we have it we have the data with an array of the character here it's the data with only one character and when we try this now and hit execute it's exactly the same we see the data and in here now there's the list of the character and down here let's try this at the proper id hit execute and we see the character frodo in the data field so you see that our characters are wrapped now in our server's response the front end could react to the new properties and provide a smooth user experience with pop-up notifications or something similar instead of presenting complex exception messages in the console or worse a frozen application in case of an error you already heard about them now it's time to use dtos first things first let's create a folder called dtos so new folder dtos and then in there we create another folder called character for our character dtos so all the data transfer objects regarding the role playing game characters as already mentioned the idea behind dtos is that you've got smaller objects that do not consist of every property of the corresponding model when we create a database table for our rpg characters later in this course we could add properties like the created and modified date or a flag for the soft deletion of that character and we don't want to send this data to the client so we map certain properties of the model to the dto which would be the case of returning data to the client but it also works the other way around we already created a new rpg character by only providing an id and a name for instance so why not use a type that only consists of these two properties or other properties we want to use this is even more important when you build a front end that should use a specific type for the creation of a new character at the moment we have these two cases receiving rpg characters from the server and sending a new character to the server so let's create two classes called get character dto and add character dto so in our folder now dto's character we first add get character dto and then another one at character d to regarding the get character dto it should look exactly the same as the character model for now i know it does not seem to make sense but i don't want you to be overwhelmed by implementing anything entity framework related at the same time so let's just copy exactly the same properties for now in the add care in the get character in dto and of course we add the using directive for our rpg class and the add character dto looks a bit different now let's say we want to send every property but the id to the service so again we can copy and paste the properties but we can remove the id from there and also add of course the using director for our rpg class so now that we have our dtos ready we can use them in our controller and service methods and let's start with the interface we go to the i character service class and instead of the character type we can now return the get character dto so get character dto and of course we need another using director for that dto's character and we do the same for the other methods get character dto get character dto and the parameter of the add character method now is of type add character dto and of course we have to make the same changes in the character service so here it's the add character dtos parameter in the add character method and here now it's the get character dto let's just copy this replace also the type here for the service response same in the get all characters method and also here in get character by id and we do the same of course in the character controller so here it's a get character dto the same here and here and the parameter for the add character method is add character dto all right now the character controller has no error anymore but as you can see here visual studio is not happy with that change the types do not really match and that's where we have to map the dtos now with the model it is time for automapper now we could map the objects manually by creating a new instance of the necessary class and then setting every property one by one but the idea behind automapper is that it's doing exactly that for us on the fly but first we have to install automapper of course now there's a package available on nuget.org it's automapper extensions microsoft dependency injection and this is the one we want to install so in visual studio code to install this package we go to the terminal and first we stop the application and then we enter dot net add package and then the name of the package so auto mapper extensions microsoft dependency injection so net add package automapper dot extensions dot microsoft dot dependency injection without any specific version to install the latest package now when the installation is done we should see a new entry here in our project file there it is auto mapper extensions and so on with version 8.1.0 in my case could be of course that there's a newer version available in your case and after that we jump to the startup cs and we go to the configure services method and in here we have to register auto mapper now in the configure services method we register auto mapper with services and then add auto mapper and then type of startup like that and of course we have to add another using directive so we hit control periods and then using automapper now to be able to use the mapping of automapper we now need an instance of the mapper in our service so we go to our character service again and up here now we add a constructor similar to our character controller so we hit ctor that's the character service and now we inject i mapper and call this mapper we add the using directive automapper and here again we can use initialize field from parameter and again add an underscore and now we can use the mapper to set the correct types to the data property of our server's response and let's start with the get character by id method here we can use the map function so we call our mapper and then map and then we first decide in angle brackets which type the value should be mapped to and the parameter of this function is the actual object that will be mapped so we want to map the character to a get character dto and then our parameter is simply the character with the given id now regarding the other changes here in the add character method for instance we want to map the add character dto to a character object so it's the other way around and in this case we say mapper map and then to a character and this is then the new character as parameter and now to map the whole characters list in one line and then give it to the service response we use the select method of link followed by a lambda expression where we map every single character object of the list into a get character dto so instead of just setting the data to characters we say select and then the lambda expression so for every character we want to use our mapper and map the result to a get character dto and this here then is the character and in the end we turn everything into a list like that and of course we can do exactly the same with the get all characters method here all right we save everything and run the application and then we test this with swagger for instance let's use the get all method we had tried out and then execute and then we are getting an error so it seems auto mapper does not know how to map character into a character a dto as you can see right here missing type map configuration or unsupported mapping now you might ask it's called auto mapper so why isn't this working automatically well we have to configure one more thing but then i promise auto mapper is working fine we have to create maps for the mapping and this is organized in profiles you could create a profile for every mapping but let's spare the hassle and just create one class for all profiles for now so back to visual studio again and now in the file explorer at root level we create a new c sharp class and we call this one auto mapper profile and then this class derives from profile [Music] just profile and then we have to add the using directive using auto mapper and regarding the implementation we need a constructor with no parameter so ctor and we can remove the parameter and then we create a map for the necessary mapping and that would be create map and then character and then get character dto and of course we have to add the using directives so that would be our dtos and this now is our models reference all right now let's try this again with swagger we go to the get all methods click try it out hit execute and now we are getting all our characters if for whatever reason it does not work in your case please first try to stop the application with ctrl c like that and then run it again with a.net watch run for instance and then test this again and then hopefully this should work because the thing is that this auto mapper profile class maybe you were already wondering it it's not registered manually by ourselves so this is a convention that automapper uses here it looks for files or classes that are derived by the profile class and maybe this does not work with the watcher for some reason so if it doesn't work in your case please stop and restart the application manually so receiving the list of characters works what about getting a single character you try this for instance with frodo this works as well but what about adding a character now so we try this hit execute and we are getting an error again we can not map the add character dto to the character so we have to add another mapping in the auto mapper profile so let's just add create map and now we want to map it and add character dto to a character we save this go back to swagger and let's try this again and now it's you see everything works now but there's one tiny thing the id here is zero so we already have this id and this shouldn't be the case actually but of course it's because the add character dto does not provide an id that's exactly what we wanted but still let's fix this by generating a proper id ourselves so back to visual studio we go to the add character method here and what i want to do now is i first want to create the character based on the dto and then set the correct id by finding the current max value in the characters list and then increase this value by one so what we can do is we can first say we have our character or let's use the type here so our character is the new character in this case and then we say that the character id is characters max and then with the lambda expression we have a look at the ids of all the characters and then we simply increase this value by one then again we add this character to the character list like that so i first create the character object here then have a look at the maximum value for the id of all the characters increase it by one and then add this resulting character to the characters array saved it and now we can test this again with sweger we go to our post character method try this out hit execute and now without even sending an id the rpg character gets the correct one later when we use entity framework it will generate the proper id by itself all right we are done here i know it was a lot and maybe way too much implementation for such a small project but in large real world applications that's how it's done to modify or update an rpg character we have to add a new method to the i character service interface the character service class and the character controller so let's go to the interface and start here and here now we need an update character methods so the return type first is a task service response and then return let's return the character again to see the results we call this method update character and now we use a new dto an update character dto and we call this parameter updated character and of course we have to add this dto now so let's add it real quick in our dtos folder character we add a new class and we call this one update character dto and we can actually copy and paste all the properties of the get character dto we add the using director for the models and now we can implement this method in the character service we first implement the interface automatically and here is our method now first thing we can add is the async keyboard and then we start with the service response so bar service response would be a new service response with a get character dto and then we try to find the rpg character with the given id of the updated character in the characters list similar to the get method so character character would be characters first or a default and then again in the lambda expression character where the character id is in our case the updated character id and now after that we overwrite almost every property of this rpg character one by one meaning the name hit points strength defense intelligence and the class now we could use auto mapper here with a line like mapper map and then updated character character and also we can then add the corresponding mapping to the automapper profile and i encourage you to try this out by yourself but keep in mind though that with using automapper here every single property will be mapped maybe even data you don't want to be overwritten like fighting statistics we will add later in this course so let's do this manually now we say character name updated character name and our character hit points the updated character hit points character strength is the updated character strength and then a character defense is the updated character defense we're almost done we've got the intelligence and then the last one would be the class and again that's important because i want to make this clear we could do something like mapper map and then updated character to character but again in this case later in this course we will add something like character fights and victories and defeats and in this case this this would be overridden or mapped with default values and maybe you don't want this so that's why we are doing this manually here anyways in the end we set the service response data with now the mapper map and then i get a character dto and then character and in the end we return the service response all right off to the character controller right here we have to add another method of course and now this is a put method so we use http put here and then we add public async task action results with service response with a get character dto the method is called update character of course with an updated character dto called updated character and similar to the other methods we just call our character service with the update character method and then updated character all right it's time to test this with swagger first let's get all our characters for reference so we hit try it out and then execute here's frodo and sam and now let's use our update methods we try it out and we just keep the request body as it is hit execute and then we see the result here so let's double check with receiving all the characters again and we see that frodo is now called a string and he has no hit points no strength nothing it's good that this will be changed again when we restart the application so again keep in mind that every single property has been updated this means the strength defense and so on will be overwritten even though we do not send a value for these properties with the body if you would run another update and leave the rpg class frodo would be turned into a knight in any case because that's the default value so you have to pay attention to how you design your front end in this case do you want to update single properties or all at once by receiving the current values of the character and save them back again even though they did not change alright that was just a side note but now let's try to update a character that doesn't exist just change the id to 2 for instance so here we say id 2 and hit execute and now we are getting a now reference exception object reference not set to an instance of an object because of course the id does not exist we have two options now either we catch that exception with a try catch block or we just check if we find a character in the characters list or we do both so let's start with a try catch block back to visual studio and the character service here we start with the try block after we define the service response so we just add try and let's put this bracket down here and then we add catch exception x for instance and of course at the using system directive like that and in the case of an error we can already set the service response success in this case to false and the service response message to exception message like that that's it already so let's test that again with the put method here try it out and add id 2 it executes and now we get the actual service response with the message object reference not set to an instance of an object now a possible front-end can work with that maybe another message would be more suitable for the user alternatively we can add a slight modification to the character controller so back to vs code and to the character controller here you might have seen that we are still getting a status code 200 okay well a character wasn't found so maybe we can also return a 404 not found response so first let's get the result in our first line and define this as a response like that and then we can check if the response data is actually null and in this case we return not found with the response and in the other case we still return an okay but now with the response here again i haven't saved this yet so when you have a look here we are getting a 200 okay as a result although the character has not been found and now i save this and the application is rebuilding by itself swagger is reloading and now when we try this add id or use id2 hit execute we are actually getting a 404. now feel free to play around with that for instance you do not have to use the message of the service response only in case of an error but about a success message like your character has been saved anyways let's move on and remove an rpg character next to delete an rpg character again we have to make modifications to the eye character service interface the character service and the character controller so let's go to the i character service interface and of course we need a new method task service response let's return the list this time of all characters we call this method delete character and the only parameter we have here is the id now and regarding the implementation we can of course generate our method and then we can actually copy and paste the code of the update character method and paste this here in the delete character method but of course we have to make a few changes the first thing is adding the async keyword and then we have to fix the service response because we return a list of characters and not only one single character so this is a list now and then what we can do is we can change first or default to just first i already mentioned that in an earlier lecture but the difference is that first or default will return null if no matching entity was found and first throws an exception so let's make use of that now if however the character has been found we can simply remove it from our characters list so characters remove character and in the end we want to return all the characters and again we can actually copy this from here for instance we want to return all characters so character select and then we map all the characters and of course this has to be changed as well okay and now already the controller method this is actually a combination of the get single and update character method now we can copy the get signal method here paste it down there and the first change we have to make of course is the method name we call this one delete we can also change the attribute which is now http delete but again with the id parameter and we are returning a list of characters so let's get character in dto and the body is almost the same as the body of the update character method so let's copy this one here paste it down there and then we change the method we're calling the get character method with the i d of course all right when everything is saved we can go back to swagger now in swagger we already see our delete method here and let's try this with id 0 for instance just for reference again we have a look at all the characters 0 is frodo one is sam and when we now use id 0 frodo should be deleted and this is the case because sam is the only character left perfect this works just fine our web api with all crowd operations is done it's time to save the data in a database with entity framework and sql server now if you made it this far you are definitely ready for the complete.net jumpstart course you seem to have what it takes to build a net application with web api and entity framework completely by yourself from start to finish in the next sections of this course you will dive deep into entity framework with code first migration sql server and all kinds of relationships meaning one-to-one one-to-many and many-to-many relationships additionally you will learn how to implement authentication into your application with the help of json web tokens this means users will be able to register log in and create their very own rpg characters and after that you will do more than just crotch by letting the role-playing characters fight against each other even in a death match as a thank you and reward for completing this part of the course i want to give you a pretty sweet discount make sure to use the link in the video description below i'm looking forward to seeing you again in the complete [Music] [Music] course you
Info
Channel: Patrick God
Views: 6,313
Rating: undefined out of 5
Keywords:
Id: hUZHv3tnQUo
Channel Id: undefined
Length: 109min 25sec (6565 seconds)
Published: Thu Apr 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.