Building a Hotel Management System With ASP.NET Core(#1) - Introduction

in #utopian-io6 years ago (edited)

Repository

https://github.com/dotnet/core

What Will I Learn?

  • You will be introduced to building web applications using ASP.NET core.
  • You will learn how to set up and run an ASP.NET core application.
  • You will learn how to think intuitively when designing software system models.
  • You will learn how to architect software systems using the MVC pattern.
  • You will begin creating a Hotel Management System starting with the model entities.
  • You will learn about Microsoft Identity and EntityFramework Core.
  • You will learn how to set up a database connection using database contexts.
  • You will learn about Database Migrations.

Requirements

  • Basic knowledge of C# programming language
  • Visual Studio 2017/ VS code/ Any suitable code editor

Difficulty

  • Basic/Intermediate

Tutorial Contents

Before we begin to get our hands dirty with code, I guess it is essential I give a brief introduction to ASP.NET Core as a whole. ASP.NET Core is a new web framework built by Microsoft. It is free and open source(Yeah, you heard that right, open source). Coupled with all these, it is multi-platform. That is, it can run on windows, Mac and Linux. It has proven to surpass its predecessor as well as competitors like Node.js, in terms of speed. If you are still not sure why you should learn ASP.NET core, I think you should do a little more research on its pros. If you have made up your mind to learn it, well let's proceed!

img8.PNG

Currently, at the time of writing this, the current release is ASP.NET core 2.1. If you have a prior knowledge of ASP.NET MVC5 or ASP.NET core 1.0/1.1, you'll pick this up much faster. However, if you have no knowledge of these, you would still be able to pull through. Although I must mention that without knowledge of C#, you probably won't get anywhere. So I suggest you go acquaint yourself with the language before continuing with this, as this tutorial assumes you already know that.

What We are going to Build

In my own experience, I have found that the best way to learn a language or framework, is to build something with it. That being said, this tutorial series is going to focus on building a Hotel Management System from start to finish, and we are going to deploy this application to a production server, to illustrate the multiplatform support of the framework. Every technical aspect associated with achieving this would be explained as we proceed. I am confident that by the end of this series(that is if you remain faithful), you would have touched every important detail as regards ASP.NET Core.

The Web App we are going to be building will enable us to manage our hotel. Users/Guests would be able to book rooms on our platform. We would be able to manage our inventories and bookings from an admin panel separate from the front-end available to the user. This is the skeleton view of what we are going to be doing. Other features will follow suit in their natural order.

For this first post, I'll go over the project structure of an ASP.NET core app and the basic things you need to know so that you feel at home working with them. Also, we would build our first model-controller-view so that we have a sense of achievement in the journey we are about to begin!

Setting Up your Project

One thing about .NET development in general, that has been a big turn off for many in time past, is the fact that you had to install the full host of the .NET framework and Visual Studio IDE that weighed quite a ton of Gigabytes. Well, good news is, you don't require Visual Studio to work with ASP.NET Core! Isn't that wonderful? You get to build full blown standard .NET web applications without needing to consume a lot of hard drive space needed for Visual Studio.

.NET core now supports CLI. You can download the .NET core SDK from the official website https://www.microsoft.com/net/download/ and you are ready to go.

*Just a quick side note, the .NET core SDK is totally different from the runtime. The runtime is just what is required to run .NET Core. However, the SDK is needed for development and it includes the runtime itself. This is the one you should download on your system in order to develop .NET Core applications.

After downloading the SDK, you can confirm that its installed by typing the command dotnet --version on your command line.
If everything went well, you should see something like this

Capture.PNG

To create a new .NET project, you use the "new" command. Therefore, to create a new ASP.NET MVC project with individual authentication in a location "MyHotel", we would do this

dotnet new mvc --auth Individual -o MyHotel

A fresh installation of an MVC project will be scaffolded for you, which you can work on using Visual Studio Code or any other editor.

Despite being able to build .NET core apps with any editor, there's still a lot of added advantage using the robust Visual Studio IDE. For those that prefer clicking their way through rather than typing commands (like me), visual studio is the way to go, and since I am the one writing this series, I will be making use of visual studio. However, I would not fail to mention important details required for those without VS to follow effectively.

Setting up on Visual Studio

You require the latest build of VS 2017, as previous versions do not support .NET core workload.

Now, you simply go, File --> New --> Project

Then select ASP.NET Core Web Application. Give it a name(Mine is "TheHotelApp"), then select MVC.
Make sure to include Individual User Account Authentication

Capture.PNG

After the scaffolding is done, run the project by hitting F5. You should see your first application. Note that this application is currently running on IIS server as this is the default. Subsequently, when we are done, we will deploy this application using docker.

Capture.PNG

If you have this result, then you have completely set up correctly, thus you are good to go!

Building Our Web App

  • Thinking Like a Programmer
    To begin developing our application, we have to understand the relationship between the different components of the system. In ASP.NET, the various components of the system are represented as models. Models are primarily entities having various properties and relationships with other models. These properties and relationship is what can be leveraged and manipulated by the controllers to present to the view.
    The first step to approaching our system crafting is, thinking of the parts of our hotel that we want users to interact with, and also information from the user we might want to interact with on our own end.

The basic component that is being interacted with in this system is the Hotel Room and of course the entity that is interacting with this component is the User.

Next questions we would want to ask is:
What are the properties of the Room that is to be interacted with?
What differentiates one room from the other?
What are the actions we would want users to carry out on the room?
Are there any information we would want to obtain from the users as regards the room?

Based on these questions, here are some few points that comes to mind:

  • Room Categories
  • Room Features
  • Room Description
  • Room Availability
  • Room Price
  • Room Bookings
  • Review on Room
  • Room Images

Next step is to try to structure all of these in terms of nouns and verbs. This entails classifying these points into properties, separate models and relationships.

The following are the models I came up with:

Room

  public class Room
    {
        public Guid ID { get; set; }
        public int Number { get; set; }
        public Guid RoomTypeID { get; set; }
        public virtual RoomType RoomType { get; set; }
        public decimal Price { get; set; }
        public bool Available { get; set; }
        public string Description { get; set; }
        public int MaximumGuests { get; set; }
        public virtual List<Feature> Features { get; set; }
        public virtual List<Image> RoomImages { get; set; }
        public virtual List<Review> Reviews { get; set; }
        public virtual List<Booking> Bookings { get; set; }

    }

Room Type

 public class RoomType
    {
        public Guid ID { get; set; }
        public string Name { get; set; }
        public decimal BasePrice { get; set; }
        public string Description { get; set; }
        public string ImageUrl { get; set; }
        
    }

Room Feature

  public class Feature
    {
        public Guid ID { get; set; }
        public string Name { get; set; }
        public string Icon { get; set; }
    }

Image

public class Image
    {
        public Guid ID { get; set; }
        public string ImageUrl { get; set; }
    }

Booking

public class Booking
    {
        public Guid ID { get; set; }
        public Guid RoomID { get; set; }
        public virtual Room Room { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime CheckIn { get; set; }
        public DateTime CheckOut { get; set; }
        public int Guests { get; set; }
        public decimal TotalFee { get; set; }
        public bool Paid { get; set; }
        public bool Completed { get; set; }
        public Guid ApplicationUserId { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
        public string CustomerName { get; set; }
        public string CustomerEmail { get; set; }
        public string CustomerPhone { get; set; }
        public string CustomerAddress { get; set; }
        public string CustomerCity { get; set; }
        public string OtherRequests { get; set; }
    }

Review

public class Review
    {
        public Guid ID { get; set; }
        public Guid RoomID { get; set; }
        public virtual Room Room { get; set; }
        public string ReviewerName { get; set; }
        public string ReviewerEmail { get; set; }
        public string Description { get; set; }
    }

User

public class ApplicationUser : IdentityUser
   {
       public string Address { get; set; }
       public string City { get; set; }
       public List<Booking> Bookings { get; set; }
   }

Explanation

As can be seen above, I have 7 models defined. Notice how some points we outlined above, became separate model entities while other fell as properties of the room. "Availability" became a property of the room, while room type is an entity of itself. Also notice how, despite being a model entity of its own, room type is also defined as a property of room. Same with feature, booking, review and images.

Why??

Although room type is a property of room, room type has its own properties. Assuming the room type was to be defined by only a name(single value property), it would have been defined just as availability was. However, room type has variations of its own, which warranted it being a separate class having properties of its own, yet being a property of the room. It has a one to one relationship with the room.

Review, just like room type is an entity and also a property of the room. However, in this case, a room can have many reviews. This is a one to many relationship.

The keyword virtual seen in the models is to enable the said navigation properties take advantage of lazy loading.

The ApplicationUser Model is inherited from the IdentityUser which is a class that is part of the EntityFramework implementation. Here, it is used in our application:

  public class Startup
    {
       .
       .
       .
  services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
     }

These models are not perfect, but they help you get the main idea on how to start building your system. You basically think of all of the things relating to the system you are about to design and write them out! The idea behind going through this process is for you to understand the pathway to the development of any software solution. You shouldn't restrict yourself to these few ideas of mine. I really haven't owned or worked at a hotel company, so my models might be grossly inadequate to fully describe all the details of a hotel system. But for the purpose of this tutorial, we'll stick to these.In the comment section, I would love to see your ideas on some extra properties you think I missed, or models you feel should be part of our system before we continue building it!

Setting Up the Database

Unlike some other languages/frameworks in which setting up databases is quite straightforward, setting up DB in ASP.NET could be quite a hassle, owing primarily to the complexity of EntityFramework, which we will demystify here.

To connect to a database, you require an actual database(to which we are going to be connecting to), a database context class and a connection string.

By default, you should have a localDB already installed in your computer and a connection set up in your project by default, but for this tutorial, I would configure a new database.

A database context is an entry point into your database. It manages all the interactions with your database. Actions are performed against the database via the database context.

The connection string is kinda like a domain that defines the particular address to the database and any details needed to connect with it.

I am creating a new Database using Microsoft SQL Server Management Studio.

Screenshot (373).png

To connect to it using visual studio, go to Tools --> Connect to Database
Enter the neccessary details and click Test Connection. If successful, you can get the connection string by clicking on "Advanced". You should see the connection string.

1Capture.PNG

2Capture.PNG

You can connect to any database of your choice. You just need the connection string.

Add the Connection string to the appsettings.json file

{
  "ConnectionStrings": {
 
    "HotelDb" : "Data Source=JCOOL\\SQLEXPRESS;Initial Catalog=HotelDb;Integrated Security=True"
  }

Next we add it to the ConfigureServices Method of the class Startup.cs using the name of our connection string. In my case "HotelDb".

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("HotelDb")));
               .
               .
               .
        }

Next, we need to add our model classes as Dbsets in our ApplicationContext class. This is to tell the database to create tables for each of the model entities.

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Room> Rooms { get; set; }
        public DbSet<ApplicationUser> Users { get; set; }
        public DbSet<RoomType> RoomTypes { get; set; }
        public DbSet<Feature> Features { get; set; }
        public DbSet<Image> Images { get; set; }
        public DbSet<Booking> Bookings { get; set; }
        public DbSet<Review> Reviews { get; set; }


        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }

