One of the essential elements in any technological system is its ability to pick and understand the most effective .Net Libraries that enable improving the development process. The rapid growth of the online marketplace is in line with the rise of the digital population.There appears to be lots of activity and the amount of competition between companies and developers is increasing.
One such technology that helps in providing services that are friendly for customers and users includes that of the .NET framework. Microsoft’s. NET Core Framework has been an incredible success. It enables .NET developers to build strong high-quality, efficient, and feature-rich websites on the go, and .NET applications.
While the .NET development business is growing quickly, it is creating more libraries to satisfy the diverse needs of developers. So, listed below are the top most important .NET libraries that .Net developers use when developing .NET apps. They will assist in your choice and comprehension of the various class libraries that are portable and considered essential to .NET Core integration.
Benefits of AutoMapper
AutoMapper
When developers employ AutoMapper for mapping the properties of two different types of objects they have proven its ability as an object-to object mapper library. AutoMapper makes it easy to set up types for mapping and testing. Methods for mapping objects perform the conversion from one type of object to another. AutoMapper offers attractive standards to help you avoid the hassle with manually converting one kind to another. Since issues in one layer are often in conflict with issues in the other object-object mapping produces partitioned models where issues in a specific layer only affect specific types at this level.
Benefits of AutoMapper
Maps that are easier to use
If you’re using AutoMapper You can test the mapping using Unit tests at one place to save time and energy.
Code that is Clean
Transferring data among distinct objects requires the smallest number of lines. A shorter development time is directly derived from a simpler program since it takes less effort to create maps between objects.
Excellent maintainability
Similar mappings between both items is centralized in one place that makes it much easier to manage
Let’s See How to Use AutoMapper Library
Step 1: Here are the Employee entity and Employee view model classes.
public class Employee
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; }
public string Email get; set; }
public DateTime CreatedDate { get; set; } = DateTime.Now;
public class EmployeeViewModel
{
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
}
Step 2: In order to implement AutoMapper, first we should download a NuGet Packages to our project:
Step 3: Create a mapping profile that specifies how to map the properties between the Employee entity and the EmployeeViewModel.
public class MappingProfile: Profile
{
public MappingProfile()
{
CreateMap()
.ForMember(dest=> dest.Name, opt=> opt.MapFrom(src => src.Name))
.ForMember(dest=> dest.Email, opt=> opt.MapFrom(src => src.Email));
}
}
Step 4: After creating the proper mapping profile class, the next step is to register AutoMapper as a Service in the Program.cs file.
// Add services to the container,
builder.Services.AddA flapper(typeof(Program).Assembly);
builder.Services.AddControllersWithViews();
vår app = builder.Build();
Step 5: We can map Employee entities with EmployeeViewModel in the controller methods.
using AutoMapper:
using Microsoft.AspNetCore.Mvc;
using PracticeAPP.Models;
using PracticeAPP.Models.Entities;
using PracticeAPP.Models.ViewModels;
using System.Diagnostics;
namespace PracticeAPP.Controllers
public class HomeController: Controller
{
private readonly ILoggerloggerlogger;
private readonly IMapper_mapper;
public HomeController(ILoggerlogger, IMapper mapper)
{
_logger= logger;
_паppег= mapper;
}
public IActionResult Index()
{
return View();
}
public IActionResult Register(EmployeeViewModel model)
if (!ModelState.IsValid)
return BadRequest(ModelState);
var employee= _mapper.Map(model);
return View(employee);
}
Polly
Polly is an .NET library that addresses temporary faults and retries. It also offers programmers a clear and safe approach to define rules such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback.
In addition, with only two lines of code Polly will protect resources and stop the making of queries to services that are not working or retrying unsuccessful requests. prior cache results, stop long-running queries, and, in the worst case scenario offer a default response. Polly is also thread-safe, and works with both Asynchronous and synchronous calls.
Polly allows users of the .NET ecosystem to utilize try..catch and when integrated into an environment that is distributed it could assist in calling various processes, databases and other.
Benefits of Polly
Effective Policies
Polly can deal with temporary issues and provides the capacity to handle them and provides. Retry, Circuit Breaker, Bulkhead Isolation Timeout as well as Fallback are all policies of Polly which can be utilized to make these abilities work.
Thread-safety
None of the policies from Polly pose an issue for thread safety. The policies can be safely reused across multiple call sites, and run in parallel across multiple threads.
Let’s See How to Use Polly Library
Polly is a .NET resilience strategy and a transient fault management library that allows developers to define resilience-related policies, such as Retry policy and circuit Breakers, Timeout, Bulkhead Isolation policy, and Fallback. Polly is targeted at ASP.NET Core, which makes it a crucial tool to help with. NET Core resilience.
Swashbuckle
Utilize the .NET library to produce polished API documentation. It is possible to make use of Swagger’s Swagger UI to examine and play around with API actions within Swashbuckle too. Its main function is to create a Swagger specification file to be used in the .Net-based project. This program is a full set of tools that can be used to create .NET APIs. It might surprise you to know that we used C# instead of JavaScript to create this.
Benefits of Swashbuckle
Documentation
It allows you to rapidly and effortlessly provide stunning API documentation in a browser by creating an OpenAPI definition using controllers, routes and models.
Authentication Mechanism
Multiple authentication methods are provided by Swashbuckle It supports OAuth2, API keys along with JWT (JSON Web Tokens).
There are three main components to Swashbuckle
Swashbuckle .AspNetCore .Swagger
A Swagger model of objects and middleware that exposes SwaggerDocument object models as JSON endpoints.
Swashbuckle .AspNetCore .SwaggerGen
A Swagger generator that creates SwaggerDocument objects straight from your controllers, routes and models. It’s usually combined with Swagger endpoint middleware to expose Swagger JSON.
Swashbuckle .AspNetCore .SwaggerUI
An integrated version of Swagger’s UI tool. It uses Swagger JSON to build a customized and rich experience for explaining the web API capabilities. It comes with test harnesses built-in in the open methods.
Let’s See How to Use Swashbuckle Library
Step 1: Install the Swashbuckle.AspNetCore.
Step 2: Now, please Configure the program.cs file for swagger and the application you are able to check the API via Swagger.
//Add AddSwaggerGen
builder.Services.AddSwaggerGen();
builder.Services.AddControllersWithViews();
vår app = builder.Build();
//Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
//Config Swagger for Dev
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
CacheManger
- To help the cache providers that are part of .NET features that are enhanced for implementation, CacheManager was built as an open-source .NET Network library for C#. C# programming language.
- By using CacheManager, the .NET CacheManager library, developers can streamline their work and deal with even the most complex cache scenarios with just two pages of code.
Benefits of CacheManger
Seamless Coding
Because of the possibility for the possibility of concurrency, making changes to a value in a distributed environment can be a challenge. CacheManager removes the complexity and allows you to accomplish this in a single page of your code.
Sync Mechanism
It is possible to keep local instances in sync by using multiple layers with a distributed cache layer and running multiple instances of your application running.
Cross-platform Compatible
CacheManager has been updated to include cross-platform compatibility. It has tested for cross-platform compatibility across Windows, Linux, and iOS because of the new .NET Core/ ASP.NET Core structure of the project and the libraries.
Let’s See How to Use CacheManger Library
Step 1: Add Configuration for CatcheManager in the Program.cs file.
services.AddLogging (c => c.AddConsole() .AddDebug().AddConfiguration (Configuration));
services .AddCacheManager Configuration (Configuration,cfg=> cfg.WithMicrosoftLogging (services));
services .AddCacheManager (Configuration, configure: builder => builder. WithJsonSerializer());
services .AddCacheManager (inline => inline. WithDictionary Handle());
services .AddCacheManager();
Step 2: Now, We will use CacheManager in Values Controller.
[Route("api/[controller]")]
public class ValuesController: Controller
{
private readonly ICacheManager _cache;
public ValuesController(ICacheManager valuesCache, ICacheManager intCache, ICacheManager dates)
{
_cache = valuesCache;
dates.Add("now", DateTime.UtcNow);
intCache.Add("count", "1");
}
// DELETE api/values/key
[HttpDelete("{key}")]
public IActionResult Delete(string key)
{
if (_cache.Remove(key))
{
return Ok();
}
return NotFound();
}
// GET api/values/key
[HttpGet("{key}")]
public IActionResult Get(string key)
{
var value = _cache.GetCacheItem(key);
if (value == null)
{
return NotFound();
}
return Json(value.Value);
}
// POST api/values/key
[HttpPost( “{key}")]
Public IActionResult Post(string key, [FromBody]string value)
{
if (_cache.Add(key, value))
{
return Ok();
}
return BadRequest("Item already exists.");
}
// PUT api/values/key
[HttpPut("{key}")]
public IActionResult Put(string key, [FromBody]string value)
{
if (_cache. AddOrUpdate(key, value, (v) => value) != null)
{
return Ok();
}
return NotFound();
}
}
Dapper
To ease communication between applications and databases You could make use of Dapper which is an Object-Relational Modeler (ORM) that can be described more specifically. Micro ORM that works with SQL server. Dapper lets you write SQL statements using the same format as SQL Server. Dapper’s speed is unbeatable since it doesn’t modify SQL queries made within .NET. Dapper is able to execute procedures either in synchronous or asynchronous fashion.
Benefits of Dapper
Size : It’s light, and simple to operate and access.
Security : Dapper is not affected by SQL Injection so that you can run parameterized queries without restriction. The assistance offered by several databases is a further important aspect.
Database Compatibility : Dapper can be used with a wide array of database services. Dapper is an extension of ADO.NET’s IDbConnection that adds convenient methods to interact using your database.
Let’s See How to Use Dapper Library
Step 1: Let’s start by creating a new Entities folder with two classes inside
public class Employee
{
public Guid Id { get; set; } Guid. NewGuid();
public string Name { get; set; }
public string Email { get; set; }
public DateTline CreatedDate { get; set; } = DateTime.Now;
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public List Employees { get; set; } = new List();
}
Step 2: Now, we are going to create a new Context folder and a new DapperContext class under it:
public class DapperContext
{
private readonly IConfiguration _configuration;
private readonly string _connectionString;
public DapperContext(IConfiguration configuration)
{
_configuration = configuration;
_connectionString =_ configuration.GetConnectionString("SqlConnection");
}
public IDbConnection CreateConnection()
=> new SqlConnection(_connectionString);
}
Step 3: We have to do the registration in the Program class:
builder.Services.AddSingleton();
builder.Services.Add Controllers
Step 4: Now We have to create Repository Interfaces and Classes and Then, let’s implement this method in the class:
public interface ICompanyRepository
{
public Task> GetCompanies();
}
using Dapper;
using PracticeAPP.Context;
using PracticeAPP.Contracts;
using PracticeAPP.Models.Entities;
namespace PracticeAPP.Repository
{
public class CompanyRepository: ICompanyRepository
{
private readonly DapperContext _context;
public CompanyRepository(DapperContext context)
{
_context = context;
}
public async Task> GetCompanies()
{
var query= "SELECT * FROM Companies";
using (var connection = _context.CreateConnection())
{
var companies = await connection.QueryAsync(query);
return companies. Tolist();
}
}
}
}
Ocelot
Ocelot can be described as an asp.net core library that acts as an API bridge to .NET APIs. It is targeted at a group of .NET developers that require an interface for their decentralized services as well as microservice functionality. However, it can work on any platform where ASP.NET Core is accessible and can be used with any application that can understand HTTP.
It tricked its HTTP Request object into a state it is able to determine by its parameters, until it is transformed through a middleware for request building. A HTTP request message is created from there, and then used to connect with an online service. The Ocelot pipeline is completed with the sending of the request to middleware. Following that the middleware ceases to make calls. middleware will be made. When requests are made upstream along the Ocelot pipe, they will be followed by an answer by the service downstream.
This is how the Ocelot API Gateway Works in our project.
Benefits of Ocelot
Usability : Request aggregation, routing web sockets, rate-limiting authentication, authorization caching, load-balancing and configuration. are just a few of the numerous applications for this net central module.
Let’s See How to Use Ocelot Library
Step 1: You should add Ocelot to the service container by calling the AddOcelot method in the ConfigureServices method of the Startup class as shown below:
public void ConfigureServices(IServiceCollection services)
{
Action settings = (x) =>
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
}).WithDictionaryHandle();
}; services.AddOcelot(Configuration, settings);
}
public async void Configure(IApplicationBuilder app, IHostingEnvironment env )
{
await app.UseOcelot();
}
Run the projects.
Now make sure that you’ve made all projects as startup projects. To do this, follow these steps:
1. In the Solution Explorer window, right-click on the solution file.
2. Click “Properties”.
3. In the “Property Pages” window, select the “Multiple startup projects” radio button
4. Click Ok.
Autofac
To support .NET programs, Autofac provides an IoC container. It allows programs to be flexible when they grow in terms of size and complexity, by regulating inter-class relations. To accomplish this aim, developers can utilize standard .NET classes as elements.
Benefits of Autofac:
Flexibility : Autofac doest-net library manages inter-class dependencies that allow programs to be flexible, even when their complexity and size increase.
Community support : The majority of ASP.NET developers select Autofac as their preferred DI/IoC container because it’s compatible with .NET Core architecture without any problems.
Let’s See How to Use Autofac Library
Step 1: Install Autofac and Autofac.Extensions.DependencyInjection nuget package
Step 2: The code in program class will change to use Autofac as the DI container.
builder.Host. UseServiceProviderFactory (new AutofacService ProviderFactory());
Step 3: We will create a class and interface with a method to return a static string.
using PracticeAPP.Contracts;
namespace PracticeAPP.Repository
{
public class AutofacRepository: IAutofacRepository
{
public string getStringAutofac()
{
return "Hello Autofac Data";
}
}
}
namespace PracticeAPP.Contracts
{
public interface IN Autofac Repository
{
public string getStringAutofac();
}
}
Step 4: Finally, I will update the Controller to use the interface to return the constant text “Hello Autofac Data” as a return to the GetStringAutofac method.
using Microsoft.AspNetCore.Mvc;
using PracticeAPP.Contracts;
namespace PracticeAPP.Controllers
{
public class AutofacController: Controller
{
private readonly IN Autofac Repository _autofacRepository;
public AutofacController(IAutofacRepository autofacRepository)
{
this._autofacRepository=autofacRepository;
}
// GET api/values
[HttpGet]
public string GetStringAutofac()
{
return _autofacRepository.getStringAutofac();
}
}
}
MediatR
A person who describes the dynamic between several parties is described as the mediator pattern within the area of development software. This pattern is categorized as a behavioral one because it is able to modify the behavior of the program while it is in use.
MadiateR is a basic application of the mediator within .NET. Request/response, instruction, questions as well as notifications and instances. In this library, both the synchronous and asynchronous functions are enabled by the clever distribution and dispatching C# generic variance.
MediatR could be viewed to be an “in-progress” version of Mediator that allows the creation of CQRS systems. In the plethora of useful .Net libraries, MediatR stands out.
Benefits of MediatR:
Seamless Coding
Because of the possibility for the possibility of concurrency, making changes to a value in a distributed environment can be a challenge. CacheManager removes the complexity and allows you to accomplish this in a single page of your code.
Reduced Dependencies
The direct dependence on numerous objects can be reduced by using the MediatoR pattern to make them cooperative.
Communication
It serves as the primary means of interaction between your user interface and your data storage system. Classes provided by MediatR in .NET Core facilitate efficient, freely linked communication between numerous objects
Let’s See How to Use Autofac Library
Step1: Create a new web API project.
Step 2: Create a folder with these three classes.
Step 3: ApiRequestModel: This class represents a request for API.
using MediatR;
namespace MediatrApiProject.APIFolder
{
public class ApiRequestModel: IRequest
{
public int Number { get; set; }
}
}
— IRequest<> It represents a request with a response.
Step 4: ApiResponseModel: This class represents a response of API.
namespace MediatrApiProject.APIFolder
{
public class ApiResponseModel
{
public string Response { get; set; } = string.Empty;
}
}
Step 5: ApiHandler: And this class keeps the Media R
using MediatR;
namespace MediatrApiProject.APIFolder
{
public class ApiHandler: IRequestHandler
public async Task Handle(ApiRequestModel apiRequest, CancellationToken cancellationToken)
{
var response = $"Number :- {apiRequest.Number}";
return new ApiResponseModel
{
Response=response
};
}
}
Step 6: ApiHandler: MediaR
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace MediatrApiProject.Controllers
[ApiController]
[Route("api/[controller]")]
public class APIControllerBase : ControllerBase
{
private ISender _mediator;
protected ISender Mediator => mediator ??= HttpContext. RequestServices.GetService();
}
Step 7: ApiHandler: And this class for MediaAPIFolder
using MediatrApiProject.APIFolder;
using Microsoft.AspNetCore.Mvc;
namespace MediatrApiProject.Controllers
{
public class HomeController: APIControllerBase
{
public HomeController() { }
[HttpGet(nameof(ApiController))]
public async Task> ApiController(int number)
{
try
{
var request = new ApiRequestModel { Number = number };
return await Mediator.Send(request);
}
catch (Exception ex)
{
throw;
}
}
}
}
Step 8 : Test this API using swagger.
Fluent Validation
Fluent Validation is an .NET Framework class library used to build validation rules that can be highly constructed. Fluent Validation can be a fantastic alternative to annotations of data for validation of models. It allows for a greater separation of problems as well as a better control of validation rules and makes them simple to understand and test. The Lambda expression is used to verify the authenticity of. When you require complex validation for users’ data Fluent Validation is a great tool.
Benefits of Fluent Validation
Open-source
Fluent Validation is an .NET framework-based class library that allows making validating rules which are well constructed. Fluent Validation is a great alternative to data annotations in model validation. It allows for a greater separation of problems as well as a better control of validation rules and makes them easier to understand and test. The Lambda expression is used to verify the validity of. When you require complex validations for users’ data Fluent Validation is a great tool
Code Quality
By removing the need for annotations to data during the creation of a public class that can be used to test Your models, the FluentValidation can help create code that is simpler, easier to manage, and more reliable.
Let’s See How to Use Fluent Validation Library
Step 1: Create Employee class:
public class Employee
{
public Guid Id {get; set; }= Guid.NewGuid();
public string Name { get; set; }
public string Email { get; set; }
public DateTime CreatedDate { get; set; } DateTime.Now;
}
Step 2: Validated using a EmployeeDtoValidator. These classes are defined as follows:
public class EmployeeDtoValidator: AbstractValidator
{
public EmployeeDtoValidator()
{
RuleSet("name", () =>
{
RuleFor(x => x.Name). NotNull().WithMessage("name could not be null");
});
RuleSet("email", () =>
{
RuleFor(x => x.Email).NotNull().WithMessage("email could not be null");
});
}
}
Step 3: Configure validator class in program file.
builder.Services.AddScoped, EmployeeDtoValidator>(); builder.Services.AddValidatorsFromAssemblyContaining ();
Step 4: With the manual validation approach, you’ll inject the validator into your controller and invoke it against the model.
For example, you might have a controller that looks like this
public class EmployeeController: Controller
{
private IValidator _validator;
public EmployeeController(IValidator validator)
{
//Inject our validator and also a DB context for storing our Employee object.
_validator = validator;
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public async Task Create(Employee employee)
{
var result= await _validator.ValidateAsync(employee);
if (!result.IsValid)
{
//re-render the view when validation fails.
return View("Create", employee);
}
TempData["notice"] = "Employee successfully created";
return RedirectToAction("Index");
}
}
SignalR
One of the main goals of modern application development is to provide users real-time information. If you’re developing an application, game or any other type of application that you’re developing, you could benefit from real-time functions. The capability of your server-side software to quickly transmit information to other clients is a sign of real-time capabilities. In this instance we will require SignalR within .Net Core. It also simplifies the process dramatically. Similar to a chatroom, SignalR automates the management of connections and lets you send messages to everyone simultaneously.
You can incorporate SignalR hubs written in C# in the .NET Core project along with your APIs and pages. Additionally, the basic approach to programming naturally integrates other advanced features in NET such as dependency injection and authorization, authentication and the ability to extend.
SignalR is an open source library that allows you to create real-time web applications within ASP.NET Core. SignalR has an API that enables server-side software to transmit messages to browsers on the client.
Benefits of SignalR:
Real-time Functionality
SignalR is a no-cost and open-source software that allows you to integrate real-time features onto the internet. By using server-side programming, data can be sent to clients in real time thanks to the capability of real-time on the web.
Networking
The ability to broadcast messages to all clients on the network at the same time. It allows communication between clients, both individually and in groups being capable of accommodating many more users.
Let’s See How to Use SignalR Library
Step 1: Install SignalR NuGet package:
ntegrate the SignalR library into your project to enable real-time communication
Step 2: Register services and CORS policy
builder.Services.AddSignalR();
builder.Services.AddCors options => {
options.AddPolicy ("CORSPolicy", builder=>
builder .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .SetIsOriginAllowed ((hosts) => true));
};
Step 3: Define IMessageHubClient interface: Create an interface inside the “Hub” folder, outlining the methods for sending offers to users.
public interface IMessageHubClient
{
Task SendOffersToUser(List message);
}
Implement MessageHubClient class: Develop the actual SignalR hub that extends the IMessageHubClient interface. This class manages to send offers to clients.
public class MessageHubClient: Hub
{
public async Task SendOffersToUser(List message)
{
await Clients.All.SendOffersToUser(message);
}
}
Step 4: Design a controller responsible for handling offers. Inject the IHubContext to enable sending messages via SignalR.
public class OfferController: Controller
{
private IHubContext messageHub;
public OfferController(IHubContext_messageHub)
{
messageHub = messageHub;
}
[HttpPost]
[Route("electronic offers")]
public string Get()
{
List offers = new List();
offers.Add("28% Off on IPhone 12");
offers.Add("15% Off on HP Pavilion");
offers.Add("25% Off on Samsung Smart TV");
messageHub.Clients.All.SendOffersToUser(offers);
return "Offers sent successfully to all users!";
}
}
MailKit
MailKit is among the most popular Net Standard libraries. It is the top of MimeKit which is a .net main library that powers email clients that are cross-platform. The aim of this project is to provide robust, rich, feature-packed, and fully compatible RFC SMTP, POP3, and IMAP client network implementations.
Benefits of MailKit
Security : Simple Authentication and Security Layer (SASL) Authentication.
Proxy Support:Proxy support for SOCKS4/4a, SOCKS, and HTTP.
Let’s See How to Use MailKit Library:
Step 1
For sending an email, we must provide SMTP server information, together with the email address we wish to send emails to. The application should not be able to hardcode the details as they may alter over time and need updates. It is also easier to manage by other programmers. Below is the code in appsettings.json.
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MailSettings": {
"DisplayName": "Developer Test",
"From": "test@dev-test.dk",
"Host": "smtp.test.email",
"Password": "upPftsKAqgcFKKmXBW",
"Port": "587",
"UserName": "dev.test@test.email",
"UseSSL": false,
"UseStartTls": true
}
Step 2: Create a MailSettings object file like below.
public class MailSettings
{
public string? DisplayName { get; set; }
public string? From { get; set; }
public string? UserName { get; set; }
public string? Password { get; set; }
public string? Host { get; set; }
public int Port { get; set; }
public bool UseSSL { get; set; }
public string UseStartTls (get; set;) }
Step 3: Create a new file named MailData.cs with the following properties inside.
public class MailData
{
// Receiver
public List To { get; }
public List Bcc { get; }
public List Cc { get; }
// Sender
public string? From { get; }
public string? DisplayName { get; }
public string? ReplyTo ( get;) }
public string? ReplyToName { get; }
// Content
public string Subject { get; }
public string? Body { get; }
public MailData(List to, string subject, string? body = null, string? from = null, string? displayName = null, string? replyTo = null, string? replyToName = null, List? bcc = null, List? cc = null)
{
// Receiver
To = to;
Bcc=bcc?? new List();
Cc = cc ?? new List();
// Sender
From = from;
DisplayName = displayName;
ReplyToName = replyToName;
ReplyTo = replyTo;
// Content
Subject = subject;
Body = body;
}
Step 4: Create a new folder named Services at the root of your project along with two new files inside named ImailService.cs and MailService.cs.
public class MailService: IMailService
{
private readonly MailSettings _settings;
public MailService(IOptions settings)
{
_settings = settings.Value;
}
public async Task SendAsync(MailData mailData, CancellationToken ct = default)
{
try
{
// Initialize a new instance of the Minekit. MinaMessage class
var nail = new MineMessage();
#region Sender / Receiver
// sender
mail.From.Add(new MailboxAddress(_settings.DisplayName, mailData. From ?? _settings From));
mail.Sender = new MailboxAddress(mailData.DisplayName ?? _settings.DisplayName, mailData .From ?? _settings.From);
// Receiver
foreach (string mailAddress in mailData.To)
mail.To.Add(MailboxAddress, Parse(mailAddress));
// Set Reply to if specified in mail data
if!string.IsNullOrEmpty(mailData.ReplyTo)
mail. ReplyTo.Add(new MailboxAddress(mailData.ReplyToNane, mailData.ReplyTo));
// BCC
// Check if a BCC was supplied in the request
if (mailData.Bcc != null)
{
// get only addresses where value is not null or with whitespace. x value of address
foreach (string mailAddress in mailData.Bcc. Where(x=>!string.IsNullOrWhiteSpace(x))) mail.Bcc.Add(MailboxAddress.Parse(mailAddress.Trim()));
}
// Check if a CC address was supplied in the request
if (mailData.Cc != null)
{
foreach (string mailAddress in mailData.Cc.Where(x=> !string.IsNullOrWhiteSpace(x))) mail.Cc.Add(MailboxAddress.Parse(mailAddress.Trim()));
}
#endregion
#region Content
// Add Content to Mine Message
var body=new BodyBuilder();
mail.Subject mailData.Subject;
body.HtmlBody = mailData.Body;
mail. Body = body.ToMessageBody();
#endregion
#regian Send Mail
using var smtp = new SmtpClient();
if (_settings.UseSSL)
{
await smtp.ConnectAsync(_settings.Host, _settings.Port, SecureSocketOptions.SsLOnConnect, ct);
else if (_settings.UseStartTls)
{
await smtp.ConnectAsync(_settings.Host, _settings.Port, SecureSocketOptions.StartTls, ct);
}
await smtp.AuthenticateAsync(_settings. UserNane, _settings.Password, ct);
await smtp. SendAsync(mail, ct);
await smtp.DisconnectAsync(true, ct);
#endregion
return true;
}
catch (Exception)
{
return false;
}
}
}
Step 5: Configure MailSettings and MailService in the program.cs
builder.Services.Configure (builder.Configuration .GetSection(nameof (MailSettings)));
builder .Services .AddTransient();
Step 6: Add a new MailController to send emails
public class MailController: Controller
private readonly MailService _mail;
public MailController(IMailService mail)
{
_mail = mail;
}
[HttpPost("sendmail")]
public async Task SendMailAsync(MailData mailData)
{
bool result = await _mail.SendAsync(mailData, new CancellationToken());
if (result)
{
return StatusCode(StatusCodes.Status2000K, "Mail has successfully been sent.");
else
{
return StatusCode(StatusCodes.Status500Internal ServerError, "An error occurred. The Mail could not be sent.");
}
}
}
Autocomplete
Autocomplete is an ASP.NET core library that enables desktop as well as online and cloud applications to auto-complete features such as text fields or domains.
Benefits of Autocomplete
Autofill search
The autofill search feature in the ASP.NET Core, AutoComplete control lets the user quickly and easily look for objects by filling in the word they type in accordance with the text recommendation.
UI customization
Using templates, you may change how each recommendation looks when it’s shown.
Responsive UI
Adaptive user interface (UI) created specifically for mobile devices that respond to touch
Let’s See How to Use Autocomplete Library
The jQuery AutoComplete plugin has been applied to the TextBox and the URL of the plugin is set to the AutoComplete Action method.
$(function (){
$("#txtEmployee").autocomplete(
source: function (request, response) {
$.ajax(
url: ‘/Employee/GetEmployees/’,
data: "prefix": request.tern ),
type: "POST",
success: function (data){
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response)
{
alert(response.responseText);
}
});
select: function (e, i) {
$("#hfEmployee").val(i.item.val);
},
minLength: "1"
});
};
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@ViewBag.Message
}
Table of Contents
Tags Cloud
Frequently Asked Questions (FAQs)
- Newtonsoft.Json (Json.NET)
- Entity Framework Core
- Dapper
- NUnit
- Moq
- AutoMapper
- Serilog
- RestSharp
- FluentValidation
- Polly