Pros and Cons of using Windows VPS for your Projects

The choice of operating system for a virtual private server depends on the needs of a particular company. But if you are looking for a reliable, efficient, and flexible solution to host your web projects, in most cases it will be Windows VPS. In this article, we'll analyze why many people prefer Microsoft solutions, and what benefits and limitations you can expect if you decide to buy a Windows VPS .

What is a Windows VPS and what it is used for?

Windows VPS is a virtual private server that uses Windows Server as the underlying operating system. Windows VPS functions effectively as a cloud server with elastic scalability. This means that you get a dedicated server resource that you can use as you see fit, and you can easily add resources as needed.

Typically, a private server under Windows is used in many segments, it can be hosting websites and applications, databases, mail servers, and game servers. The main advantage is that the system allows you to run programs and scripts that require a Windows-compatible environment. For example, you can use Windows VPS for hosting ASP.NET, .NET Core, SQL Server, and other Microsoft technologies.

The advantages of using a Windows VPS

The main reason Windows VPS is preferred is that the system is developed by the largest player on the market. Microsoft is a multi-billion dollar company that invests huge budgets in its products. Other vendors do not have the same amount of resources, it is difficult for them to compete at this level. Consider the other advantages of using a Windows VPS.

Ready to launch product

Windows VPS requires no additional configuration or software installation. You can start working with it immediately after purchase and get full control over the server. You can choose the desired version of Windows Server (from 2008 to 2022), that best suits your needs and requirements. 

But most importantly, the user gets access to a remote desktop with an intuitive graphical interface. There is no need to program anything from the command line, as is required in UNIX-based systems.

Integration with other Microsoft products

The system easily integrates with other Microsoft services such as Office 365, Azure, and SharePoint. You can install additional Windows software such as IIS, Active Directory, and Exchange Server. 

You get a single, seamless software interface where you can use cloud services from Microsoft for data storage, analytics, machine learning, and other purposes. It is possible to synchronize the server with other Windows devices and applications, such as Outlook, OneDrive, and Skype.

Support

Microsoft understands what customers want and for 20 years Windows Server developers have eradicated almost all the technical problems associated with the product. 

With VPS on Windows Server, you don't have to wait long for vulnerabilities to be fixed. The company promptly and regularly releases security updates and patches, which are installed automatically. With open-source systems, you achieve the same result only if the product has an extensive community.

ASP and ASP.Net compatibility

Windows VPS is ideal for developing and hosting web applications based on ASP and ASP.Net Core – popular technologies from Microsoft. You can use different programming languages like C#, VB.Net, and Python and connect different databases: SQL Server, MySQL, Oracle, and others.

Disadvantages of using Windows VPS

Windows Server is a great software for hosting and other tasks, but not perfect. The system has some limitations which may be critical for a certain group of users. 

The first is the high cost. One of the main disadvantages is that Windows VPS is usually more expensive than Linux VPS or shared hosting. This is because VPS requires an additional license for Windows Server, and it is included in the cost of renting a server. Add to this the fact that most tools and software are paid Microsoft products, and using a Windows VPS will put a noticeable strain on your budget. 

But note that the high cost is a relative indicator. You can almost always find free alternatives to Microsoft programs. And due to the stable operation of the server and quality support in the long run, you can save thousands of dollars. Windows servers are much less likely to crash and are easier to resume operation than other operating systems.

Another disadvantage of using a Windows VPS is problems with performance and compatibility. You may encounter conflicts between different versions of Windows Server or between the OS from Microsoft and other operating systems. For example, it is possible to have problems when running Windows Server 2022 on old hardware, or when trying to connect to a Windows VPS from a Linux computer.

But if you rent a VPS server, such cases will be rare. Most likely, the hosting company has already taken care of installing modern performance equipment and configuring compatibility settings. 

Some programs or scripts may run better on a Linux VPS than on a Windows VPS since they were originally designed for a Linux-compatible environment. For example, you may have problems running PHP or MySQL on a Windows VPS, since these technologies are optimized to run on Linux. Windows VPS is not suitable for developing and running web applications in Ruby on Rails or Node.js, as these technologies work better on Linux VPS.

How vulnerable is a Windows VPS to attack?

Among many users, there is an opinion that Linux VPS is preferable in terms of security, and there is a logic in that. The dominance of Windows on the desktop market has made Microsoft systems a prime target for hackers. But Windows has a lot of tools to protect your server from hackers.

You can protect your data from unauthorized access or loss through a variety of security measures, such as

  1. Firewalls. Allow you to control incoming and outgoing network traffic and block unwanted or dangerous connections. You can use both the built-in Windows Firewall and third-party tools, such as Bitdefender or Norton, to protect your Windows VPS from hackers, viruses, or other attacks.

  2. Intrusion detection and prevention systems (IDS/IPS). These are programs or devices that analyze network traffic and detect and prevent hacking attempts or other anomalous activities. You can use IDS/IPS at the operating system level or at the application level.

  3. Data encryption and SSL certificates. You can use BitLocker or VeraCrypt to encrypt disk space or Let's Encrypt and Comodo to obtain SSL certificates.

Of course, Windows VPS allows you to create real-time backups and regularly scheduled backups.

Conclusion

Windows VPS can be a suitable solution for your projects if you want: 

  • run programs or scripts that require a Windows-compatible environment;

  • have full control over your server and configure it as you wish;

  • get high performance and reliability of the server.

Windows VPS provides flexibility and scalability, data security, and ease of management for web projects. However, Windows VPS has some limitations. Therefore, you must carefully choose Windows VPS for your projects, first of all, based on usage scenarios. You should also consider other parameters such as server resources, Windows Server version, and purchase or lease costs. 

