How To Install the Sql server 2022 Express edition

step1

Now Click on install.

now

Now click

Below is connection string which can be used to connect.

Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;

Now Let’s install SSMS.Once you click on it .It will take you to https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver16&redirectedfrom=MSDN

Download and Install.

Click on Install.

Now Open Sql server Managment Studio.

Click on connect.

How to set passowrd for sa user in SQL server 2022

Launch the sql server managment studio.Connect using “Window Authentication”.

Click on connect button.

You can see sa role is disabled.

As shown in below screenshot go to propertise.

Change the Server authentication as shown in below screenshot and click on ok button.

You will get below notification and proceed.

Click on ok and proceed.

Now we need restart the sql server service.So open services.msc.

Restart the above highlighted sql services.

Now again go to Sql server managment studio.

For sa user change login to Enabled.Change the password of your choice and uncheck “Enforce password policy“.Click on ok

After clicking on OK the sa user role will enable.

Now you can disconnect and login with user sa.

Creating Background service or Task in .Net core Web Api

Creating BackGround service or Task in .Net core Web Api

Prerequisite
1>.Net core 5 https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-5.0.302-windows-x64-installer
2>Visual Studio code(optional) https://code.visualstudio.com/docs/?dv=win
3>Postman (Optional) https://www.postman.com/downloads/

Basic knowledge of .Net core web api. You can read Blog

A background tasks can be implemented as hosted services in .Net core web Api. A hosted service is a class with background task logic that implements the “IHostedService” interface.

There are two ways to create Background service (Background Task):

1>By Implementing “IHostedService” interface .”IHostedService” interface has two methods.

2>By Implementing BackgroundService class. The BackgroundService class is an abstract class that also inherits the IHostedService interface. One of the benefits of inheriting this class is that we don’t have to implement the StartAsync or StopAsync methods. However, if we wish override them, we can do that.

Let’s start implementing the second Approach First.

We have created web api using below command.

dotnet new webapi -o BackGroundTaskDemo

Now let’s have project structure which got created.

You can see that by default Controller and other required file have been added. You can read in detail about these files in blog.

Let’s run the project using command “dotnet run”. Now let’s run the postman to access the get Api.

Now let’s concentrate on creating Background service.

You can see in above screenshot we have added class “BackgroundSample” and then derived from class “BackgroundService” and override the method “ExecuteAsync”. Now the logic which will execute while running background service should be written in “ExecuteAsync” method.

Note: You need to include “using Microsoft.Extensions.Hosting” for using “BackgroundService” class.

Firstly, we have injected Logger in constructor, so that we log the activity inside the class and method “ExecuteAsync”. We have declared the Int variable count.

Inside “ExecuteAsync” method, while loop will be executed until the cancellation request is requested. Cancellation token will be called while you close the application. We are incrementing the count variable in thread safe manner at line 21. At line number 23 we are printing count and then waiting for 5 second. So in short in loop we are incrementing variable in thread safe manner and then printing it and then waiting for 5 second.So after interval of 5 second we are printing number incremented by 1.

“ExecuteAsync(CancellationToken stoppingToken)” method is called to run the background service or you can say background logic.

The implementation returns a Task that represents the entire lifetime of the background service.  No further services are started until function ExecuteAsync becomes asynchronous, such as by calling await.

We should avoid performing long, blocking initialization work in ExecuteAsync because, the host blocks in StopAsync(CancellationToken) waiting for ExecuteAsync to complete. Shortly will have look at method StopAsync(CancellationToken) .

Let’s register our Background service in “Program.cs” .

When configuring services, there is an extension method called AddHostedService
in the IServiceCollection interface. As the AddHostedService extension method is expecting a class that inherits IHostedService, we don’t specify the interface when adding the hosted service.

We have registered our Background service class from Line number 26 to Line number 11. It will get registered as Singleton  instance.

We need to import “using Microsoft.Extensions.DependencyInjection” for registration of Background service.

Now let’s run the application.

You can also Hit the postman and verify our get Api is also working fine perfectly while application is running.

I started the application and after few second I close the application using “ctr+c” hence only 1 and 2 have been printed.

Now if you stop the application using “ctr+c” then cancellation request will be initiated, and number will not be printed, and application will shut down. You can also put debugger on “ExecuteAsync” method and verify this. The cancellation token is triggered when IHostedService.StopAsync is called(When the application is shutdown. Will see this method shortly ,its implemented in BackGroundService class). The implementation of ExecuteAsync should finish promptly when the cancellation token is fired in order to gracefully shut down the service. Otherwise, the service ungracefully shuts down at the shutdown timeout.

Note: The default timeout is 5 second for cancellation token.

Kindly have look at blog

When you start the application, below is order of Execution.

1>”ConfigureServices” method of “Startup.cs” class get called. Constructor of class “BackGroundSample” get called.

2>”Configure” method of “Startup.cs” class get called. So in this step the request pipe line get set up for .Net core web api. All the middleware gets called.

3>”ExecuteAsync” method of “BackGroundSample.cs” class get called.

Now if we want that “ExecuteAsync” should get called before request pipeline is set up then we need to register in below manner.

When you start the application, below is order of Execution.

1>”ConfigureServices” method of “Startup.cs” class get called. Constructor of class “BackGroundSample” get called.

2>”ExecuteAsync” method of “BackGroundSample.cs” class get called.

3>”Configure” method of “Startup.cs” class get called.

So in this step the request pipe line get set up for .Net core web api.

 In above screenshot we can see our background task started asynchronously before the request pipeline set up.

As shown below, you can also register background service in “ConfigureServices” method of “Startup.cs” instead of registering in “Program.cs”.

Now let’s have look at class “BackgroundService” class.

We can see in above image “BackgroundService” class is deriving from “IHostedService” interface. This interface has two method “StartAsync” and “StopAsync”. “BackgroundService” class has implemented these methods, but we can override the implementation of these methods  in our “BackGroundSample” class.

Now when we run the application then “ExecuteAsync” method will not get directly called. First “StartAsync” method will get called then it will call the “ExecuteAsync” method.  Similarly, When you stop the application then “StopAsync” method will get called then it will call the “ExecuteAsync” method (IsCancellationRequested will be true, hence while loop will break).Let’s run the application.

For above output we started the application using “dotnet run” command in Visual studio code then after some time we stopped the application using “ctr+c”.

Now let’s move the code which is executed inside “ExecuteAsync” in other class. So that functionality is more decoupled, and we can see how we can inject dependencies inside Background service.

We have created Below interface which has one function.