Migration

Updating the ApplicationDbContext class doesn't automatically update the database. We have to perform a migration.

Go to the Package Manager Console in Visual studio and type in
Add-Migration InitialTables

Capture.PNG

This adds a migration file with an "Up" method and a "Down" method.

Then to actually update the database, run
Update-Database

If you are using Visual Studio Code or any code editor, you would run the following on the command line:
dotnet ef migrations add InitialTables

Then
dotnet ef database update

Now, check your database, you should see the tables created.
*Note that the migration also creates some tables we did not discuss, such as AspNetRoles, AspNetUserClaims. These are part of the Identity implementation, and we will make use of some of these later on.

Casure.PNG

Github Repo for the tutorial solution: https://github.com/Johnesan/TheHotelApplication

Sort:  

Been a while John. Glad you found your way here once again. Sounds like a software I might implement in the future.

yeah... been busy with a lot of stuff recently. You might as well implement the software now. The tutorial series is going to be dead explanatory.

Hy... Jaff8
Do you need any software for hotel
you can go to the best Recommendations plate from Techimply and go to the hotel management software category.

You can actually create a Hotel management software and list it on SoftwareSuggest. You can reach out to thousands of potential customers for free.

Resteem Promo Offer
Re-steem Post Unlimited For 1 Week
anime.gif
Send 2 SBD or 2 STEEM To @stoneboy - Post Url in the Memo - Your Post Will Be Re-steem to 9500+ followers 2 different accounts.

Note : This offer is only for one time. After that the regular rate will be applied.

Hey @johnesan
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.35
TRX 0.12
JST 0.040
BTC 71539.00
ETH 3603.23
USDT 1.00
SBD 4.75