How to Increase EF Core Performance for Saving Multiple Entities?

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to Increase EF Core Performance for Saving Multiple Entities? EF Core works well for simple CRUD operations but for saving multiple entities EF Core provides poor performance. So, today we will use a third-party EF Core extension named "Z.EntityFramework.Extensions.EFCore", designed by ZZZ Projects, which will increase the EF Core performance significantly. I will be using a BulkSaveChanges Method of this library which is specifically designed for saving bulk data in an SQL database.

ZZZ Projects is a trusted company and has designed numerous .NET libraries, a few having downloads in millions. So, you can completely trust this extension library.

  • Here's a video for this tutorial, which will give you a practical demonstration of this project i.e. How to add this Library to your project and how to use this extension method BulkSaveChanges:

Before starting with the actual process, let's first have a look at What is EF Core?

What is EF Core?

EF Core is an Object Relational Mapper(ORM) and is used as a bridge between the ASP.Net Core application & its database. Thanks to EF Core, now there's no need to write complex SQL queries for database-related operations, instead, developers can easily perform all database CRUD operations in C# language(using EF Core). Although designed by Microsoft, but EF Core is a separate module and we can add it to our .NET application from the Nuget library.

Low Performance of EF Core

  • ORM(i.e. EF Core) provides a simple instructions-set for database CRUD operations and proves very friendly to developers, but it has few drawbacks as well.
  • One of the main disadvantages of EF Core is its low performance, which not only slows down your application but also increases the database interactions(cloud providers may charge extra).
  • Moreover, as the number of data(you want to save in the database) increases, the EF Core performance decreases.

EF Core Performance for multiple Entities

  • In a professional .NET application development, there come many scenarios where the developer needs to save multiple entities in the database i.e. user notifications, real-time messages etc.
  • When multiple entities are saved using EF Core, it doesn't save them in a single SQL session.
  • Instead, it takes multiple round-trips to the database, which increases the overall time for the data-saving process.

So, now let's have a look at How to increase the EF Core Performance for multiple entities by using BulkSaveChanges(provided by Z Extension), instead of SaveChanges(provided by EF Core):

What is BulkSaveChanges Method?

  • BulkSaveChanges is a simple function, automatically generated by EF Core Extension Library and is used for saving multiple entities in the database.
  • BulkSaveChanges increases the performance of EF Core by 3 to 4 times and its performance is exponential to a number of entities.
  • First of all, you need to download this project designed in ASP.NET Core:
Download Asp.Net Core Project
  • Open it in Visual Studio and first run the Migration commands for setting up the SQL database.

How to add EF Core Extension Library

  • If you check the NuGet packages in the above project, you will find these four packages installed in it, shown in the below figure:
  • You must be familiar with the first 3 NuGet packages, as they are used to add EF Core libraries in the .Net project.
  • The fourth one is the NuGet package of EF Core extension Library, designed by ZZZ Projects.
  • If you click on the Browse tab and make a search for "Z.EntityFramework", you will find results, as shown in the below figure:

Methods offered by Z Extension Library

  • After adding this NuGet package of ZZZ Projects, its methods will become readily available under the instance of DbContext class.
  • I am going to discuss BulkSaveChanges Method only(in today's lecture) but it has a wide range of methods for improving the performance of DBContext class, used in different scenarios, depending on requirements.
  • Here's a list of few other methods, offered by this EF Core Extension Library:

BulkSaveChanges Method to improve performance of EF Core

Now, let's have a look at the implementation of the BulkSaveChanges Method in our Asp.Net Core Application:
  • In the Models folder, open the SubjectRepository.cs file and here you will find two methods, named:
    • Add1() Method: It will use the default SaveChanges() Method of EFCore.
    • Add2() Method: It will be using the new BulkSaveChanges() Method of EF Core Extension Library.
  • Both of these methods are shown in the below figure:
  • As you can see in the above code, it's too easy to use the BulkSaveChanges() method, as it's called on the same instance of DBContext class, on which I have called the default SaveChanges() method.
  • Moreover, I have placed a stopwatch function around these methods to calculate the time taken by them, for saving 5000 entities in the database.
Now, let's save 5000 entities using these two methods, and look at the results:

SaveChanges vs BulkSaveChanges

  •  I have tested these methods three times each and created a comparison table.
  • In each of these testing trials, I have saved 5000 entities in the underlying SQL database.
  • Here's the result of the comparison, SaveChanges vs BulkSaveChanges: (all these readings are in milliseconds)
  • As you can see in the above comparison table, the BulkSaveChanges method is 3 to 4 times faster than the SaveChanges method.

For a practical demonstration of this project, watch the above video, where I have completely demonstrate How to add this Z extension Library to your project and how to use the BulkSaveChanges method to improve the performance of EF Core. So, that was all today, if you have any questions, please ask in the comments. Thanks for reading!!! :)

DbContext Class in Entity Framework Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at what is DbContext Class in Entity Framework Core. It's our 17th tutorial in ASP.NET Core series. In our previous tutorial, we have discussed Entity Framework Core in detail and have also installed it in our web application. So, now we need understand how to work with Entity Framework Core and for that we have to look at its classes & functions. So, today we will discuss one of its class named DBContext in detail:

DbContext Class in Entity Framework Core

  • EF Core contains an important class named DbContext, which is mainly responsible for communication between Database & software objects.
  • We communicate with our database using this DbContext class and we can also map our fetched data to software objects i.e. properties.
  • So, in order to use this DbContext class, we have to create a new class and then inherit it from DbContext Class.
  • When we inherit our new class from DBContext Class, then we will be able to call all its members from our new class.
  • So, I am going to create a new class in Models folder, as Models are going to communicate with the database.
  • I have named this class TepDbContext and have inherited it from DbContext class, as shown in figure on right side.