Now register above class as Singleton.

 We are registering worker instance as singleton as we will injecting inside class (BackGroundSample), which is register as singleton using,

services.AddHostedService<BackGroundSample>();

as we have seen in starting of Blog.

Now inject Worker instance in the “BackGroundSample” class.

Now run the application and we get same output.

Consuming a scoped service in a background task

What happen if we register worker instance as Scoped.

Now let’s run the code. You will get below error.

“Some services are not able to be constructed (Error while validating the service descriptor ‘ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: BackgroundTaskDemo.BackGroundSample’: Cannot consume scoped service ‘BackgroundTaskDemo.IWorker’ from singleton ‘Microsoft.Extensions.Hosting.IHostedService’.)”

Our “BackGroundSample” class is register as singleton means its instance only be created only once during lifetime of Application. The dependencies this class is excepting should be register as singleton. But we have register “Worker” instance as scoped which means for each request new instance of “Worker” will be created. For detail of dependency injection please have look at blog.

We need to make changes in “BackGroundSample” class such way that it should be able to resolve dependencies which are register as Scoped.

Now if you run the application then it will run correctly.

Hosted services are added to the DI container using the singleton service lifetime. As a result, it can only resolve singleton and transient service lifetime classes that are injected into it.

If we were to inject a scoped service lifetime class into the hosted service, it would not know which scope it belongs to and would throw a runtime error when the hosted background service started. But we can create our own scope when running a background task and resolve a scoped service from that scope.

To do that, we need to inject the IServiceProvider instance into the hosted service. Within that interface, we can use the CreateScope method to create a new scope instance. From there, we can use our new scope instance to resolve a scoped service into our background task.

Creating Background Service by Implementing interface “IHostedService”

Now let’s create another Background service by Implementing “IHostedService”.

“StartAsync(CancellationToken)” contains the logic to start the background task.
“StopAsync(CancellationToken)” is triggered when the application/host is performing a graceful shutdown.
“StopAsync” contains the logic to end the background task.
We should Implement IDisposable to dispose of any unmanaged resources.

Let’s Implement the Same logic which is executed by our existing “BackGroundSample” class.

We can then kick off our tasks in the StartAsync method. However, one thing to note is that we would have to have to fire off our tasks as separate tasks using Task.Run.

If we have a infinite task and we decide to run it directly in the StartAsync method,
the task would never complete. A ASP.NET Core web application relies on the StartAsync method to complete before it can start the web application.

Here is how we can set off a separate task in the StartAsync
without delaying the web application from launching.

Now let’s register the class and run the application.

Now run the application.

Now let’s change the implementation of “BackGroundSampleScratch” class. Will Use timer in implementation.

We have created Timer which will start calling the “OnTimer” method when the application is started and “StartAsync” method is called. When “StartAsync” method is called, Timer will start executing method “OnTimer” as we have passed TimeSpan.Zero in parameter.

Then after interval of 3 second “OnTimer” is called as we have passed TimeSpan.FromSeconds(3) in parameter.

When we stop the application then “StopAsync” will get called which then calls the Dispose method of IDisposable interface and timer instance is disposed.

Note: We can dispose the timer in “StopAsync” method but its good practice to dispose the instance by using IDisposable pattern.

Note: StartAsync should be limited to short running tasks because hosted services are run sequentially, and no further services are started until StartAsync runs to completion.

Let’s register this class.

Now if we run the application then both Background services will be executing in Background, and you can query the application using Postman at same time.

You can see one Background service is printing the number at interval of 5 second. Second Background service is printing string “Timer is called….” After interval of 3 second. “BackGroundSample” class is registered First hence its started executing first.

Note: The cancellation token has a default five second timeout to indicate that code inside the “StopAsync” should not tale more than 5 second. If “StopAsync” code is taking more than five second than the application will not execute it.Application will give 5 second to execute the code. Read the blog to increase time.

ActionFilter in .Net Core Web API

Prerequisite

1>.Net core 5 https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-5.0.302-windows-x64-installer
2>Visual Studio code https://code.visualstudio.com/docs/?dv=win
(Also adding c# by omnisharp)
3>Postman https://www.postman.com/downloads/

In this tutorial We will Understand

1>Creating Action Filter by implementing “IActionFilter”
2>Understanding “OnActionExecuting” and “OnActionExecuted” methods of “IActionFilter”
3>Applying the action filter at global level, controller level and action method level.

Let’s create new API .Net core web Api in Visual studio code.

dotnet new webapi -o ActionFilterDemo
cd ActionFilterDemo
code -r ../ActionFilterDemo

You will see that below project will be created by default.

Also, you will get below option. Kindly click on yes and proceed.

Now in first screenshot we have seen “WatherForecastController,cs” and “WeatherForecast.cs”. Just delete both the classes.Let’s add the below classes.

We will be creating the controller which will perform “Get”, “Add”, “Update”, “Delete” on employee. Controller will give call to repository will perform all operation on employee in collection. Let’s have look in detail.

Let’s implement above contract in repository which will perform all operation on employee.

We need to register the above repository in “ConfigureServices”.

We need to register the above repository in “ConfigureServices”.

Now let’s have look at our controller.

Now let’s test through postman.

Currently we are getting three employees. All three employee have been hardcoded in repository.

Now let’s try to delete employee with Id 4. We know  employee with id 4 currently does not exists.

Now let’s try update operation from postman for Id which does not exists.

As Id does not exists, we will not get correct response. When we try to update or delete the employee first employee is checked whether it exists or not. If it exists then we proceed and update or delete employee, else we return not found. So, checking employee exists or not is common between both update and delete. So we can move this common code on Action Filter.

Action Filters Implementation

To create an Acton filter, we need to create a class that inherits either from the

IActionFilter” interface or “IAsyncActionFilter” interface or from the

ActionFilterAttribute” class which is the implementation of the “IActionFilter”, “IAsyncActionFilter”, and a few different interfaces as well:

public abstract class ActionFilterAttribute : Attribute, IActionFilter, IFilterMetadata, IAsyncActionFilter, IResultFilter, IAsyncResultFilter, IOrderedFilter

In our examples, we are going to inherit from the “IActionFIlter” interface because it has all the method definitions we require.

To implement the synchronous Action filter that runs before and after action method execution, we need to implement “OnActionExecuting” and “OnActionExecuted” methods:

    public class ActionFilterSample : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // our code before action executes
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            // our code after action executes
        }
    }

We can do the same thing with an asynchronous filter by inheriting from “IAsyncActionFilter”, but we only have one method to implement the “OnActionExecutionAsync”:

    public class AsyncActionFilterSample : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // execute any code before the action executes
            var result = await next();
            // execute any code after the action executes
        }
    }

