Bookstore | Using ASP.NET Core 5.0 and MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey welcome on this video we'll be setting up the backend portion of a bookstore we're going to set up a web api using asp.net core 5.0 and we'll be using mongodb as for database i'll be showing you a complete free option to start working with mongodb in the cloud and it's super easy to set up in addition i'll be showing you how to create and use sequencing.net for development purposes this way sensitive data doesn't end up in the source code if you haven't already don't forget to subscribe and let's get started if you don't have visual studio downloaded yet and installed you can visit visualstudio.microsoft.com downloads and you can get the community edition which is free if you're following with an old version of that net be sure to download the latest right now it's 5.0 you can download it.net.microsoft.com slash download and most likely you will also have to update visual studio so keep that in mind we're going to create our web api now so let's open visual studio 2019 and hit create new project let's select asp.net core web application hit next let's set bookstore that web api as a name and pick your location and hit create this window is going to pop up make sure you are in asp.net core 5.0 and you pick asp.net web api and then hit create now that we have the project load up since we created uh the project with the little template let's run it and see what what's in there should take a few seconds and we can see that 5.0 template has swagger by default before like 3.1 didn't have this so if you've seen some of my previous videos um you'll see that i include swagger it makes it a lot easier to test your code and document it and whatnot and right here if we click on this thing there's a weather forecast that comes with the template and then we can do try it out execute and we'll see the response of it and then we see it's 200 and we see all this data and this is just dummy data that they have as a template so we're going to be cleaning this up with our code so let's close this and let's go back to the code this weather forecast is one of those template files i got generated we can just right click on it and delete that now let's head over to this controller directory and open that up as you can see there's a weather forecast controller and this came with the template as well and as you can see there is a http gat endpoint and for now let's get rid of this and let's get rid of vlogger and let's get rid of all this stuff leave it clean and now let's rename this file to books controller books control there you go and let me say yes and save the file right now we have a very simple web api we just have one controller called books this is a special sync syntax for it we're saying the route is going to be controller so this is basically the name of the file excluding controller so it's just going to be books and there's nothing inside of it so we don't have any endpoints yet so let's go ahead and create our first endpoint we're going to create an http get and this http get will get all the books in our database so let's go ahead and do oops we're going to do http get and we'll do public i action result and we'll say get books and obviously we can try to access database in this file and just return all the books but we want to make the quote the code more modular and to do that we have to create a service so we're going to create a new project and that is going to be in charge of you know retrieving all the books from the database and returning that to do this let's right click on the solution and we're going to add a new project this will be a class library let's click next and we can do bookstore that core and hit create let's rename this class one file to book services yes and then let's add another one let's call it ibook services this would be an interface and hit add the service would be the one interacting with database and having the business logic for example adding a new book deleting a book editing a book or you know getting all the books or whatever so next let's define what is a book so let's create that class let's right click on the project and add a new class let's call it just book and let's make that public okay this class will have different properties it will have the name of the book the prize category and author in addition we'll have an id since this is serving as our model for a database so let's do that let's have a public string id get set let's have a name let's have a price category and lastly author okay there are two attributes we want to add let's do id this is serves as the id for our mongodb this is specified that this is the primary key so let's add that and i did alt enter to import that and let's do representation type that object id there you go and this lets us use it as a string so let's save that and let's get rid of the stuff that we don't need and we're done with this file let's head over to ibook services and let's define a we're going to do return a list of sorry a list of books so we do list book and then get books and that's it let's copy this thing let's implement this and we can do alt enter and implement interface so this method is going to return obviously all the books so for now since we don't have the database setup let's just return some dummy data so we can do return a new list of book and we can do a new book here and we can say the name is just going to be like test and the price could be like i don't know 12.99 semicolon here save this and let's head over to our controller so our controller is now ready to call the services and to do that let's quickly add a reference to our bookstore.core so let's right-click on the web api let's hover over ad let's go to project reference and click on bookstore dot core and click ok now that we have the reference we are ready to call our book services and we need an instance of book services and we will be using dependency injection for this fancy injection will automatically solve our dependencies that way we don't have to do like create a new instance be like new book services and pass whatever we need this gets resolved for us so in our construction let's do an i book services book services and let's import this guy okay and then okay it's supposed to be in ibook services and okay it doesn't recognize it because we don't have public yet so let's do public save that file let's come back and there you go we should see it and right here we'll do private read-only ibook services book services there you go and let's assign that it goes to book services all right now we should be able to return on ok and do book services dot get books and let's save that there's one more thing we got to do in order for defensive injection to work let's let's go to startup and right here we're going to do services that add transient and we're going to do i book services and book services let's import that and now let's go ahead and try to run it see what we get all right it's up and right here we see our controller books and we have this endpoint it's a get so let's try it let's try it out and hit execute and we get a response which is the object we created earlier with name test and price 12.99 really cool all right let's go back to code now that we have our first endpoint and we're returning some dummy data i think it's a good time for us to set up our database this way we have everything ready if you already have a database that's perfectly fine the rest of us are going to follow this free in the cloud option if you go over to mongodb.com you can click here and start free or try free and right here we can sign up for make sure that this cloud option is selected and right here we can just sign up for a free account pretty much and then you're going to follow up the steps it's pretty easy and you can just set up a cluster for free they don't ask for a credit card or anything like that so just follow the steps if you don't have an account if you do then just sign in once logged in you should see a page very similar to this one and there's five steps right here and the first one is already scratched out because we already built the cluster when you sign up if you log in because you already had an account and um you you don't have a cluster yet you can just click right here and you can create a new cluster that's the first step and next let's create a your first database user and if you don't see this on your page you can just click on database access and right here we're going to add a new user so we're going to just do the password and i'm just going to name mine my first name and last name and then password i'm gonna click on show and then i'll do like pass one two three and then i'm gonna scroll down make sure we have read and write to any database and we're going to click add user okay so we finished creating first database user next step is to whitelist your ip address and you can click right here or just click on network access and we're going to add ip address and what we can do is allow access from anywhere we can click this or you can do add current ip address if you want your specific one which i encourage you to do this one instead for me i'm just going to do allow anywhere for now since this is just demo and i'm going to click confirm and we can see the status is active sometimes this takes a minute or two so just be patient with it we're going to skip loading sample data for now and next step next thing after that is just to connect to your cluster you can click that or just go to clusters and click on connect and we're going to select the second option connect your application make sure the driver is c-sharp slash.net and we can just do 2.11 or later and just copy this thing there you go this is our connection string that's all we need so now we can just close this and go back to our code all right so now that we have set up our database we are ready to create create some kind of db client that will return us the collection that we want we will have a collection name a database name and a connection string so we need to set all of these up and instead of hard coded inside the code itself we're just going to have these as some environment variables so let's head over to properties and open up launch settings and right here we're going to do a comma and we're going to have a database name and let's call it bookstore tv all right and next let's have some kind of collection so let's call it books collection name and we can just call it books and let's copy this thing and have it down here as well and just save this file okay so now we have the database name and the collection name so we're missing adding the connection string and for that we're going to be using secret manager this provides a way to just set environment variables but they will not be showing up in the source code this way we can just push our code to gitlab github whatever and our connection string won't show up it won't show up there and this is because the connection shade will be stored in your computer locally in some file it's a json file actually so it's not encrypted this is not a uh you know a safe way to you know to store passwords and whatnot this is just for development purposes so keep that in mind with that said let's set up our secret this is pretty easy to do this is not complicated there's only two steps we gotta enable the secret storage and the second step is to set our secret which in our case is just our connection string so let's head over to tools and hover over package manager and package manager console click on that and the first step is to enable the secret storage so let's do net user secrets init hit enter and it doesn't know what project i'm talking about so you can do up arrow minus p which is minus minus project and you can do bookstore that web api now that we have enabled secrets remember to copy this thing back to our code we're just going to do net user secrets and we're going to do set and we'll do connection string and we'll paste that in here and my password was pass one two three pass one two three and the database name was just this guy so i'm just gonna use that we can click here package manager console let's set the project bookstore that web api and hit enter and it's successfully saved connection string nice i'm going to double check this is to win.net user secret list minus p bookstore web api and we can see we have connection string and we have this connection string cool let's now create a class to map these environment variables this way we can just use them throughout our application pretty easily so let's right click on bookstore.cor and hit over add go over add and hit class and let's call it bookstore db config let's remove all this stuff that we don't need and let's mark it as public and let's do three properties it's gonna be string this would be a database uh underscore name we get set we'll have books collection name get set and lastly we'll have our connection string makes this one capital n so as you can see database name will have our database name books collection will have the collections name and connection string will have just a connection string and this has the same kind of format as the names that we put here capitals didn't really matter but basically they're going to get mapped like whatever body this has that class will have it this value same for the connection string in order to finish this we have to go to startup and right here we gotta do services that configured we'll do book store tb config and we'll pass in configuration there you go all right save that file okay so now we're ready to create some kind of class that will be responsible for creating our mongol database client so let's right click on bookstore.core and hover over add to new item and first let's create an interface we can call it i db client let's make it public and this will have a i collection book get books collection there you go and okay if you're in windows you can do alt enter and we can install this package mongodb.driver okay and now it should be here there you go save that now let's create another class this one we're going to be calling it uh just db client all right let's remove this stuff let's make it public and this class is going to implement idb client okay so this will return the books collection first we have to do a little bit of setup before so we'll have a constructor this would be db client and this will take eye options and this is a way to inject the bookstore dbconfig file that we created earlier into this class so options bookstore db config file and then i'll do bookstore db config let's make sure we install the package microsoft that extensions that options all right and we have this now and here we're going to do first we're going to create the client then out of that client we're going to have our get our database and from the database we're going to get our collection so far client equals new client and we're going to pass in the bookstore tv config and then we're going to get the value out of that that connection string so now that we have our client we're going to get the database which goes to client.getdatabase and we pass in the config value that database name and lastly let's get the collection so let's create a variable up here read only i collection of type book and i'll just call it books and i'll say that books is equal to database that get collection type book and we pass in the config that value that books collection name once we have that this is pretty easy to implement all we got to do is do return books or we can do the short syntax and just do a little arrow here and just do books save that now we can head over to startup and register db client as a singleton so let's go over to startup and right here we can do services that singleton and we can do itb client db client this allows us to inject idb client using dependency injection and we'll have only one instance of idb client through the life of the application now that we have our client set up let's head over to our book services and try to inject db client so we'll create a constructor here book services and we will inject idb client space okay and in here we can get the the collection and let's create a variable for it so we can do private read only i collection book books and let's import this and we can say that books equals to this and now instead of returning this hard-coded list we can do books dot find and we're going to get the book and pretty much just return true and do a list of that save that and we can even do the simplified version there you go this makes it a little nicer and let's try running our app right now see what happens all right so let's test this let's say try out and we're expecting to get a 200 so that is it's a successful request but we're not expecting to get any actual data back or anything like that because we haven't even set up a collection yet so let's hit execute there you go we get a 200 success and it's just an empty body so we can do we can create a collection and a database by going back to the site and doing manually but i think it's better if we can just create it in our code so if we just create a post and we just create a new book the database and the collection should be automatically created for us so let's go back to the code and add that okay so back at the code we want to create an endpoint to add a new book so let's go back to our controller and this will be an http post an action result and this would be add book and this will get a book and then we're going to return let's return okay with a book for now but we'll have to return it to a one since we're creating something new in the database but for now this this works so we can do book services that and then we'll have to add a method here let's call it add book and passing book and let's create this method so if we go back to the let's save this real quick and if we go back to ibook services we can just create one here book add book and this will be book book save that and if we go back to the implementation let's implement that method and we want to do books that insert one and we're going to insert that book with return book there you go let's run the app again all right so now we have get books and post books let's try posting a book try out let's get rid of this id since we don't need this and we call this this is a test 299 action me all right execute and we get a 200 this is a response body we have this id got created with this name price category and author and now we go to books and we retrieve all the stuff in our database we have the object we just created cool and if we were to go back here we can close this and go to collections and now we see that we have a bookstore db and books and this is our result so basically the db got automatically created for us and the collection as well back at our code let's create an endpoint to retrieve a book by its id and update the ad book to return a 201 if a book gets added or created instead of returning it to 100 as of right now so let's do an http get inside here want to get the id and let's set a name for it okay and then we'll do public by action result get book and we're going to get an id and we're going to be calling book services that get book which we haven't created yet but we're about to and then this will return the book so we just return okay so let's go ahead and create this so if we go to interface first we can do book get book and it gets an id if we go back here let's implement the interface and all we got to do is return books that find where the book.id equals that id and we'll get the first one save that and now this should be able to just return the book by its id let's go back to our controller and let's fix this adding a book response so whenever we add a book we'll have to return a 201 instead of our 200 and to do that we're gonna have a created at route and we're gonna name that route we're gonna cut we're gonna call it getbook and then we'll say this is a new id equal to book dot id space here oh there's an extra space let me get rid of that there you go and then at the end let's just do book save that and now let's try to run it okay let's test this out so if we click on try it out this is the one we've been getting if we copy this id and we go to get book and we paste that in the in there and execute it we have a response nice let's test out creating a new book or adding a new book and make sure that we get a 201 as a response instead of 200 so we can do rich dad poor dad 1655. this would be like finance and author let's do robert t kiyosaki and let's hit execute and we get 201 sweet so if we now go to getting all the books now we have two books and if we try to get this one by this id this one shows up pretty cool okay next let's delete a book and we can start by this time by the interface just to mix it up and then this will be void delete book and we'll pass an id implement interface this will be books that delete one or the book that id equal the id and let's go back to controller let's add an http delete and we're going to pass in an id delete book pass in your id and right here we can do book service services that delete book pass in the id and then we can return a no no content all right save that let's run it we can try getting all the books to get the id first all right let's do the first one go to delete try it out pass in the id execute and we got a tool for no content sweet okay back at our code let's implement the last endpoint this example will be used to update a book and let's start off with the interface once again so this will return a book we say update book and we're going to pass in a book back to services let's implement the interface and the first thing we should do is make sure that that book exists so let's call getbook is this method we implemented right here and if it doesn't exist this first we'll throw an exception let's pass the invoke that id so if it does exist let's do a replace the id matches to book that id then replace it with book and return book nice let's head over to controller down here we can do http put we can do public i action result update book and we're going to pass in a book and then we can just return on ok with book services dot update book and we pass in book save that and let's run our api let's hit the get endpoint first just to get the id and honestly we can just copy the whole object so we can just go to put try it out paste that in there and say we change this to 8 99 we hit execute we should see that we get a response with this so now the object the book got updated to a99 since we say we changed this id to seven which doesn't exist and we hit execute and as you can see we got an exception you can have it return different status quotes but for right now this is returning a 500. and with this we have reached the end of this video if you found it helpful and you learned something from it please hit the like button and don't forget to subscribe if you haven't already y'all have a great one and i'll see you on the next one
Info
Channel: Asiel Alvarez
Views: 45,503
Rating: undefined out of 5
Keywords: ASP.NET Core, .Net Core, .Net Core 5.0, Dot Net Core 5.0, FullStack, Full-Stack, MongoDB, Non sql, non relational database, Migration, Swagger, WebApi, .Net Core Web API, ASP.NET Core Web API, Endpoints, Full Stack Development, Application Development, Full Course, Computer Science, C#, C# 9.0, Http Requests, Visual Studio, mlab, Secret Manager, secrets
Id: MNepwvCcKXA
Channel Id: undefined
Length: 37min 22sec (2242 seconds)
Published: Thu Dec 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.