DbContextOptions class in EF Core
  • DbContextOptions class in EF Core contains all the configuration information about database i.e. database name, database provider, database connection string etc.
  • We need to use DbContextOptions class along with DbContext class, so let's create a Constructor of DBContext class, as shown in below figure:
  • You can see in above figure that I have created a constructor of TEPDbContext class and then instantiated DbContextOptions class as a parameter.
  • After that, I have provided TepDbContext as a parameter inside < >, thus this option class is applied to our newly created TepDbContext class.
  • Next, I have created its object titled options and finally called the base constructor from DBContext class and provided this options object as a parameter.
DbSet Property in EF Core
  • So far, we have discussed two classes from EF Core and now it's time to have a look at this property in EF Core titled DBSet.
  • DBSet Property is used to map the data from software objects to underlying database.
  • Currently, we have just Engineers.cs file, which has the data properties, that need to be stored in our database.
  • So, let's create a new property in our TepDBContext class named DBSet, as shown in below figure:
  • As you can see we have created a new DbSet Property of type Engineers and given it a name DbEngineers. ( We will use it later )
So, we have successfully created our TepDbContext class and have updated it, so, now its time to register this newly created class with dependency injection of ASP.NET Core.

Database Connection String in App Settings

  • We need to provide authentication settings for our database, which we will add in appsettings.json file, so that we could use it anywhere in our project.
  • I am using MySQL database and thus provided its connection string, as shown in below figure:
  • You can see in above code that I have created a new section named ConnectionStrings and inside it, I have create DbConnection variable and have assigned DB connection string to it.
  • In the connection string, I have first provided the server i.e. localdb and then provided name of the database i.e. TepDB and finally I have declared it a trusted connection.
  • This MSSQLLocalDB is already available in Visual Studio and we will discuss it in detail in our coming lectures.
  • When we upload our web application on a real server then we will change these server settings but for now, we will use localdb available.

Dependency Injection for DbContext class

  • We have studied Dependency Injection in ASP.NET Core in detail, so now let's register TepDbContext class & provide SQL database connection string using Dependency Injection
  • For that, open your startup.cs file and in ConfigureServices method, on IServicesCollection instance, we have called AddDbContextPool method, as shown in below figure:
  • We have also specidified that we are using SQL Server & have provided the database connection string as well, I have placed a red boundary across it.
  • In order to get the Connection string from appsettings.json file, I have injected IConfiguration using Constructor Injection and have placed a green boundary across it.
  • So, our TepDBContext class is now registered with ASP.NET Core and we have also specified the Database provider & Connection String.
So, that was all for today. We have completed all our settings for database but we haven't yet created it. So, in our next lecture, we will see How to Create Database using EF Core Migrations. Till then take care & have fun !!!

Introduction to Entity Framework Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at detailed Introduction to Entity Framework Core. It's our 16th tutorial in ASP.NET Core series. So far, we have covered the the MVC architecture and few concepts related to object oriented programming and now we are ready to get our hands on Databases. So, today we will cover data handling in detail, which is done by Entity Framework Core in .NET Core applications. So, let's first understand this Entity Framework Core:

Introduction to Entity Framework Core

  • Entity Framework Core ( normally called EF Core ), designed by Microsoft, is an open source, flexible, extensible, lightweight and cross-platform framework, which is used for storing & retrieving data from database.
  • EF Core creates a bridge between Objects in Programming & relational databases, thus referred as Object-Relational Mapper. ( O/RM )
  • In simple words, EF Core acts as a middle layer between our .NET Core Application & database.
  • EF Core is written from scratch for .NET Core, but also works with standard .NET 4.5+, and is an enhancement of ADO.NET.
Why need Entity Framework Core ?
  • If you have worked on any database i.e. SQL, MYSQL, Oracle etc. then you must have the idea about query strings.
  • In order to send or request data from these databases, we need to use query strings, which are normally quite lengthy and prone to errors.
  • In order to avoid this direct interaction with databases using query strings, we have many third party frameworks which handle these underlying query strings themselves and provide programmers with easy programming methods to deal with the data.
  • Entity Framework Core is an official data handling framework designed by Microsoft and works perfectly with ASP.NET Core.
  • EF Core supports a wide range of relational database using third party libraries called database providers, we install these libraries as NuGet Packages.
  • For example, if I want to work on SQL database, then I will install SQL NuGet Package, we will install one later.
EF Core Approach
  • We can use two approaches in Entity Framework Core, which are:
    • Code First Approach
    • Database First Approach
  • We have very limited support available for "Database First Approach" for now and we use this approach, when we already have the database. ( will cover it in future lectures )
  • In Code First Approach, we design our database from scratch and using dbContext class, we transfer data from  app to database & vice versa.
EF Core Package
  • Now we need to select the type of database i.e. SQL, MYSQL, Oracle etc., which we want to use for our web application, so I am going to use Sql Database.
  • In order to use SQL Database with EF Core, we need to install its NuGet Package called Microsoft.EntityFrameworkCore.SqlServer.
  • This NuGet package is actually the Database provider, so if you are using any other database i.e. MYSQL, then you need to install its NuGet Package. ( We will install one in the next section )
  • SQL Server NuGet Package has a dependency on EF Core Relational Package called Microsoft.EntityFrameworkCore.Relational.
  • Relational package contains the functionality, that are common in all relational databases i.e. SQL, MYSQL, Oracle etc.
  • This relational package, in turn has a dependency on Main EF Core Package called Microsoft.EntityFrameworkCore.
  • That's the main base EF Core NuGet Package that will enable EF Core on our web App.