The Scope of Action Filters

Like the other types of filters, the action filter can be added to different

scope levels: Global, Action, Controller.

If we want to use our filter globally, we need to register it inside the “AddControllers()” method in the “ConfigureServices” method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(config => 
    {
        config.Filters.Add(new GlobalFilterExample());
    });
}

But if we want to use our filter as a service type on the Action or Controller level, we need to register it in the same “ConfigureServices” method but as a service in the IoC container:

services.AddScoped<ActionFilterSample>();

Finally, to use a filter registered on the Action or Controller level, we need to place it on top of the Controller or Action as a ServiceType:

   [ServiceFilter(typeof(ControllerFilterExample))]
    [Route("api/[controller]")]
    [ApiController]
    public class MyController : ControllerBase
    {
        [HttpGet]
        [ServiceFilter(typeof(ActionFilterSample))]
        public IEnumerable<string> Get()
        {
            return new string[] { "example", "data" };
        }
    }

Now let’s write the Action filter for our employee controller.

In above Filter we are checking the id exists or not. If id not found then we return not found .Also we are checking user is passing id or not (We can do better error handling with int.tryparse)

if we find the employee in the repository collection, we store it in “HttpContext” because we need that employee in our action methods and we don’t want to query the repository two times (we would lose more than we gain if we double that action).

Let’s register this action filter.

Let’s use this Action Filter in our action method.

You can see in above screenshot we have have commented repetitive code from both action method. We have applied action filter.

[ServiceFilter(typeof(EmployeeExistsActionFilter))]

If Employee exists then we are getting the employee from “HttpContext”

var empfromrepo = HttpContext.Items["employee"] as Employee;

If you run the web Api and Hit from postman then everything will work fine.

As discussed if you apply filter at global level then it will be executed first then filter applied at Controller level will be executed then filter applied at action level will be executed. Below Diagram Depicts that ,

Routing in .Net Core

Routing is the process through which the application matches an incoming URL path and executes the corresponding action methods inside controller.
.NET Core MVC uses a routing middleware to match the URLs of incoming requests and map them to specific action methods.

We can define the routes either in the startup code or as attributes.
They describe how we can match the URL paths with the action methods.
We can also use routes to generate URLs for links that are sent out in responses.

In this blog we will learn how can we define route using Route and HttpGet Attribute.

There are two types of routing for action methods:

Conventional Routing
Attribute Routing

Let’s Concentrate First on Attribute routing .First create Simple .Net core web api.

Open Visual studio code and fire below command.

dotnet new webapi -o RoutingDemo
cd RoutingDemo
code -r ../RoutingDemo

We will get by default the highlighted controller. I have completely changed the controller, below is code. I have added three action Methods.

namespace RoutingDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public String GetApiOne()
        {
          return "This is API One of WeatherForecastController";
        }

        [HttpGet]
        [Route("{id}")]
        public String GetApiTwo(int id)
        {
           return $"This is API Two of WeatherForecastController with id {id}";
        }

        [HttpGet]
        [Route("Custom/{id}")]
        public String GetApiThree(int id)
        {
           return $"This is API Three of WeatherForecastController with id {id}";
        }
    } 
}

When we run the application we get the url where this rest service is accessible.

Now just hit the https url from postman.

When using Attribute Routing, the controller name and action method name plays no role in selecting which action method to execute. As we have decorated our controller with [Route(“[controller]”)],hence the url to access the method inside controller will have “/WeatherForecast”.

Note: In url “Controller” word will be remove. So below are three url.

http://localhost:5000/WeatherForecast
http://localhost:5000/WeatherForecast/2
http://localhost:5000/WeatherForecast/Custom/3

You can pass id of your choice.

In First method of Controller There is no route hence we can access it directly.

Below middleware helps in routing which are by default configured.

The two middleware highlighted in below screenshot, set up the application with routes and endpoints required to handle the request in application.
app.UseRouting() add the route matching to the middleware pipe line.
It will look at end point defined in the application and select the best match for request. app.UseEndpoints() add the endpoint execution code to the endpoint in middleware pipe line.

Below Highlighted line will help to inject the controller’s which will be required by middleware to execute the routing.

Let’s have look at below code. We have created more end point address using existing three action methods. We have used one more Route at controller level.

namespace RoutingDemo.Controllers
{
    [ApiController]
    [Route("RestService")]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public String GetApiOne()
        {
          return "This is API One of WeatherForecastController";
        }

        [HttpGet]
        [Route("{id}")]
        public String GetApiTwo(int id)
        {
           return $"This is API Two of WeatherForecastController with id {id}";
        }

        [HttpGet]
        [Route("Custom/{id}")]
        [Route("Generic/{id}")]
        public String GetApiThree(int id)
        {
           return $"This is API Three of WeatherForecastController with id {id}";
        }

    }
}

Now below will be combination of Route.

http://localhost:5000/WeatherForecast
http://localhost:5000/WeatherForecast/2
http://localhost:5000/WeatherForecast/Custom/3
http://localhost:5000/WeatherForecast/Generic/3

http://localhost:5000/RestService
http://localhost:5000/RestService/2
http://localhost:5000/RestService/Custom/3
http://localhost:5000/RestService/Generic/3

We can define route at method level using HttpVerb. Below is code snippet. So we can achieve same thing.

namespace RoutingDemo.Controllers
{
    [ApiController]
    [Route("RestService")]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public String GetApiOne()
        {
          return "This is API One of WeatherForecastController";
        }

         [HttpGet("{id}")]
        public String GetApiTwo(int id)
        {
           return $"This is API Two of WeatherForecastController with id {id}";
        }

        [HttpGet("Custom/{id}")]
        [HttpGet("Generic/{id}")]
        public String GetApiThree(int id)
        {
           return $"This is API Three of WeatherForecastController with id {id}";
        }

    }
}

Now lets have look at Conventional Routing.

Until now we have defined endpoints in controller. Let’s define end points outside controller and access them. We are calling “MapGet” function to register the end point and their execution.

Below is definition of MapGet() method.

Now with the help of “HttpContext” we are modifying the response asynchronously. Below are the possible endpoint which we can have.

https://localhost:5001/ https://localhost:5001/routing/abhinav

Note: We can also have MapPost(),MapDelete(),MapPut() etc

Now let’s create endpoint where we will validate the endpoint.

“name:alpha” means name which passed should contain only alphabets.

You can have look at routing constraint here on msdn https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0#route-constraint-reference These constrain can be applied in attribute routing. Let’s say you do not pass any parameter to https://localhost:5001/validateinput/

Let’s say we want to make routing parameter optional. We just need append ? after parameter name.

You can see we have not passed parameter still request is getting executed.

How to save data is sql server using model validation and Auto mapper in .net Core Web API

Prerequisite

The .Net 5 SDK (https://dotnet.microsoft.com/download/dotnet/5.0)

Visual Studio Code (https://code.visualstudio.com/download)

C# Extension for Visual Studio Code (powered by OmniSharp)

Postman (https://www.postman.com/downloads/)

Basic Understanding of .Net code

In this article we will cover below things

1>Exposing DTO to client instead of actual model.

2>Use of “AutoMapper” to map the domain class with DTO class.

3>Using the class inheriting from “Profile” class to define the mapping.

4> Register classes inheriting from “Profile” class in Startup.cs inside function “ConfigureServices” using “AddAutoMapper” function.

5>Using the instance of “IMapper” to perform the mapping of  Domain class to DTO class using the mapping define in subclass of Profile class.

6> implementing [HttpPost] and creating Employee.

7>Use of Use of “CreatedAtRoute”

8>Model Validation using Custom Attribute e.g [Required]

You can see in below Screenshot our rest Api end point directly exposing the actual domain/Model class, as shown in below snapshot.

Ideally, we should not expose our implementation to outside world. We should create dto(data transfer object),which can be similar to our domain object or can differ in some properties.

We have created new class which we will expose to client (outside world).

Now how to convert the domain object(Employee) to dto object(EmployeeReadDto).We can write some code to achieve it. But we have readymade automapper available for it.

Let’s add the dependencies for above auto mapper in our project.

dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection

Once you have installed it. Let’s define our mapping. We will create folder Profiles inside which we will create class profile.

Our class “EmployeeProfile” is inheriting from “Profile” which is present in “AutoMapper” namespace. In constructor of our class we have defined our mapping from domain object to dto object(from “Employee” to “EmployeeReadDto”). Let’s register this class in “StartUp.cs”. Fist we need to add

using AutoMapper;

We need to add above namespace in class “StartUp.cs”.

The above highlighted line registers all the profile classes we declare in this project. So that, they can be used in Controller class.

Now let’s use auto mapper in our controller. First, we need add below namespace in controller.

using AutoMapper;

We have injected the instance for “IMapper” in constructor of controller class. We are using map function of instance “IMapper” for converting/mapping  the Employee class into “EmployeeReadDto”.

_mapper.Map<TragetObjectType>(Sourceobject);

Let’s run and test application.

As everything works fine, let’s move on to create Employee function.

We will extend our repository to create Employee. User will send request to create employee. So Let’s Extend our interface.

Let’s Implement the above contracts in our repository.

User should not be aware about real Employee. So, user will send request and we should map request  to employee object. So, let’s create dto which user will send to our web api create Employee.

User will not send the Id. It will generate by sql server. Now our controller will accept instance of “EmployeeCreatedto” to create Employee. So, our controller needs to map “EmployeeCreatedto” instance to “Employee” instance and then pass to repository for employee creation. So, lets write mapper and make changes in our controller.

We have just defined mapping as shown in above class.

Now let’s have look at controller.

In above function we have first done the mapping of dto and Employee class.

We will now test with postman.

You can see Description is not coming in response. As “EmployeeReadDto” instance is return by our web api does not have it. Everything looks fine. But once Employee is created client should get url to access that Employee. Let’s make changes in controller for this.

We have added the above line so that we get the url of new Employee created in response header. Now let’s run the code. Again, we can save the employee.

In header we have extra field name as location. Now let’s try to create employee without entering “description”.

As description is mandatory, we are getting error. But we are getting internal server error. Here mistake is from client side. Here comes the concept of Data validation. When HTTP request comes to web Api for particular action method ,then model binding helps to map that request to object expected by action method. But before the object reaches the action method the model validation happens. There are two ways through which model validation can happen.

1>Built in Validation through Data Annotation attribute

2>Custom Validation attribute

Let’s have look at First approach.

Let’s make change in class “EmployeeCreateDto”. We will use “DataAnnotation” attribute in our DTO for validation. As it makes error handling nice.

So to use attribute for validation we need to add using System.ComponentModel.DataAnnotations;

Now run the application and create employee using postman.

Now we are seeing bad request. So client will understand it’s his/her  mistake.

Note: Web API controllers don’t have to check “ModelState.IsValid” if they have the [ApiController] attribute. In that case, an automatic HTTP 400 response containing error details is returned when model state is invalid. Will see in Bit what is ModelState.

You can also give message according to your convenient.

Note: So, when you have decorated your controller with attribute [ApiController] then it is going to take care of model validation (due to Data Annotation Attribute). You can see in above screenshot we have not specified explicit handling of bad request in our Action method for model validation. You can visit below Link for other Data Annotation attribute.

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0

If you remove attribute [ApiController] from the controller and hit the postman then you will not see the automatically bad request coming when “description” is not passed in request although your field is decorated with [Required] attribute. You need to write explicit code in in your action method where you will add the error to “ModelState” and return “ModelState” in   BadRequest.

Now let’s have look at custom validation.

Let’s say we have scenario where we do not want client to enter special character in description while creating the employee. Let’s put this validation inside the api method.

Now if we try to save employee having special character in description then we will get bad request.

But this is violation of Single responsibility. As it is not Controller responsibility to perform the validation. So, we need to move this validation out of Controller. Here Custom validation Annotation comes in picture.

Now we will create Custom Annotation for Validation. To achieve it first we need to create class and derive from “ValidationAttribute” class and then Override the below method.

protected ValidationResult IsValid(object value,ValidationContext validationContext);

Have look at below screenshot for better understanding.

Let’s test using Postman.

Again controller will take care of everything (Sending the error message with BadRequest) as it is decorated with [ApiController].

Now let’s jump to one more concept regarding Validation of nullable type and non-nullable type. We have below function which take two parameters of non-nullable type. One parameter is of type reference type one is of value type.

[HttpGet("/ValidationNonNullable")]
 public ActionResult<string> ValidationNonNullable(string id,bool istest)
  {
              return $"The id value is {id} and istest value is {istest}";
  }

When we call above method and do not pass both parameters then below is result.

We can see in above screenshot that id is not printed (as default value is null) and “istest” is printed as it is value type and having default value false. Now here we can impose validation in two ways. Add Highlighted entry in your .csproj

Now run the application and test using postman.

You can see we have got the Validation only for Id field not for “istest”. The Id field is reference type, and the validation system treats non-nullable parameters or bound properties (reference type only) as if they had a [Required] attribute.

Note:This behavior can be disabled by configuring SuppressImplicitRequiredAttributeForNonNullableReferenceTypes in Startup.ConfigureServices:

services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

Now if we do not want to use above approach then we cause [Required] attribute.

Run the application and test using postman.

We can see both parameters are getting validated with this approach. Value type and Reference type does not matter.

We can achieve same thing in Nullable parameters also with help of [Required].

Data Binding

Now let’s take have look at example of Data Binding. Let’s say we have simple method which takes one parameter of type Boolean. We have simple method which takes a parameter of type Boolean and returns string.

[HttpGet("/DataBindingDemo")]
 public ActionResult<string> DataBindingDemo(bool istest)
 {
   return $"The  istest value is {istest}";
 }

You can see in above screenshot we are able to call the method correctly. If we pass the value  to api which is not Boolean then.

You can see when we are passing the value which cannot be type casted to Boolean then our controller is replying with “BadRequest” and error message. This is happening because our controller is decorated with [ApiController].

So internally here model binding is getting triggered and it is adding binding error two “ModelState”. “ModelState” has error from Data Validation and Data Binding errors. if you do not want this behavior then we need to write below piece of code in class “StartUp.cs” (method ConfigureServices)

services.Configure<ApiBehaviorOptions>(options => 
 {   
  options.SuppressModelStateInvalidFilter = true;     
 }
);

Patch Update,delete using Entity framework in .NetCore web API

The .Net 5 SDK (https://dotnet.microsoft.com/download/dotnet/5.0)
Visual Studio Code (https://code.visualstudio.com/download)
C# Extension for Visual Studio Code (powered by OmniSharp)
Postman (https://www.postman.com/downloads/)
SQL server Express(https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
Basic Understanding of .Net code.

In this article we will cover below things
1>Use of [HttpPut] to Update the Employee.
2> Use of [HttpPatch] to update the employee by not sending the whole object
3> Use of [HttpDelete]

Now let’s implement the update functionality for Employee. We will first create class,“EmployeeUpdateDto” which will be send by client to update the employee in update request.

Also, you can see in above screenshot we have updated the “EmployeeProfile” class for mapping of DTO to domain/model class. Now we will extend our repository interface with new method for update.

Will Implement this method in “EmployeeSqlRepository”. As you can see in above screenshot, in implementation of “UpdateEmployee” we are doing nothing. Because DBcontext will do it for us. We just need to call “SaveChanges”. Let’s see code in our controller.

You can see in above screenshot we are getting the “id” of Employee and “EmployeeUpdatedto” object in request to update employee. Using “Id” we are fetching the employee to be updated. If employee not found in database, then we return not found. If employee found, then we update the employee instance from database with “EmployeeUpdatedto” object received in request. Now we call function “UpdateEmployee” and “SaveChanges” to update employee.

Let update employee by running application from postman. First see what all employee available in database.

In screenshot I am not able to show full response (all employee records).

We will update the highlighted employee. Now let’s update employees using postman.

You can see above we are using PUT in the postman. As you can see in response, we have Status code 204, which we return from controller after successful update. Let’s verify using get verb. We have updated the city of user with id 3.

As “EmployeeReadDto” do not have description property hence we are not able to see it.

Patch Update

Now let’s concentrate on patch update. In patch updated we do not need to send the whole object like Update Employee. We just need to send the properties and their value which needs to be update.

We need to install below package in order to patch functionality work.

dotnet add package Microsoft.AspNetCore.JsonPatch

dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson

Once package is installed validate it “.csproj” file.

In “StartUp.cs” we need to import below namespace.

using Newtonsoft.Json.Serialization;

Let’s make changes in “StartUp.cs” class in the way we add our controller.

We need to also register new mapping (Shown in below Screenshot). Will see how it used.

We will use above mapping in our controller.

You can see in above screenshot the second parameter of function “PatchUpdateEmployee()” is of type  “JsonPatchDocument<EmployeeUpdatedto>”.

In function we are fetching the employee to be updated from repository using id. Then we are converting it to type of “EmployeeUpdateDto”. Then this object is updated from the “patchdoc” send by client. We then validate the updated object. Now after this step our steps will be nothing but the code of update employee.

So, in case of patch update user will not send the “EmployeeUpdateDto” hence we need to construct it from the “id” which we receive from client.

Let’s concentrate on employee with id 7. We want to update two properties name and city.

Let’s perform the patch update using Postman.

Now let’s verify record is updated correctly or not. As you can see we are able to update. Let’s have look at request.

[
 {
   "op": "replace",
   "path": "/name",
   "value": "Ankur"
 },
 {
   "op": "replace",
   "path": "/city",
   "value": "Jaipur"
 }
]

We have three properties “op”, “path” and “value”.  In “op” we specify operation. In “path” we give property to be updated prefix with forward slash. “value” contains the new value which needs to be updated.

There are several other operations which we can explore in future.

Delete

Let’s implement the Delete functionality. First, we need to introduce below function in contract “IEmployeeRepo”

void DeleteEmployees(Employee emp);

Then we need to implement in our repository.

Now call this function from our controller.

Now call the Api using postman.

We have got status as 204.It means delete operation was successful. Let’s verify in our get API. Now we are done.

We are getting response as not found because record is deleted.

How to connect to sql server using Entity Framework in .NetCore Web Api

Prerequisite

The .Net 5 SDK (https://dotnet.microsoft.com/download/dotnet/5.0) Visual Studio Code (https://code.visualstudio.com/download) C# Extension for Visual Studio Code (powered by OmniSharp) Postman (https://www.postman.com/downloads/) SQL server Express(https://www.microsoft.com/en-us/sql-server/sql-server-downloads) Basic Understanding of .Net code

In this article we will cover below things

In Previous tutorial, we implemented get verb using in memory repository where we had hardcoded data.
1>In this tutorial we will replace the in-memory repository with sql repository which will use entity framework to connect to sql server and perform the operation.
2>Also we will see how to resolve dependencies using nuget packages.
3>Use of Nuget package.
4>How to connect to database using Entity framework class “DBContext” and property of type DbSet.
5>How to read configuration using “IConfiguration”.
6>Use of method “AddDbContextMethod” in interface “IServiceCollection” for dependency injection.

Let’s install the packages/dependencies required for using Entity framework.Let’s go to nuget.

Install the highlighted package in order to make entity framework work .Just open terminal in Visual studio code.

dotnet add package Microsoft.EntityFrameworkCore

Similarly, we want to include below packages for using Entity Framework to connect to Sql server.

dotnet add package Microsoft.EntityFrameworkCore.Design

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Once you ran all command verify “.csproj” file to make sure all packages have been installed correctly.

You can see packages has been added in above screenshot. In short, these packages will be downloading all the dll required to run the entity framework.

Now in terminal run dotnet ef

If you are not getting above output means Entity framework is not installed correctly.  So, you need to run below command in terminal.

dotnet tool install –global dotnet-ef

Now let’s add class to communicate to database using entity framework.

We have added class “EmployeeContext” which will connect to database using “EntityFramework”. We need to make below changes in class in order to connect to database using EF.

This class should inherit from “DbContext”.

We must define constructor which will have parameter of type “DbContextOptions<EmployeeContext>” and constructor should call base constructor. The dependencies needed by constructor will be injected by dotnet framework. We must define property of type “DbSet<T>”, where T is our model(employee). Currently we have one model hence we have defined one property. So this class will help us to connect to Sql server and help us to perform different operation on Employee Entity/Model in Sql Database.

Note: To be able to connect to SQL Server Express using Entity Framework Core, we need to have a class that would inherit the EF Core “DbContext” class and hold the DbSets of tables and any configurations that might come along the mapping between the models and the actual Database tables.

Now let’s define the connection string to connect to sql server. We need to define the string in “appsetting.json”.

We can read the connection string in “Startup.cs” using “IConfiguration” instance using function “GetConnectionString”.

public IConfiguration Configuration { get; }
Configuration.GetConnectionString("EmployeeConnection");

Will see in bit use of this.

Note: In order to work with “ConnectionStrings(“Key”)” function, we should have “ConnectionStrings” defined in “appsetting.json” file, in which can define multiple connection string(properties)   defined. Let’s make change “Startup.cs” file so that dependencies needed by “EmployeeContext” class get resolved with help of connection string define above.

Let’s make change “Startup.cs” file so that dependencies needed by “EmployeeContext” class get resolved with help of connection string define above.

To be able to use the EmployeeContext directly in your controllers

and give it the required connection string to do the connection,

you will need to add it in the service collection of your .NET Core Project

Now “services.AddDbContext” will help to inject instance needed by constructor of “EmployeeContext”.

Inside the “AddDbContext”, we need to describe the options for our DBContext.

This can be done by a lambda expression, it is an action where we receive an option parameter and the Entity Framework can support the different databases. All we need to do is, tell the Entity Framework that this particular “DBContext” is going to use sql server ( “UseSqlServer”).

This method requires a parameter which is the connection string to be used to connect to database.

services.AddDbContext<EmployeeContext>(
opt => opt.UseSqlServer(Configuration.GetConnectionString("EmployeeConnection"))
);

Note: The above line registers a class called “EmployeeContext” (derives from “DbContext”)  as a scoped service in the ASP.NET Core application service provider (a.k.a. the dependency injection container). The context is configured to use the SQL Server database provider and will read the connection string from ASP.NET Core configuration.

The EmployeeContext class must expose a public constructor with a DbContextOptions<ApplicationDbContext> parameter

AddDbContext constructor takes input as lambda expression.

Note: Configuration.GetConnectionString(“EmployeeConnection”) will return the connection string defined in “appsetting.json” file. Below is the screenshot of my “sql server mangment studio”. Kindly login to your database using this tool.

There is way if you want to register the repository as singleton.

Now let’s open sql server. The password will be same which is same as which we have mention in connection string.

Let’s make some changes in Employee Model to do validation..

Now let’s create our migration script which will be generated on basis of property “DbSet<Employee> Employees”

dotnet ef migrations add InitialMigration

You can see migration folder has been created. It has files which have “InitialMigration” appended at last in their name.

We are interested in highlighted file.

Now let’s have look at database.

Now let’s run below command in terminal.

dotnet ef database update

Once above command is executed then refresh the database. You will find new database with table is created. Database name is same which we specified in connection string in “appsetting.json”.

We can see “EmployeeDB” is created which we specified in our connection string. Now we have inserted row in Employee table by right click “Edit Top 200 rows”.

You can id has been automatically generated.

Note: You can also insert by writing insert statement.

Let’s create the new repository which will fetch data from database using entity framework.

You can see that in constructor we are expecting the instance of “EmployeeContext”. Dot net core is going to do for us as we have already register the dependency needed in  in class “Startup.cs””.

Now we are done. Let’s run the app.

You can see we are able to fetch the data from sql database.

Creating the .Net core Web API

Prerequisite

The .Net 5 SDK (https://dotnet.microsoft.com/download/dotnet/5.0)

Visual Studio Code (https://code.visualstudio.com/download)

C# Extension for Visual Studio Code (powered by OmniSharp)

Postman (https://www.postman.com/downloads/)

Basic Understanding of .Net code.

In this article we will cover below things

In this tutorial we will be creating simple rest service using “Visual Studio code” Editor.We will be Exploring the get verb using mocked repository(In Memory Collection).Also we will have look at how to do dependecy injection in .net core is done.

For Creating the rest api in .Net core, Web api is most used template.

Open “Visual Studio code” Editor. Make sure no folder is open.if open then you can close using “File->Close Folder”

Now go to “View->Terminal”

Just type below command in Terminal(at bottom of visual studio code).

dotnet new

Now let’s create “webapi” project name “EmployeeWebApi”. Will use below command to create it.

dotnet new webapi -o EmployeeWebApi

The dotnet command creates a new application of type webapi (that’s a REST API endpoint). The -o parameter creates a directory named “EmployeeWebApi” where your app is stored.

You can see project created in above screenshot. Now to open newly created project you can fire below command or open from “File->Open Folder”.

cd .\EmployeeWebApi\

code .

once project is open in visual studio code.

Now you will be seeing below pop up.

Just click on Yes. It will add “.vscode” folder which has two files. These files will be used in development environment for building and running our project from Visual studio code. Will see use of these files. Let’s have look at below project structure.

 “Program.cs” will have main method and it has code to host service. It will call the “Startup.cs”. “Startup.cs” has code to set up service, middleware etc. we will see these file in detail  as we proceed  in this blog.

Now let’s have look “WeatherForeCastController.cs”. It has code for a simple API that returns the weather forecast for the next five days.

In .NET Core framework Web APIs are implemented in Controllers. Controllers are classes derived from the ControllerBase class. Web API project could be consisting of one or more controllers. All these controllers need to be derived from ControllerBase class.

ControllerBase class has various properties which we can use to handle REST requests. The Web API project which we have created from the template provides us starter Controller — “WeatherForecastController” as shown in above Screenshot.

Note: The constructor of above class is expecting the instance of “ILogger”. Now who will be injecting it ? Dot net framework will be injecting it. Will see how it’s done as we proceed in blog.

WeatherForecastController is decorated with ApiController attribute. Applying ApiController attribute enables some API specific behaviors such as attribute routing, Automatic HTTP 400 series responses, binding the source parameters from the request URLs, etc.

ASP.NET Core uses routing middleware to map the incoming request URL to the action that needs to be performed. The routes could be placed as attribute on the controller or action(method in controller). This way of defining routes for actions is called attribute-routed actions. The starter controller provided in the generated template has attribute-routed actions:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
 {

All the api exposed inside this controller will have string “WeatherForecast” in their end point path. Will see details in bit as we call the function inside controller.

APIs uses the HTTP protocols like GET, POST, PUT, and DELETE to link the resources with the actions that need to be performed. ASP.NET Core framework has following HTTP verbs which can be placed as attributes of the actions:

[HttpGet]

[HttpPost]

[HttpPut]

[HttpPut]

[HttpDelete]

[HttpHead]

[HttpPatch]

In the controller “WeatherForecastController”, we have one action Get() . Get() action has HttpGet attribute which indicates this action uses the HTTP GET protocol. Now let’s have look at file “launchsetting. json”

Now when we run this web api, then we will be able to access API at highlighted url. So below will be path.

https://localhost:5001/WeatherForecast

http://localhost:5000/WeatherForecast

“WeatherForecast” is the routing path we provided at controller .Now before running our application we need to do run below command

dotnet dev-certs https –trust

Let’s build and then run our service using below command.

dotnet build

dotnet run

Note: You might get message “disable ssl version”. You can select yes.

Now in below screenshot we can see although we are calling “http” end point, but request is getting redirected to “https” endpoint.

This is happening because of below line of code in “Startup.cs”.

Note: If you comment the above line then redirection will not happen. For swagger UI to work in Dev environment you need to comment. Otherwise, you will get error “type error: fail to fetch”.

Note: In above Configure method we can configure different Middleware’s pipeline.  Middleware is a software component that hooks into the request pipeline to handle web requests and generate responses.

Each middleware Process manipulates the request as it is received from the previous middleware. It may decide to call the next middleware in the pipeline or send the response back to the previous middleware (terminating the pipeline )

To start using any Middleware, we need to add it to the Request pipeline. This is done in the Configure method of the startup class. The Configure method gets the instance of IApplicationBuilder, using which we can register our Middleware. So, all function called using “app.” are middleware.

So, if any request comes to Web Api it will pass through middleware defined in  “Configure” method.  First “UseRouting()” will be called then it will call the middleware   “UseEndpoint” to  map the request to the action function(endpoint) inside controller. The dependencies need for this middleware and Web api is done in method “ConfigureServices()”. “AddControllers” method should be call inside the “ConfigureServices()” in order to inject the dependencies required for middleware “UseEnpoints”.

Dot net core 5 has inbuilt support for Swagger. We can hit below url . It UI where you can view detail about all the api which you have exposed inside your controller. You can also call your api from swagger and test it.

http://localhost:5000/swagger/index.html

You can see we are not able to fetch data. We can see “Type error”. We need to so small change in return type of our api return type.

Now Swagger UI will work perfectly fine.

Now we are fine.

ActionResult<T>: during the execution of some of the actions, the specific type could not be returned due to various reasons like a failure in model verifications or unexpected exceptions during execution. In such cases, ActionResult<T> should be returned which enables to return of either type deriving the “ActionResult” or specific type. Now in this series we will create service which will perform below operations for type “Employee”.

So here we will create service related to employee crud operation. In this blog we will cover first two rows (only Get verb).

Above will be architecture of our service/rest Api/Web Api. Client will call service then inside service controller will take request and will pass the request to repository and then repository will give the result back to controller which will be return by controller. As we are going to see Get verb hence result will single employee or collection of employees in success scenario.

Now let’s create Model’s folder. We will create our Employee model.

We have created model with four properties.

Now add folder “Data”. Let’s define contract for our repository.

We have created contract “IEmployeeRepo”.

Now let’s implement this contract in below class which is created inside folder repository. We have hard coded data here.

Now let’s add our controller.

You can see the class is decorated with [ApiController]. Also, in [Route] we have specified the path to access this service. Now all Api end point path will not have controller name in their endpoint path. Also, you have to inherit your controller from “ControllerBase”.

Now let’s add end point.

You can see each method is decorated with [HttpGet]. As both methods will be fetching using Get verb of HTTP.Each Method has return type of Action<T>.

We are calling return in Ok.

Now let’s make small change in “launchSetting.json

Note: applicationurl+controller address will make address to access the endpoint.

https://localhost:5001/api/Employees

http://localhost:5001/api/Employees

Now run the application using below command.

dotnet run

Now let’s access the service usingpostman.

You can see that we are getting status as ok as we have returned Ok. Let’s query the employee with Id 1.

Now let’s use dependency injection. We are creating the instance of mocked repository in our controller. Ideally controller should be only aware about the contract not the real instance. Let’s use it.

Now when the application will run then instance of “EmployeeMockedRepository” will be injected in constructor of above controller class.Now how .Net core will do it. We need to tell it by registering the repository instance in function “ConfigureServices(IserviceCollection service)” of “StartUp.cs”.

ASP.NET Core provides a built-in service container, IServiceProvider. Services are typically registered in the app’s “Startup.ConfigureServices” method.

Services.AddSingleton<IEmployeeRepo,EmployeeMockedRepository>();

Now we are done. Just query with postman you will get same result.

Note: Whenever we ask for the instance of type “IEmployeeRepository”, the DI Container must decide whether to return a new instance of the service or provide an existing instance.

The Lifetime of the Service depends on how we instantiate the dependency. We define the lifetime when we register the service. We learned how to register services startup.cs. There are three ways, by which you can do that. And it in turn decides how the DI Framework manages the lifecycle of the services.

Transient: creates a new instance of the service, every time you request it.

Scoped: creates a new instance for every scope. (Each request is a Scope). Within the scope, it reuses the existing service.

Singleton: Creates a new Service only once during the application lifetime, and uses it everywhere

You can have look at above lifecycle in this blog.

Which collection you will use to store unique item in c#

HashSet<T> is used to store unique item in c#.Let’s create class Employee which we will be using in our application.

public class Employee
{
    public  int Id{get;set;}
    public  string Name{get;set;}
    public  DateTime JoiningDate {get;set;}
}

Let’s have look at Simple example use of HashSet with respect to value type and String/Reference Type.

In Output you can see that HashSet is working perfect for Value type and String. It is not allowing to duplicate value getting added. But for Employee (a reference type), it is not working expected. We are able to add to add duplicate employee.

This is because HashSet does not know what properties of Employee it should use to determine uniqueness of Employee. Let’s say we want to use “Name” and “Id” to determine the uniqueness of Employee. There are two approaches.

Note: When you add value type or string in HashSet<T> then it will contain unique hash key for each item. HashSet<T> will use this key to uniquely identify elements in HashSet<T>.For reference type HashSet<T> will use GetHashCode() and Equals() to create unique Hash Key.

Approach1

1>Overriding “bool equals(object obj)” and “int GetHashCode()”. HashSet or other collections like List, Dictionary etc calls “Equals” to determine the uniqueness of item. Both these method are virtual and present in Object class. So when you override the equals then its thumb rule to override the GetHashCode(). Refer blog


    public class Employee
   {
       public  int Id{get;set;}
       public  string Name{get;set;}
       public  DateTime JoiningDate {get;set;}

       public override bool Equals(object obj)
        {
            // If the passed object is null
          
            if (obj == null)
            {
                return false;
            }
            if (!(obj is Employee))
            {
                return false;
            }
            return (this.Id == ((Employee)obj).Id)
                && (this.Name.Equals(((Employee)obj).Name));
        }
        public override int GetHashCode()
        {
            return Name.GetHashCode() ^ Id.GetHashCode();
        }
   }

Now let’s run the program.

You can see now duplicate employee is not getting added.

Note: In case of String “Equals” is overridden by .Net Framework to compare String.

Approach 2

We can Implement IEquatable<T>.We need to implement its method “bool Equals(T obj)” and then override “int GetHashCode()” method of object class.

 public class Employee :IEquatable<Employee>
   {
       public  int Id{get;set;}
       public  string Name{get;set;}
       public  DateTime JoiningDate {get;set;}

        public bool Equals(Employee obj)
        {
           if (obj == null)
            {
                return false;
            }
               return (this.Id == obj.Id)
                && (this.Name.Equals(obj.Name));
        }
        /*When you implement Equals you should also oveeride getHascode*/
        public override int GetHashCode()
        {
            return Name.GetHashCode() ^ Id.GetHashCode();
        }
    } 

Now run the program you will get same result.

From MSDN

The IEquatable(T) interface is used by generic collection objects such as Dictionary(TKey, TValue), List(T), and LinkedList(T) when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove.

If you have implemented Equals(T Obj) of IEquatable interface and Overriden Equals(object obj) from object class the Framework will use Equals(T Obj) of IEquatable interface .

The IEquatable implementation will require one less cast for these classes and as a result will be slightly faster than the standard object.Equals() method that would
be used otherwise.

When class Implements IEquatable for uniqness then its child class should also implement it ,if child class will used in collection.

 public class ContractEmployee : Employee,IEquatable<ContractEmployee>
    {
        public bool Equals(ContractEmployee obj)
        {
         /*Here you can give your implementation instead of calling base         function*/
           return base.Equals(obj as Employee);
        }

        public override int GetHashCode()
        {
             /*Here you can give your implementation instead of calling base function*/
           return base.GetHashCode();
        } 
       
       //Some More Properties and functions
    }

Now let’s have look some of operations which we can perform with help of HashSet.

 HashSet<string> hashSet1 = new HashSet<string>() { "10", "20", "30", "40" };
 HashSet<string> hashSet2 = new HashSet<string>() { "20", "40", "30", "80" };
 HashSet<string> hashSet3 = new HashSet<string>() { "10", "20","30","40","50" };
if (hashSet1.IsProperSubsetOf(hashSet3)) //true
    Console.WriteLine("hashSet3 contains all elements of hashSet1.");
if (!hashSet1.IsProperSubsetOf(hashSet2)) //False
   Console.WriteLine("hashSet2 does not contains all elements of hashSet1.");

UnionWith

 HashSet<string> hashSet1 = new HashSet<string>() { "30", "40" };
 HashSet<string> hashSet2 = new HashSet<string>() { "20", "40", "60", "80" };
 hashSet1.UnionWith(hashSet2); //hashSet1 -> 30, 40, 20, 60, 80
 foreach(var item in hashSet1)
 {
  Console.WriteLine(item);
 }

IntersectWith

HashSet<string> hashSet1 = new HashSet<string>() { "30", "40", "80" };
HashSet<string> hashSet2 = new HashSet<string>() { "20", "40", "60", "80" }
hashSet1.IntersectWith(hashSet2); //40,80

ExceptWith

HashSet<string> hashSet1 = new HashSet<string>() { "10", "20", "30", "50", "60" };
HashSet<string> hashSet2 = new HashSet<string>() { "10", "20", "30", "40" };
hashSet1.ExceptWith(hashSet2);//hashSet1 -> 50, 60

SymmetricExceptWith

HashSet<string> hashSet1 = new HashSet<string>() { "10", "", "3", "5", "6" };
HashSet<string> hashSet2 = new HashSet<string>() { "1", "2", "3", "4" };
hashSet1.SymmetricExceptWith(hashSet2);//hashSet1 -> 4, 5, 6

HashSet<T> VS List<T>

Unlike a List<> …

1>A HashSet is a List with no duplicate items.

2>Because a HashSet is constrained to contain only unique itemss, the internal
structure is optimised for searching (compared with a list) – it is considerably faster

3>Adding to a HashSet returns a boolean – false if addition fails due to already existing in Set

4>Can perform mathematical set operations against a Set: Union/Intersection/IsSubsetOf etc.

5>HashSet doesn’t implement IList only ICollection

6>You cannot use indices with a HashSet, only enumerators.
HashSet objcollection=new HashSet();
objcollection[0];

The main reason to use a HashSet would be if you are interested in performing Set operations.

Given 2 sets: hashSet1 and hashSet2

//returns a list of distinct items in both sets
HashSet set3 = set1.Union( set2 );
flies in comparison with an equivalent operation using LINQ. It’s also neater to write!

A>Even though addition is O(1) in both cases, it will be relatively
slower in HashSet since it involves cost of precomputing hash code
before storing it.
B>The superior scalability of HashSet has a memory cost. Every entry
is stored as a new object along with its hash code