How to Install Entity Framework Core

  • Now, let's install EF Core on our web application, so right click on the Project's Name in Solution Explorer.
  • Now click on Manage NuGet Packages, and NuGet Package Manager will open up.
  • In the Browser tab, make a search for EntityFrameworkCore.SqlServer and you will get results, as shown in below figure:
  • You can see in above figure that first one appeared in the search, is our required NuGet Package, so let's install this one.
  • As this SQL NuGet Package has a dependency on Relational, which in turn has dependency on EF Core, so when we install SQL Server Package, the other two will automatically be installed by the Visual Studio.
  • So, click on the Install Button and then accept the terms and this SQL Server NuGet Package will be installed.
  • After complete installation, you need to open Dependencies in Solution Explorer, as shown in figure on right side.
  • You will find Packages in Dependencies, so open it up and inside it you will find our SQL Server NuGet Package.
  • Expand this SQL Server Package and you will find its dependencies i.e. Relational etc.
  • So, we have successfully installed Entity Framework Core for SQL Database on our web app.
So, that was all for today. We have successfully installed EF Core on our web application but we haven't yet created our SQL Database. In the next video, we will have a look at DbContext Class in Entity Framework Core. Till then take care & have fun !!!

Form Validation in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at Form Validation in ASP.NET Core. It's our 15th tutorial in ASP.NET Core series. In our previous lecture, we have created a Registration Form for our engineering website. But we haven't added any validations on the submitted data. So, even if users don't fill any boxes and just hit the Register Button, a new user will be created without any personal info. So, today we will place some checks on these text boxes to validate the user submitted data. So, let's get started with it:

Form Validation in ASP.NET Core

  • Validations in ASP.NET Core are available in the form of attributes & Tag Helpers.
  • Validation Attributes are applied on Properties in Model classes and validate the user submitted data.
  • Validation Tag Helpers are used in Views and provide validation errors to the users.
  • So, let's add few validations to our registration form and show errors, if inappropriate data is submitted.

Validation Attributes in ASP.NET Core

  • ASP.NET Core has many builtin Validation Attributes to verify the incoming data, few of them are as follows:
    • [Required] : Value is required.
    • [Regular Expression] : Value must match the regular expression provided.
    • [Compare] : Compares two properties i.e. Verify Email.
    • [Range] : Value must lie between specified range.
    • [MinLength] : Specifies the value's minimum length.
    • [MaxLength] : Specifies the value's maximum length.
    • [DataType] : Value must be of specified datatype.
  • So, let's apply few of these Validation Attributes on our Properties in Engineers.cs file, placed in Models folder.
  • We have already linked these properties with text boxes using asp-for Tag Helper.
  • So, open this file & in Engineers class, place these validation attribute before properties, as shown in below figure:
  • As you can see in above figure that before Username property, I have used two validation attributes i.e. Required & MaxLength.
  • I have set the MaxLength to 50 and have also added a custom ErrorMessage.
  • On the Email property, I have used Required & RegularExpression, this expression will verify the email format.
  • On the FullName property, I have used Display attribute (it's not a validation attribute), and changed the name to "Full Name", it will change the label of this text box.
  • Moreover, I have also made my enums properties null-able, as you can see I have placed ? sign infrom of DeptEnum & UniEnum. ( We will see later why null-able)
  • We have added the validation attributes on our properties and now let's place a check in our Home Controllers class using builtin validation property.
Check if Data is Valid
  • So, open you HomeController.cs class placed in the Controllers Folder.
  • In HomeController class, we need to place validation check on the Registration action method of [HTTPPost] type, as this method is going to execute on pressing the Register button.
  • As you can see in above code, I have placed an IF loop and have placed a Boolean property in it called ModelState.IsValid.
  • This Boolean property will return TRUE, if there's no validation error & will return FALSE, if there's any validation error appeared.
  • So, if it's true then I have added the submitted user data and displayed it in Info link by redirecting it to Info action method and if its FALSE, then simply returned the Registration View itself.
  • One more thing to note here is that I have changed the return type of action method to IActionResult, as it contains both RedirectToAction() & View() result types.

Display Validation errors in ASP.NET Core

  • Now it's time to display validation errors on the form itself, so now open your Registration.cshtml View file.
  • Below each textbox, we need to add a <span> element, as shown in figure on right side.
  • Inside this <span> element, I have use Validation Tag Helper named asp-validation-for and this Tag Helper is taking Username as a value.
  • So, if there's any validation error appeared for Username, then it will be displayed here.
  • Let's add this <span> element below all the textboxes, as shown in below figure:
  • You can see in above figure, that I have placed <span> element containing asp-validation-for Tag Helper, below every input field.
  • One more thing to note here is that I have added an option element Please Select, in both of my <select> tags, I have encircled them in above figure.
  • Now let's run our application, and without entering any data, hit the Register button, and we will get validation errors, as shown in below figure:
  • You can see in above figure that we are getting the Validation Error Messages for each component and at the end we have the summary of Validation errors.
  • Moreover, for our Select boxes now we have a default option "Please Select", that's why we are getting Validation Errors for them as well, as now their value is null.
  • If we select any option, then it will get value from the respective enum but in case of Please Select, its null-able and giving us Validation Error.
  • We haven't added any Bootstrap design on these elements, as I want to keep things simple for now. ( We will design them later )
So, that was all for today. I hope you have enjoyed today's lecture. In next tutorial, we will have a look at detailed introduction to Entity Framework Core. Till then take care & have fun !!!

Create a Registration Form in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to Create a Registration Form in ASP.NET Core. It's our 13th tutorial in ASP.NET Core series. In our previous lecture, we have seen How to use Tag Helpers in ASP.NET Core and have also discussed link, image & environment Tag Helpers. Today, we will have a look at Form Tag Helpers and with their help we will design a simple Registration Form in ASP.NET Core. It will be a quite lengthy tutorial so if you got into any trouble, then ask in comments. So, let's create our Registration Form:

Create a Registration Form in ASP.NET Core

  • Let's create a new action method named Registration, in our Home Controller class, as shown in figure on right side.
  • I have also returned a View, so let's create a new Razor View in Views > Home folder and give it a name Registration.cshtml.
  • This View is going to execute, when someone will open up this link: http://localhost:61745/home/registration
  • So, let's create our registration Form in this Registration View file, as shown in below figure:
  • It's a bit lengthy code, so let's understand this code, part by part. I have also added the Engineers.cs Code in red box for better understanding.
  • I have first used @model directive and included Engineers class in this View file, as I want this user provided data to be linked with the properties of Engineers class.
  • Next, I have given the Title for the Page which will be rendered to the Layout View file.
  • Finally, I have used the <form> tag to create my Registration Form and I have used two Tag Helpers to provide the Controller & action method.
  • So, when we will submit this form, then it will be redirected to the same page and I have also provided post method, So, this form will make a POST request, as shown in below figure:
  • Inside this form, I have created label & input and have provided a tag helper asp-for.
  • asp-for tag helper will link this input with the respective property in Engineers class.
  • As you can see, I have provided Username to my first asp-for tag helper and we also have a Username property in my engineers class.
  • Moreover, this asp-for tag helper will generate the Name & Id fields of this <input> tag, which you can check by looking at the source code of your webpage.
  • As you can see in HTML output, we have for attribute in <label> tag and in <input> tag, we have name & id attributes.
  • I have created 3 Labels & Text Boxes for their respective properties in engineers data class, i.e:
    • Username.
    • Email.
    • FullName.

Enums in ASP.NET Core

  • If you have studied C#, then you must be aware of C# Enums, so let's create two enums for our project.
  • As our site is related to Engineering, so I want the registering users to provide their University & Department Names and for that I have created enums.
  • We can place Emums anywhere in our project, so I have created a new folder in the root directory and named it TepEnums.
  • Inside this folder, I have created two enums, named as:
    • DeptEnums.
    • UniEnums.
  • Inside these Enums, I have added few data and I am going to provide this data to my select elements in registration form, these enums are shown in below figure:

Select Tag Helpers in ASP.NET Core

  • I have created 3 Textboxes at the start and then created two select element for Department & University.
  • In this <select> tag, I have used asp-items tag helper and then provided it our newly created enum DeptEnum.
  • I did the same with University <select> tag, so overall we are getting 5 values from our end user.
  • Finally, at the end of our code, we have a Register button.
  • Moreover, I have also changed the data type of University & Department from string to their respective enum, shown in the first figure of this tutorial.

Import Namespaces in Layout Imports File

  • We have to include the namespaces of our enums in the Imports Layout File, so that we could use them in all of our Views.
  • Similarly, as we are linking for Registration form with engineers class, which is present in Models folder, so we also have to include this Models Namespace, as shown in below figure:
  • We have made all the changes and now it's time to run our web application and if everything goes fine, then you will get similar results:
  • So, we have created our registration form but if you click on this Register Button, then it won't do anything except refreshing the page.
Create Method for adding New User
  • We have created the font-end View for this registration form and have also created its action Method in Controller, but we haven't yet created it's model's function.
  • So, let's open the IEngineersRepository.cs file in Models Folder and create a method in it for Adding New Engineer, using data coming from registration form, as show in figure on right side.
  • We have declared the method in interface, so we have to provide its implementation as well in the EngineersRepository class, which is implementing this interface.
  • So, open your EngineersRepository.cs file and inside this file, I have provided the implementation of AddNewEngineer() function.
  • This function takes engineer as an input, which we will send it from Controllers class and when it gets this new engineers data, then we need to increment the id property, which has to be set internally.
  • After that, I am adding this engineer variable in my _EngineersData array and finally returning the newly created engineer variable.
  • So, we have successfully added the Model method for our Registration form, and when it will get the data, it will simply save it in the EngineerData array. ( We will save data in database in our coming lectures )

POST action method in ASP.NET Core

  • Now open your HomeController.cs file, whcih has the action method Registration.
  • This action method was used to open the Registration View but what will happen, when we press the Register button.
  • When we press the REgister button, then HTML form will make a POST request so, let's create two method with same name i.e. Registration.
  • First method will handle the HTTP Get request i.e. will simply display the Registration Form.
  • Second method will handle the HTTP POST request and will execute on Register Button press, as shown in below figure:
  • You can see in above figure, I have placed an [HTTPGet] attribute before first action method and thus it will simply serve the respective View file.
  • While, I have placed [HTTPPost] attribute before second method and thus when we press the Register Button, a POST request will be generated and thus this action method will execute.
  • In this Post method, I have simply executed the AddNewEngineer method of Model class, which will add this new engineer.
  • Finally, I have redirected it to Info Page and have shown the details of newly created user.
  • Now when you run your project, and add users' data using registration form then it's info page will open up with new engineer's data.
  • I haven't added any Bootstrap code yet, as I want to keep things simple, we will design our application in future lectures.
So, that was all for today. So far, we haven't placed any validation check on our submitted data, we will do that in our next lecture. Till then take care & have fun !!!

HTML Tag Helpers in ASP.NET Core

Hello friends, I hope you all are doing great. In today's lecture, we will have a look at HTML Tag Helpers in ASP.NET Core. It's our 12th tutorial in ASP.NET Core series. If you have worked on ASP.NET then you must have been familiar with HTML Helpers. Tag Helpers are quite similar to HTML Helpers with slightest difference in its syntax. Tag Helpers are new in ASP.NET Core and were not part of ASP.NET. So, let's first understand what are Tag Helpers & why we need to use them and at the end we will also discuss few common tag helpers in detail. So, let's get started with HTML Tag Helpers in ASP.NET Core:

HTML Tag Helpers in ASP.NET Core

  • HTML Tag Helpers in ASP.NET Core are server side components and thus executed on the server to create HTML elements of the webpage.
  • ASP.NET Core has a lot of built-in Tag Helpers for links, images, forms etc. available in Microsoft.AspNetCore.Mvc.TagHelpers assembly and we need to use @AddTagHelper directive to include them in Views.
  • As we want to use these Tag Helpers in all of our Razor Views, so I am going to include this TagHelper assembly in _ViewImports.cshtml file, which we have created in 10th lecture and has all the assemblies importing statements.
  • AS you can see in the figure on right side, I have imported Tag Helper assembly using @AddTagHelper directive and it has two parameters.
  • I have added * in first parameter, which means I want to import all the Tag Helpers available in TagHelper assembly.
So, after adding this statement, we can now use Tag Helpers in our project. Let's have a look at few commonly used Tag Helpers:

HTML Tag Helpers for Hyperlinks

  • In our Bootstrap lecture, we have added three <a> elements in our Info View file but haven't provided the href value.
  • So, now let's use Tag Helpers to provide link value for href parameter of <a> tag, as shown in below figure:
  • I have marked these 3 links with red box and you can see that I have used 3 link Tag Helpers i.e.
    • asp-controller: I have provided the controllers name i.e. home.
    • asp-action: I have provided the action method name i.e. Index for first link & Info for second.
    • asp-route-id: I have provided the third parameter in it, while id is the name of the parameter.
  • All Tag Helpers start with asp- prefix and are embedded in HTML tags as simple parameters.
  • Now let's run this app and open this Info link and have a look at the HTML source, as shown in the below figure:
  • I have encircled the output links with green box and you can see that we don't have any tag helpers in our output file.
  • Instead, these tag helpers generated the HTML code of href parameter and we can see that the first link is of Homepage and the second link is of /Home/Info/3.
  • Now, you must be wondering that why we need to use Tag Helpers, as we can easily add the hard coded links.
  • The main benefit is, in future if you change your Controllers' names then your links will be changed and if you have placed them hard coded then you have to manually change them one by one.
  • But with Tag Helpers, there's no need to change as they will get the update name of Controller or action method and will provide the corrected link.
  • Moreover, Tag Helpers are inline with HTML unlike HTML Helpers and are thus easy to use.

HTML Tag Helper for Images

  • If we change any existing image on our server without changing its link, the browser will keep on showing the old image, because of Browser Cache.
  • So, in order to avoid that we need to use a builtin HTML Tag Helper called asp-append-version in <img> tag, as shown in below figure:
  • So, now if the image content is changed on the server then it will make the new image available to the end user.
  • If you check the HTML code of your output page, then you will find a unique string appended to your image link, which is calculated using the image content.
  • So, if image content is changed then this string will also be calculated again and thus browser will know that there's new content in the image and will load it again from the server, instead of providing it from its cache.

HTML Tag Helper for Environments

  • Using Environment Tag Helper, we can execute different content of the webpage, based on application environment.
  • We have studied Environment variable in 5th lecture and have seen that we set this variable in lauchSettings.json file.
  • In our Development Environment, we need to use non-minified versions of all of our third part client side libraries i.e. Bootstrap, Jquery, Javascript etc.
  • But in Staging or Production Environment, we should use minified versions and for better performance, we should get them from their CDN networks.
  • So, let's make these changes using Tag Helpers, open your _Layout.cshtml file, placed in Views > Shared folder.
  • We have linked Bootstrap file with our project here, so let's add some code in it, as shown in below figure:
  • You can see in above figure that in green box, I have placed the link to non-minified version of Bootstrap inside Environment tag helper and I have included Development Environment.
  • So, this link will be used only when we are working in Development Environment.
  • In the red box, I have excluded Development Environment, so this block will work for all Environments except Development.
  • Inside this block, I have placed the Bootstrap CDN link, which you can get from its official site.
  • But what if, this external CDN is link is down for some reason, then your server won't be able to fetch those files and thus your site won't work perfectly.
  • In such cases, we should fall back to our own server and get the minified version of Bootstrap.
  • So, let's add few more Tag Helpers to achieve that, as shown in below figure:
  • As you can see in above figure, I have added five tag helpers in <link> tag.
  • So if our application is unable to get the CDN link, then it will fallback to our own server & get the minified version of Bootstrap.
  • These tag helpers are injecting a JavaScript code to check, whether we got the CDN link or not.
  • As we have added this code in our Razor Layout file so it will be applied to all of our Views. ( We will add more Views in coming lectures )
So, that was all for today. I hope you have enjoyed today's lecture. In next tutorial, we will have a look at How to design Bootstrap navigation Menu in ASP.NET Core. Till then take care & have fun !!!

How to include Bootstrap in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to include & use Bootstrap in ASP.NET Core. It's our 12th tutorial in ASP.NET Core series. As it's ASP.NET Core tutorial so I am not going to explain bootstrap much. But you must have the basic idea of Bootstrap, its a client side package of CSS libraries, designed by twitter and these days you can't design a responsive site with Bootstrap as it follows symmetry and is too easy to use. So, let's get started with How to include Bootstrap in ASP.NET Core:

How to include Bootstrap in ASP.NET Core

  • There are many third party tools ( Bower, NPM, WebPack etc. ) available in Visual Studio for installing client side applications like Bootstrap, JavaScript, Jquery etc.
  • But we are going to use builtin tool of Visual Studio called LibMan ( short for Library Manager ), for installing third party packages, we can use both file system & CDN.
  • LibMan is a light-weight client side library acquisition tool, which not only downloads the third party libraries but also keep a track in a special file.
  • In order to open Library manager, right click on your project's name in Solution Explorer & then Add > Client Side Library and below dialog box will open up:
  • You can see in above figure that I have made a search for twitter-bootstrap@4.3.1 in the Library Text Box and LibMan previewed its files.
  • After that I have changed the Target Location and its now wwwroot/lib/bootstrap, so my bootstrap files will be placed inside lib folder of wwwroot folder.
  • After these settings click the Install button and these bootstrap files will be installed.
  • Let's also install jquery using Library manager, as shown in below figure:
  • Library Manager has also created LibMan.json file which keeps the record of all the third party packages installation.
  • I have placed both bootstrap & jquery in wwwroot > lib folder, as shown in below figure:
  • That's how, we can easily install third party client side packages in ASP.NET Core.
  • Now, we need to include this Bootstrap file in our Razor Layout View file, as shown in below figure:
  • You can simply drag & drop the bootstrap file in this Layout file and the link tag will automatically be generated.
  • So, now let's add some bootstrap code in our Info View file to make it look eye caching, as shown in below figure:
  • Now run your application and navigate to info page and if everything goes fine then you will get similar results, as shown in below figure:
  • Now you can see our page got a much nicer look with bootstrap included.
So, that was all about bootstrap in ASP.NET Core. I hope you have enjoyed today's lecture. In the next tutorial, we will have a look at Tag Helpers in ASP.NET Core. Till then take care & have fun !!!

URL Routing in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at URL Routing in ASP.NET Core. It's our 11th tutorial in ASP.NET Core series and it's an important but quite easy concept to understand. You must be wondering how we are routing rite now as we haven't added any routing codes yet. But if you remember, we have used MVC with default route middleware in our pipeline and this middleware automatically sets up this default URL routing for our web application.  So, let's understand how this URL Routing works in ASP.NET Core:

URL Routing in ASP.NET Core

  • URL Routing in ASP.NET Core is used to provide the controller's action method to the incoming HTTP request.
  • In simple words, when a user enters an HTTP URL in its browser, then it is greeted by the respective controller's method and which controller's method should by executed, it is decided by the URL Routing.
  • As you can see in below figure that our controller class has two action methods in it i.e. Index & info:
  • By default, first segment of URL ( home in our case ) is the name of the Controller and the second segment is the name of the action method. So, when we have info in the second segment then Info action method will be executed.
  • So, now let's understand this third segment in URL link, which is routed as a parameter to the action method.
  • If you remember, when we created the Info action method then we have hard coded the value of Engineers to 1.
  • So, let's make it flexible and ask the user to enter it as a third segment in the URL.
  • Open your Controller's file and make these changes to Info action method, as shown in figure on right side.
  • I have added a parameter int id in our Info method and then placed this id in the GetEngineers function.
  • So, now run your function and navigate to /home/info/3 and now you will get the data of your third engineer, as shown in below figure:
  • Now, we have automated our Info method by adding this third parameter and we can view any engineer's data quite easily.
  • But, if you open /home/info/ without the third parameter, then you will get a run time error and one way to avoid it is by making this third parameter null-able, as shown in figure on right side.
  • I have made the id null-able and then assigned it a default value of 1 by using id??1.
  • So, now if you don't add the third parameter then it will show you the data of first engineer by default.
  • This default routing of ASP.NET Core is also called Conventional Routing.
I hope you have understood the Conventional URL Routing in ASP.NET Core, so that was all for today. In the next lecture, we will have a look at How to include Bootstrap in ASP.NET Core. Till then take care & have fun !!!

Razor Layout Views in ASP.NET Core

Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at different Razor Layout Views in ASP.NET Core. It's our 10th tutorial in ASP.NET Core series. You must have noticed in websites that they have common sections, which remains the same throughout the website i.e. Header Section, Footer Section, Sidebar etc. In today's lecture, we will have a look at how to design these default layouts of a website. We have already discussed the MVC architecture in detail so now it's time to start building our site's layout or basic structure. Today we will just discuss different files available in ASP.NET Core for default layout designing. So, let's get started with Layout View in ASP.NET Core:

Razor Layout View in ASP.NET Core

  • Razor Layout View in ASP.NET Core is a Razor file ( extension .cshtml ), used to design default Layouts of the website, which are then embedded in all ( or desired ) Views of the website.
  • A simple website's layout is shown in the figure on right side and these are normal sections of a blog and depending on site, these sections may increase or decrease.
  • Moreover, you may have more than 1 Layout for a single View i.e. different layouts for signed in users and guest users.
  • We place these Layout Views in Shared sub folder of Views folder, so let's create this Shared Folder inside Views folder and then click on Add > New item.
  • Add New Item dialog box will open up, make a search for razor in it, as shown in below figure:
  • We have already used Razor View to create Info View Page and we have seen that in razor files, we can use both html and C#, these are like smart HTML Pages.
  • So, today we will have a look at remaining Razor files and first let's add this Razor Layout file in our Views > Shared folder.
  • You must have noticed the underline sign ( _ ) before Layout name, its a convention ( not necessary ) to differentiate Layout files from other files, although you can write any name you want.

Why use Razor Layout View ?

  • It reduces repetition of code thus saves time especially in bigger projects.
  • Let's say you are working on a blog then you have to place these Footers, Headers & Sidebars etc and if you hard code them in each of your page then editing will be a serious issue.
  • That's why it's better to have all the default settings of our Views in a single file, so that we could change them easily.
  • Layouts are also used for consistent look and behavior of the website across all its webpages, you can think of them as HTML theme of your web application.
  • These Layout files are the alternative of Master Pages in ASP.NET Web Forms.
So, let's add some code in our newly created Layout View File:

Adding code in Razor Layout View file

  • We have added the Razor Layout file in our Views > Shared folder, open this file and you will find HTML code in it, as shown in the figure on right side.
  • As you can see this code is kind of an HTML wrapper having all the required tags i.e. head, body, meta, title etc. but it doesn't have any content in it.
  • It has 2 C# code lines in it:
    • First one is Title property which will set the title of the page.
    • Second one is RenderBody() method, View specific content will be injected here.
  • Both of these C# lines will be getting data from the View, which will be calling this razor layout.
  • Now, let's open our Info View file, and delete the wrapping HTML code, as shown in figure on right side.
  • Now, I just have the content HTML code in my Info View file.
  • Now let's enable this Info View file to use Razor Layout file and for that we have to include a new razor code block in our View file.

Layout Property in Razor View file

  • You can see in figure on right side that I have added a new razor code block at the top of my Info View File.
  • In this razor code block, I have specified two properties:
    • First one is the Layout property, where I have provided the path to the Razor Layout File.
    • Second one is ViewBag.Title, which was also present in Layout file and this property will set the Title of the Page.
  • Now run your web application and obviously you won't find any difference and if you check the Page soruce of Info page then you will find the complete html code in it with all required tags i.e. head, body, title etc.
Now let's have a look at another property called Sections in Razor Layout Files:

Render Sections in Razor Layout Files

  • Sections is a property in Razor Layout Files, which is used for the organized placement of few page elements.
  • You must have seen any movie review site, normally in such reviews, the review box is placed right at the top in either left or right corner displaying the overall review aggregate.
  • Sections are used to place such sticky elements in web pages, I have placed a Render section in my _Layout.cshtml file named AdBanner.
  • First I have placed an IF loop to check if the section is present in the View or not and if it's present then execute that section.
  • This IF statement is necessary as it makes the section optional otherwise it will be mandatory and if you don't have it in your View file then you will get a run time error.
  • So, this Ad Banner section will be placed at the end of the webpage.
  • Now, we need to create this AdBanner section in our Info View File, so open your View file and place the code as shown in figure on right side.
  • You can see I have used @section directive and then provided it the same name as in our Layout file and then in curly brackets { } placed the content ( which doesn't make much sense for now ).
  • Now run your project and open this link home/info and if everything goes fine then you will see this line at the end of your file, as shown in below figure:
  • So, despite the fact that we have placed the section at the top of our Razor View File but still it appeared at the bottom, as specified in the Razor Layout File.
  • We can create as many sections as we want in our Razor Layout file.
You must have noticed that we have to add the path of our Layout file in every View file, which is clearly a negation of DRY ( Don't Repeat Yourself ). So, let's see How to get rid of this linking.

Razor View Start File in ASP.NET Core

  • Razor View Start File in ASP.NET Core is used to specify the Razor Layout file location for Razor View Files.
  • It is normally placed inside the Views folder, so let's Add New item and in the search dialog box, make a search for razor, as shown in belwo figure:
  • Previously, we have selected Razor Layout file and this time we are going to select Razor View Start file and you can see it also has underscore sign ( _ ) at the start of the name.
  • Add this file to your project and you will find a simple code in it, as shown in figure on right side.
  • This code is automatically generated by visual studio, as it knows we have the Layout file in our project, so now we have successfully specified the Layout file for our View files.
  • So, now remove your path from the Info View file and run your project and it will still work the same.
  • It's really helpful as if you wanna change the name or path of your Layout file then you can quite easily do it here and it will be applicable to your entire application.
  • Moreover, Razor View Start file is hierarchical i.e. you can add View Start files in each folder and it will override the parent View Start settings.
  • So, if you wanna assign different Layouts to different Controllers then you can easily do that by adding a new View Start file in these folders.
  • We can still specify path to Layout file directly in View file and it will override everything, we can also make Layout = "null", which will remove all the Layouts from that View.
  • So, the Razor View Start file reduces the code redundancy and thus increases maintainability.
Finally, let's have a look at the Razor View Imports file, which is the last one in razor files import section:

Razor View Imports in ASP.NET Core

  • Razor View Imports in ASP.NET Core are used to include common namespaces, required by the Razor View files.
  • In our Info View file, you have seen that we have specified @model directive at the top and then provided fully qualified name of our View Model, which in our case is:

TheEngineeringProjects.ViewModels.HomeInfoViewModel

  • So, if we have to add more View Models or simple Models then we have to write full name again, which is again a violation of DRY, so it's always a better approach to place most commonly used namespaces in our Razor View Imports file.
  • This file is placed inside Views folder and is hierarchical ( similar to View Starts ).
  • So, right click on Views folder and then Add > New Item and select Razor View Imports file, it's name also starts with underscore sign ( _ ).
  • Inside this file, place this single line of code, as shown in the figure on right side.
  • Here, I have placed @using directive and then specified the namespace if my ViewModels folder and it will be automatically included in my View files.
  • So, now open your Info View File and remove this namespace from @model directive and now we will just specify the name of the ViewModel, which we are using for the View, as shown in below figure:
  • So, that's our final Info View Code and you can see that now we don't have any code repeatability in it.
  • The code is clean and contains only the content of this View file, so our project is more organized and maintained, although have no effect on the output.
So, that was all for today. I hope you have enjoyed today's lecture, it was quite a lengthy one but you must have got the idea how important it is. In the next lecture, we will have a look at Routing in ASP.NET Core. Till then take care & have fun !!!
Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir