European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting - HostForLIFE.eu :: SQL Store Procedure Call Function In .NET Core Console Application

clock June 29, 2020 13:09 by author Peter

In this function, the SQL procedure table reads a procedure call method in the .NET Core application for the basic console write to get the input value to the search result. The SQL procedure calls to select the statement from the database.

SQL Procedure
    CREATE PROCEDURE  procselect  @username nchar(10)    
    AS    
         select * from wincurd where username=@username     
    go      


Basic string console values get functionality:
    string val;  
    Console.Write("Enter value: ");  
    val = Console.ReadLine();  
    string a = Convert.ToString(val);  
    Console.WriteLine("Your input: {0}", a);  


SQL Connection string functionality:
    SqlConnection dc = new SqlConnection("Data Source=.;Initial Catalog=databasename;Integrated Security=True");   

Command Execution Functionality
    using(SqlCommand cmd = new SqlCommand("procselect", dc)) {  
        cmd.CommandType = CommandType.StoredProcedure;  
        cmd.Parameters.AddWithValue("@username", a.ToString());  
        dc.Open();  
        SqlDataReader dr;  
        dr = cmd.ExecuteReader();  
        if (!dr.Read()) {  
            Console.Write("Record not found ");  
        } else {  
            string b = Convert.ToString(val);  
            b = dr[1].ToString();  
            Console.WriteLine("Your PASSWORD: {0}", b.ToString());  
            Console.ReadLine();  
        }  
        dc.Close();  
    }  





European ASP.NET Core Hosting - HostForLIFE.eu :: How To Serialize Nonstandard Enum Values?

clock June 22, 2020 12:50 by author Peter

.NET client libraries that integrate with third-party APIs occasionally need to compromise on how enum values are represented in model classes. For example, an API that requires values to be expressed in all uppercase letters force the creation of an enum similar to:
    public enum YesNoMaybeEnum 
     { 
         YES, 
         NO, 
         MAYBE  
     } 

While this will compile, it violates .NET naming conventions. In other cases, the third party may include names that include invalid characters like dashes or periods. For example, Amazon's Alexa messages include a list of potential request types that include a period in the names. These values cannot be expressed as enumation names. While this could be addressed by changing the data type of the serialized property from an enumeration to a string, the property values are no longer constrained and any suggestions from Intellisense are lost.
 
This article demonstrates how to eat your cake and have it, too. Using attributes and reflection, values can be serialized to and deserialized from JSON.
 
Serialization with EnumDescription
Let's say we need to serialize values that include periods. Creating an enum like the following generates compile time errors,
    public enum RequestTypeEnum 
    { 
        LaunchRequest, 
        IntentRequest, 
        SessionEndedRequest, 
        CanFulfillIntentRequest, 
        AlexaSkillEvent.SkillPermissionAccepted, 
        AlexaSkillEvent.SkillAccountLinked, 
        AlexaSkillEvent.SkillEnabled, 
        AlexaSkillEvent.SkillDisabled, 
        AlexaSkillEvent.SkillPermissionChanged, 
        Messaging.MessageReceived 
    } 

The EnumMember attribute defines the value to serialize when dealing with data contracts. Samples on Stack Overflow that show enumeration serialization tend to use the Description attribute. Either attribute can be used or you can create your own. The EnumMember attribute is more tightly bound to data contract serialization while the Description attribute is for use with design time and runtime environments, the serialization approach in this article opts for the EnumMember. After applying the EnumMember and Data Contract attributes, the enum now looks like,
    [DataContract(Name = "RequestType")]   
    public enum RequestTypeEnum   
    {   
        [EnumMember(Value = "LaunchRequest")]   
        LaunchRequest,   
        [EnumMember(Value = "IntentRequest")]   
        IntentRequest,   
        [EnumMember(Value = "SessionEndedRequest")]   
        SessionEndedRequest,   
        [EnumMember(Value = "CanFulfillIntentRequest")]   
        CanFulfillIntentRequest,   
        [EnumMember(Value = "AlexaSkillEvent.SkillPermissionAccepted")]   
        SkillPermissionAccepted,   
        [EnumMember(Value = "AlexaSkillEvent.SkillAccountLinked")]   
        SkillAccountLinked,   
        [EnumMember(Value = "AlexaSkillEvent.SkillEnabled")]   
        SkillEnabled,   
        [EnumMember(Value = "AlexaSkillEvent.SkillDisabled")]   
        SkillDisabled,   
        [EnumMember(Value = "AlexaSkillEvent.SkillPermissionChanged")]   
        SkillPermissionChanged,   
        [EnumMember(Value = "Messaging.MessageReceived")]   
        MessageReceived   
    }   


The EnumMember attribute is also applied to enum members without periods. Otherwise, the DataContractSerilizer would serializes the numeric representation of the enumeration value. Now we can define a DataContract with,
    [DataContract] 
    public class SamplePoco 
    { 
        [DataMember] 
        public RequestTypeEnum RequestType { get; set; } 
    } 

And serialize it to XML with,
    SamplePoco enumPoco = new SamplePoco(); 
     
    enumPoco.RequestType = RequestTypeEnum.SkillDisabled; 
     
    DataContractSerializer serializer = new DataContractSerializer(typeof(SamplePoco)); 
     
    var output = new StringBuilder(); 
    using (var xmlWriter = XmlWriter.Create(output)) 
    { 
     
        serializer.WriteObject(xmlWriter, enumPoco); 
        xmlWriter.Close(); 
    } 
     
    string xmlOut = output.ToString();  


This generates the following XML,
    <?xml version="1.0" encoding="utf-16"?><SamplePoco xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/EnumSerializationSample"><RequestType>AlexaSkillEvent.SkillDisabled</RequestType> 
    </SamplePoco> 


DataContract serialization is sorted out, but doesn't yet address JSON serialization.
 
JSON Serialization
If you need to work with any REST API endpoints, then you'll need to support JSON. The NewtonSoft JSON has its own serialization strategy, and so the EnumMember attribute needs to be leveraged to integrate with it using a custom JsonConverter, but before taking that step, the enumation value must be read from the attribute.
 
This method accepts an enum value and returns the string value in the EnumMember attribute.
    private string GetDescriptionFromEnumValue(Enum value) 
            { 
    
    #if NETSTANDARD2_0 
                EnumMemberAttribute attribute = value.GetType() 
                    .GetField(value.ToString()) 
                    .GetCustomAttributes(typeof(EnumMemberAttribute), false) 
                    .SingleOrDefault() as EnumMemberAttribute; 
     
                return attribute == null ? value.ToString() : attribute.Value; 
    #endif 
    
    #if NETSTANDARD1_6 || NETSTANDARD1_3 || NET45 || NET47 
     
                EnumMemberAttribute attribute = value.GetType() 
                    .GetRuntimeField(value.ToString()) 
                    .GetCustomAttributes(typeof(EnumMemberAttribute), false) 
                    .SingleOrDefault() as EnumMemberAttribute; 
     
                return attribute == null ? value.ToString() : attribute.Value; 
               
    #endif 
     
     
                throw new NotImplementedException("Unsupported version of .NET in use"); 
            } 


There's a subtle difference between the .NET Standard 2.0 implementation and the others. In .NET Standard 1.6 and prior versions, use the GetRuntimeField method to get a property from a type. In .NET Standard 2.0, use the GetField method to return the property of a type. The compile-time constants and checks in the GetDescriptionFromEnumValue abstract away that complexity. 
 
Coming the other way, a method needs to take a string and convert it to the associated enumeration.
    public T GetEnumValue(string enumMemberText)  
    { 
     
        T retVal = default(T); 
     
        if (Enum.TryParse<T>(enumMemberText, out retVal)) 
            return retVal; 
     
     
        var enumVals = Enum.GetValues(typeof(T)).Cast<T>(); 
     
        Dictionary<string, T> enumMemberNameMappings = new Dictionary<string, T>(); 
     
        foreach (T enumVal in enumVals) 
        { 
            string enumMember = enumVal.GetDescriptionFromEnumValue(); 
            enumMemberNameMappings.Add(enumMember, enumVal); 
        } 
     
        if (enumMemberNameMappings.ContainsKey(enumMemberText)) 
        { 
            retVal = enumMemberNameMappings[enumMemberText]; 
        } 
        else 
            throw new SerializationException($"Could not resolve value {enumMemberText} in enum {typeof(T).FullName}"); 
     
        return retVal; 
    } 


The values expressed in the EnumMember attributes are loaded into a dictionary. The value of the attribute serves as the key and the associated enum is the value. The dictionary keys are compared to the string value passed to the parameter and if a matching EnumMember value is found, then the related enum is returned and so "AlexaSkillEvent.Enabled" returns RequestTypeEnum.SkillEnabled.
 
Using this method in a JSON Converter, the WriteJson method looks like the following,
    public class JsonEnumConverter<T> : JsonConverter where T : struct, Enum, IComparable, IConvertible, IFormattable
    { 
     
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
        { 
            if (value != null) 
            { 
                Enum sourceEnum = value as Enum; 
     
                if (sourceEnum != null)   
                { 

                    string enumText = GetDescriptionFromEnumValue(sourceEnum); 
                    writer.WriteValue(enumText); 
                } 
            } 
        } 


Please note that an enum constraint is applied to the generic type class declaration. This wasn't possible until C# version 7.3. If you cannot upgrade to use C# version 7.3, just remove this constraint.
 
The corresponding ReadJson method is,
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     
        object val = reader.Value; 
     
        if (val != null) 
        { 
            var enumString = (string)reader.Value; 
     
            return GetEnumValue(enumString); 
        } 
     
        return null; 
    } 


Now the class definition needs to apply the JsonConverter class to the RequestType property,
    [DataContract] 
    public class SamplePoco 
    { 
        [DataMember] 
        [JsonConverter(typeof(JsonEnumConverter<RequestTypeEnum>))] 
        public RequestTypeEnum RequestType { get; set; } 
     
    }  


Finally, the SamplePoco class is serialized to JSON,
    SamplePoco enumPoco = new SamplePoco(); 
     
    enumPoco.RequestType = RequestTypeEnum.SkillEnabled; 
     
    string samplePocoText = JsonConvert.SerializeObject(enumPoco); 


This generates the following JSON,
    { 
      "RequestType":"AlexaSkillEvent.SkillEnabled" 
    } 


And deserialing the JSON yields the RequestTypeEnum.SkillEnabled value on the sample class.
    string jsonText = "{\"RequestType\":\"AlexaSkillEvent.SkillEnabled\"}"; 
     
    SamplePoco sample = JsonConvert.DeserializeObject<SamplePoco>(jsonText); 

Summary
The EnumMember attribute is used to drive serializing of non-standard enum values using both DataContract serialization and Newtonsoft JSON serialization. Attached sample code shows other examples and unit tests. The Whetstone.Alexa NuGet package makes use of this technique and is also available for reference on GitHub.



European ASP.NET Core Hosting - HostForLIFE.eu :: Graphs In ASP.NET MVC Using HighCharts

clock June 17, 2020 13:13 by author Peter

Firstly, we will learn how to fetch your data from a database (here we will use MsSql ) and then present it in the View using HighCharts. To understand the complete article, you must have basic knowledge/understanding about the below mentioned technologies/ methods,

  • Asp.Net MVC.
  • MSSQL Server.
  • JavaScript
  • JSON (JavaScript Object Notation).
  • ADO.Net
  • Entity Framework

We will be using HighCharts for representing our record as chart/graph (given at the end of the article).
 
What is HighCharts?
Highcharts is a charting library written in pure JavaScript, offering an easy way of adding interactive charts to your web site or web application. In the vast majority of charts we will be using a basic column chart here to represent our data.
 
You can visit here to check more variety and select which is best for your scenario.
 
Steps 1 - Creating a basic Asp.Net MVC Web Based Application.
Create an Application in ASP.NET MVC web application using Visual Studio.
 
Go to File Menu > New > Project.
 
Select ASP.NET Web Application ( .NET Framework ) and change the application name:
 
e.g. : HighCharts, and then click OK
 
Choose MVC>
 
Now, the MVC web application project is created with the default ASP.NET MVC template.
 
Step 2 - Create/Step up your DataBase and Table.
Here, we are using an existing MsSql Database of a “Grievance Portal” and a table (T_Complaint) which stores the data of the person from whom the Complaint has been received and we will show the same number of applications which are received by year,  by grouping them by years of application received and then sorting them by year.
 
The Structure of the table (T_Complaint) is as Below,

There will be many more columns like address, district, state, father’s name, complaint description, but as of now the above-mentioned columns are enough for our task.
 
Since the data that we will fetch could be huge here we are using “Stored Procedure” to retrieve it by just calling it from the controller as Stored Procedures take less time to fetch a huge amount of data as compared to SQL queries.
 
The below code will help you to create a Stored procedure.
    Create PROCEDURE [dbo].[SP_YearlyRec] 
    AS 
     
    select sum(Total)as 'Total',max(t1.concluded)as concluded,MAX(t1.Not_concluded)as Not_concluded,Complainletteryear from ( 
    select count(Complainletterdate) as 'Total',case when Conclusion=1 then count(year(Complainletterdate))end as concluded, 
    case when Conclusion=0 then count(year(Complainletterdate)) else 0 end as Not_concluded,YEAR(Complainletterdate) as [Complainletteryear] from T_Complaint 
    where Complainletterdate is not null 
    group by year(Complainletterdate),Conclusion 
    )t1 group by t1.Complainletteryear order by t1.Complainletteryear. 


Step 3 - Working on Controller
 
Here we will use the default HomeController that is created automatically when we create a new MVC application.
In the HomeController we will use default Index() ActionMethod and modify it as per our need or you can also create a new ActionMethod for yourself.
    public ActionResult Index() 
    { 
       return View(); 
    } 


Now create a view for your ActionMethod and give it the same name as your ActionMethod.
<view code is given below>
 
Next, we will create the WebMethod where we will call the Stored procedure which we have created previously.
    [WebMethod] 
    public JsonResult GetText() { 
        var db1 = new Grievance_Entities1(); 
        var list = db1.SP_YearlyRec(); 
        return Json(list.ToList(), JsonRequestBehavior.AllowGet); 
    } 


In the above code, Grievance_Entities1 is the entity we have created of our database which has a Stored Procedure “SP_YearlyRec” using Entity Framework.
 
Once it is created, open the index view and write the below code in the view.
 
We are dividing the View/HTML Code in 3 parts, Which are,
 
Head
The Head Will contain the links to HighCharts important Library as well as the styling of the complete graph inside a style tag . Every change in our design of our HighCharts need to be done here only in the Style tag itself.
 
Body
The body tag will contain the body of our HTML page which is HighCharts Graph in this Case.
    <div class="container"> 
        <h2 id="h2">Index</h2> 
        <figure class="highcharts-figure container" > 
            <div id="container-fluid" class="container-fluid"></div> 
            <p class="highcharts-description"> 
                A basic column chart . 
            </p> 
        </figure> 
    </div> 


Script
The Script tag will be the functioning body of our View as here we will use Ajax to fetch our data from the database by calling the WebMethod which is in our HomeController and will return Json Result as an output.
 
As this is the most important part of our module so I will be explaining the working of this module.
 
The javascript here has two parts first is the $(document).ready() ,and the other is a function which we have created that is LoadChart().
 
$(document).ready() is automatically triggered when the document is loaded. Whatever code we write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
 
So, here we will call the WebMethod in our controller using Ajax which is GetText using URL format “../{ControllerName}/{MethodName}”. And if the data is fetched correctly then we will call the LoadChart() function to Load the HighCharts with the fetched data.
 
Below is the code that will be placed in $(document ). ready() method.
    $(document).ready(function() { 
                var Complainletteryear = []; 
                var Total = []; 
                var concluded = []; 
                var N_concluded = []; 
                $.ajax({ 
                    type: "POST", 
                    url: "../Home/GetText", 
                    data: "{}", 
                    contentType: "application/json; charset=utf-8", 
                    dataType: "json", 
                    async: true, 
                    success: function(result) { 
                        $.each(result, function(key, item) { 
                            Complainletteryear.push(item.Complainletteryear); 
                            Total.push(item.Total); 
                            concluded.push(item.concluded); 
                            N_concluded.push(item.Not_concluded); 
                        }); 
                        loadChart(Complainletteryear, Total, concluded, N_concluded); 
                    }, 
                    error: function(errormessage) { 
                        $('#h2').html(errormessage.responseText); 
                        return false; 
                    } 
                }); 

In the above code, after the data is fetched we are selecting each Row using the foreach loop and putting every column in a specific array as the data accepted by HighCharts is either in the form of Array or Objects. In our case we need our data in the form of array. Refer to foreach loop in the above code.
 
Below we can see the Code where we will be working with HighCharts.
    function loadChart(category, val2, val3, val4) { 
        Highcharts.chart('container-fluid', { 
                chart: { 
                    type: 'column', 
                }, 
                title: { 
                    text: 'No. of Application Received yearly ' 
                }, 
                subtitle: { 
                    text: 'Source: LocalDb.com' 
                }, 
                xAxis: { 
                    categories: category, 
                    crosshair: true 
                }, 
                yAxis: { 
                    min: 0, 
                    title: { 
                        text: 'Number of Application' 
                    } 
                }, 
                tooltip: { 
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>', 
                    pointFormat: '<tr href="#"><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y} </b></td></tr>', 
                    footerFormat: '</table>' 
                }, 
                shared: true, 
                useHTML: true 
            }, series: [{ 
                name: 'Total', 
                data: val2, 
                color: '#ccb1fc', 
            }, { 
                name: 'Concluded', 
                data: val3, 
                color: '#b0ceff', 
            }, { 
                name: 'Not Concluded', 
                data: val4, 
                color: '#fcb1f0' 
            }] 
        }); 
    } 


In the above code, we have 4 input parameters which are category, val2,val3,val4.
Each variable is of array type which represents each column provided as an output from our stored procedure.
 
The variable category here defines X-Axis Categories which will be shown in the chart as a category for each column. The remaining three arrays consist of data which is to be represented as a vertical bar in each column.
 
The title here defines the  title of the Chart/Graph.
Chart Type tells what chart we will be using in the module.
 
Below is the figure which shows the output after implementing the above HighCharts code in Asp.Net MVC
 
Graphs In ASP.NET MVC Using HighCharts
 
Conclusion
To conclude , HighCharts are a user friendly graphical representation of data which can easily be represented using the above implementation in Asp.Net MVC application.




European ASP.NET Core Hosting - HostForLIFE.eu :: Action Result in ASP.NET Core API

clock May 5, 2020 10:12 by author Peter

This article overview action result which are used in ASP.NET Core and Core API. We will understand both, which are available in two different assemblies of ASP.NET Core Microsoft.AspNetCore.Mvc and System.Web.Http.

ObjectResult
ObjectResult primary role is content negotiation. It has some variation of a method called SelectFormatter on its ObjectResultExecutor. You can return an object with it, and it formats the response based on what the user requested in the Accept header. If the header didn’t exist, it returns the default format configured for the app. It’s important to note that if the request is issued through a browser, the Accept header will be ignored, unless we set the RespectBrowserAcceptHeader to true when we configure the MVC options in Startup.cs. Also, it doesn’t set the status code, which causes the status code to be null. ObjectResult is the super type of following:

AcceptedResult

AcceptedAtActionResult
AcceptedAtRouteResult
BadRequestObjectResult
CreatedResult
CreatedAtActionResult
CreatedAtRouteResult
NotFoundObjectResult
OkObjectResult

AcceptedResult

An AcceptedResultthat returns an Accepted (202) response with a Location header. It indicates that the request is successfully accepted for processing, but it might or might not acted upon. In this case, we should redirect the user to a location that provides some kind of monitor on the current state of the process. For this purpose, we pass a URI.
public AcceptedResult AcceptedActionResult() 
    { 
        return Accepted(new Uri("/Home/Index", UriKind.Relative), new { FirstName = "Peter",LastName="Scott" }); 
    } 


AcceptedAtActionResult
An AcceptedAtActionResult action result returns an accepted 202 response with a location header.
public AcceptedAtActionResult AcceptedAtActionActionResult() 

return AcceptedAtAction("IndexWithId", "Home", new { Id = 2, area = "" }, new { FirstName = "Peter",LastName="Scott" }); 


AcceptedAtRouteResult
An AcceptedAtRouteResult returns an Accepted (202) response with a Location header. It's the same as AcceptedResult, with the only difference being that it takes a route name and route value instead of URI.
public AcceptedAtRouteResult AcceptedAtRouteActionResult() 

return AcceptedAtRoute("default", new { Id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 


BadRequestResult
An ObjectResult, when executed. will produce a Bad Request (400) response. It indicates a bad request by user. It does not take any argument.
public BadRequestResult BadRequestActionResult() 

  return BadRequest(); 


BadRequestObjectResult
This is similar to BadRequestResult, with the difference that it can pass an object or a ModelStateDictionary containing the details regarding the error.
public BadRequestObjectResult BadRequestObjectActionResult() 

        var modelState = new ModelStateDictionary(); 
        modelState.AddModelError("Name", "Name is required."); 
        return BadRequest(modelState); 


CreatedResult

CreatedResult returns a Created (201) response with a Location header. This indicates the request has been fulfilled and has resulted in one or more new resources being created.
public CreatedResult CreatedActionResult() 
    { 
        return Created(new Uri("/Home/Index", UriKind.Relative), new { FirstName = "Peter", LastName = "Scott" }); 
    } 


CreatedAtActionResult
CreatedAtActionResult that returns a Created (201) response with a Location header.
public CreatedAtActionResult CreatedAtActionActionResult() 
    { 
        return CreatedAtAction("IndexWithId", "Home", new { id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 
    } 


CreatedAtRouteResult
CreatedAtRouteResult that returns a Created (201) response with a Location header.
public CreatedAtRouteResult CreatedAtRouteActionResult() 
    { 
        return CreatedAtRoute("default", new { Id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 
    } 


NotFoundResult
This represents a StatusCodeResult that when executed, will produce a Not Found (404) response.
public NotFoundResult NotFoundActionResult() 
    { 
        return NotFound(); 
    } 

NotFoundObjectResult
This is similar to NotFoundResult, with the difference being that you can pass an object with the 404 response.
public NotFoundObjectResult NotFoundObjectActionResult() 
    { 
        return NotFound(new { Id = 1, error = "There was no customer with an id of 1." }); 
    } 


OkResult
This is a StatusCodeResult. When executed, it will produce an empty Status200OK response.
public OkResult OkEmptyWithoutObject() 

return Ok(); 


OkObjectResult

An ObjectResult, when executed, performs content negotiation, formats the entity body, and will produce a Status200OK response if negotiation and formatting succeed.
public OkObjectResult OkObjectResult() 
    { 
        return new OkObjectResult(new { Message="Hello World !"}); 
    } 


NoContentResult

The action result returns 204 status code. It’s different from EmptyResult in that EmptyResult returns an empty 200 status code, but NoContentResult returns 204. Use EmptyResult in normal controllers and NoContentResult in API controllers.
public NoContentResult NoContentActionResult() 
    { 
        return NoContent(); 
    } 


StatusCodeResult

StatusCodeResult accepts a status code number and sets that status code for the current request. One thing to point is that you can return an ObjectResult with and status code and object. There is a method on ControllerBase called StatusCode (404, new {Name = "Peter Scott”}), which can take a status code and an object and return an ObjectResult.
public StatusCodeResult StatusCodeActionResult() 
    { 
        return StatusCode(404); 
    } 



European ASP.NET Core Hosting - HostForLIFE.eu :: Dependency Injection in ASP.NET Core

clock April 28, 2020 08:21 by author Peter

Dependency injection is a software design pattern that enables users to create an application with loosely coupled code. The term 'loosely coupled' means objects that should only have as many dependencies as required to complete their job by decreasing the tight coupling between the software components. Object's dependencies should be on interfaces as opposed to the concrete object. An object is concrete in the sense that it is created with the "new" keyword.

Advantages of Dependency Injection
Easier Maintainability
Greater re-usability

Code is more easily testable with different mock implementation.

Code is cleaner and more readable

There are basically 3 types of Dependency injection in ASP.NET Core:

  • Constructor Injection
  • Method Injection
  • Property Injection

Constructor Injection
Constructor injection is the most common dependency injection used in an application. Constructor injection uses parameters to inject the dependency. It accepts the dependency at the constructor level. It means when instantiating the class, their dependency pass through the constructor of the class.

Implementing Constructor Injection

In the below code, HomeController has a dependency on IEmployeeRepository. We are not creating an object of EmployeeRepository using the new Keyword but we are injecting IEmployeeRepository in Home Controller class using its constructor. This is called constructor injection.
using DependencyInjectionTech.Models; 
using Microsoft.AspNetCore.Mvc; 
namespace DependencyInjectionTech.Controllers { 
    [Route("api/[controller]")] 
    [ApiController] 
    public class HomeController: ControllerBase { 
        private IEmployeeRepository _employeeRepository; 
        // Constructor Injection 
        public HomeController(IEmployeeRepository employeeRepository) { 
                _employeeRepository = employeeRepository; 
            } 
            [HttpGet] 
            [Produces("application/json")] 
        public Employee GetEmployee() { 
            return _employeeRepository.GetEmployee(1); 
        } 
    } 


While running the application, we will get the below error because we have to manually register the interface IEmployeeRepository and its implementation class in the Asp.Net Core dependency injection container. Unless we won't do that process, we will get the below error:

An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'DependencyInjectionTech.Models.IEmployeeRepository' while attempting to activate 'DependencyInjectionTech.Controllers.HomeController'.

For registering the interface and its implementation, we have a startup class where we configure the service methods. We make use of the ConfigureServices method to configure the required service for our application. We can use this method to configure in both the ASP.NET Framework Service as well as our application-related custom service. We can make use of the incoming parameter type IServiceCollection of the Configure service method to configure the service.

There are basically 3 methods to register our custom service in the configure service method:
Add Singleton
Add Transient
Add Scoped

The below code in the startup file indicates if any controller (for example HomeController) requests IEmployeeRepository. Then it will automatically create an instance of MockEmployeeRepository class and then inject the instance.
// This method gets called by the runtime. Use this method to add services to the container. 
public void ConfigureServices(IServiceCollection services) { 
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 
    //Registering the interface and its implementation in asp.net core dependency injection container. 
    services.AddSingleton < IEmployeeRepository, MockEmployeeRepository > (); 


Method Injection
Method Injection enables you to inject the dependency into a single method to be only used by that method. We make use of the [FromService] attribute for the method Injection.

Implementing the Method Injection

In the below code, we are implementing the method injection in a single method.
namespace DependencyInjectionTech.Controllers { 
    [Route("api/[controller]")] 
    [ApiController] 
    public class HomeController: ControllerBase { 
        public HomeController() {} 
        //Method Injection 
        [HttpGet] 
        [Produces("application/json")] 
        public Employee GetEmployee([FromServices] IEmployeeRepository _employeeRepository) { 
            return _employeeRepository.GetEmployee(1); 
        } 
    } 
}



European ASP.NET Core Hosting - HostForLIFE.eu :: Flyweight Design Pattern

clock April 21, 2020 07:46 by author Peter

In this post, we will talk about Flyweight design pattern. We will see when one should use this design pattern and how we can implement it. In the below example, we will use C# language to implement the example.

In early days of computing, memory was very costly, but nowadays, it's getting cheaper on a daily basis. Usually, in software application, memory is needed to create and hold objects. Sometimes, some objects stay in memory for a longer period of time. It's the developer’s responsibility to remove the object from memory whenever it's not needed to save memory. Another way to save memory is to use a created object instead of creating a new object each time. This will definitely save memory and improve the performance of the application.
 
To achieve this, we should have a pool of objects where we will keep all newly created objects. Whenever we need the same object, we will query to pool and get that object. After query, if the needed object doesn’t exist in the pool, we will create new one and store it in the pool. In a higher language like C# or Java, we can use Dictionary<Key,Value> or HashTable<Key,Value> to create a pool.
 
Example

Let's add new project. You can give any name you want to it.
Lets create a contract called “IShape” which will be implemented by different shapes.
    internal interface IShape 
        { 
            void Print(); 
        } 


Lets add a “Rectangle” shape.
    internal class Rectangle : IShape 
        { 
            public void Print() 
            { 
                Console.WriteLine("Printing Rectangle"); 
            } 
        } 


Lets add a “Circle” shape.
    internal class Circle : IShape 
        { 
            public void Print() 
            { 
                Console.WriteLine("Printing Circle"); 
            } 
        } 


Lets add “Shapes” enum.
    public enum Shapes 
        { 
            Rectangle, 
            Circle 
        } 


Here's a factory class which will hold all objects in dictionary (hashtable). If the requested object doesn't exist in this list, then it will create it, or else it will return the already created one.
internal class ShapeObjectFactory 

    private readonly Dictionary<Shapes, IShape> shapes = new Dictionary<Shapes, IShape>(); 

    public int TotalObjectsCreated 
    { 
        get { return shapes.Count; } 
    } 

    public IShape GetShape(Shapes shapeType) 
    { 
        IShape shape = null; 
        if (shapes.ContainsKey(shapeType)) 
        { 
            shape = shapes[shapeType]; 
        } 
        else 
        { 
            switch (shapeType) 
            { 
                case Shapes.Rectangle: 
                    shape = new Rectangle(); 
                    shapes.Add(Shapes.Rectangle, shape); 
                    break; 

                case Shapes.Circle: 
                    shape = new Circle(); 
                    shapes.Add(Shapes.Circle, shape); 
                    break; 

                default: 
                    throw new Exception("Factory cannot create the object specified"); 
            } 
        } 
        return shape; 
    } 


Client program
internal class Program 

    private static void Main(string[] args) 
    { 
        var factoryObject = new ShapeObjectFactory(); 

        IShape shape = factoryObject.GetShape(Shapes.Rectangle); 
        shape.Print(); 
        shape = factoryObject.GetShape(Shapes.Rectangle); 
        shape.Print(); 
        shape = factoryObject.GetShape(Shapes.Rectangle); 
        shape.Print(); 

        shape = factoryObject.GetShape(Shapes.Circle); 
        shape.Print(); 
        shape = factoryObject.GetShape(Shapes.Circle); 
        shape.Print(); 
        shape = factoryObject.GetShape(Shapes.Circle); 
        shape.Print(); 

        int NumObjs = factoryObject.TotalObjectsCreated; 
        Console.WriteLine("\nTotal No of Objects created = {0}", NumObjs); 
        Console.ReadKey(); 
    } 



European ASP.NET Core Hosting - HostForLIFE.eu :: Using Sorted Sets Of Redis To Delay Execution In ASP.NET Core

clock April 14, 2020 07:33 by author Peter

In a previous article, I showed you how to delay execution via keyspace notifications of Redis in ASP.NET Core, and I will introduce another solution based on Redis.
Sorted Sets, a data structure of Redis, also can help us work it out.

We can make a timestamp as score, and the data as value. Sorted Sets provides a command that can return all the elements in the sorted set  with a score between two special scores. Setting 0 as the minimum score and current timestamp as the maximum score, we can get all the values whose timestamp are less than the current timestamp, and they should be executed at once and should be removed from Redis.
 
Taking a sample for more information.
 
Add some values at first.

ZADD task:delay 1583546835 "180" 
ZADD task:delay 1583546864 "181" 
ZADD task:delay 1583546924 "182"  

Suppose the current timestamp is 1583546860, so we can get all values via the following command.

ZRANGEBYSCORE task:delay 0 1583546860 WITHSCORES LIMIT 0 1

We will get the value 180 from the above sample, and then we can do what we want to do.

Now, let's take a look at how to do this in ASP.NET Core.

Create Project
Create a new ASP.NET Core Web API project and install CSRedisCore.
    <ItemGroup> 
        <PackageReference Include="CSRedisCore" Version="3.4.1" /> 
    </ItemGroup> 


Add an interface named ITaskServices and a class named TaskServices.
    public interface ITaskServices 
    { 
        Task DoTaskAsync(); 
     
        Task SubscribeToDo(); 
    } 
     
    public class TaskServices : ITaskServices 
    {        
        public async Task DoTaskAsync() 
        { 
            // do something here 
            // ... 
     
            // this operation should be done after some min or sec 
     
            var cacheKey = "task:delay"; 
            int sec = new Random().Next(1, 5); 
            var time = DateTimeOffset.Now.AddSeconds(sec).ToUnixTimeSeconds(); 
            var taskId = new Random().Next(1, 10000); 
            await RedisHelper.ZAddAsync(cacheKey, (time, taskId)); 
            Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} done {taskId} here - {sec}"); 
        } 
     
        public async Task SubscribeToDo() 
        { 
            var cacheKey = "task:delay"; 
            while (true) 
            { 
                var vals = RedisHelper.ZRangeByScore(cacheKey, -1, DateTimeOffset.Now.ToUnixTimeSeconds(), 1, 0); 
     
                if (vals != null && vals.Length > 0) 
                { 
                    var val = vals[0]; 
     
                    // add a lock here may be more better 
                    var rmCount = RedisHelper.ZRem(cacheKey, vals); 
     
                    if (rmCount > 0) 
                    { 
                        Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} begin to do task {val}"); 
                    } 
                } 
                else 
                { 
                    await Task.Delay(500); 
                } 
            } 
        } 
    } 


Here we will use DateTimeOffset.Now.AddSeconds(sec).ToUnixTimeSeconds() to generate the timestamp, the sec parameter means that we should execute the task after some seconds. For the delay execution, it will poll the values from Redis to consume the tasks, and make it sleep 500 milliseconds if cannot get some values.

When we get a value from Redis, before we execute the delay task, we should remove it from Redis at first.

Here is the entry of this operation.

    [ApiController] 
    [Route("api/tasks")] 
    public class TaskController : ControllerBase 
    { 
        private readonly ITaskServices _svc; 
     
        public TaskController(ITaskServices svc) 
        { 
            _svc = svc; 
        } 
     
        [HttpGet] 
        public async Task<string> Get() 
        { 
            await _svc.DoTaskAsync(); 
            return "done"; 
        } 
    } 


We will put the subscribe to a BackgroundService

    public class SubscribeTaskBgTask : BackgroundService 
    { 
        private readonly ILogger _logger; 
        private readonly ITaskServices _taskServices; 
     
        public SubscribeTaskBgTask(ILoggerFactory loggerFactory, ITaskServices taskServices) 
        { 
            this._logger = loggerFactory.CreateLogger<RefreshCachingBgTask>(); 
            this._taskServices = taskServices; 
        } 
     
        protected override async Task ExecuteAsync(CancellationToken stoppingToken) 
        { 
            stoppingToken.ThrowIfCancellationRequested(); 
            await _taskServices.SubscribeToDo(); 
        } 
    } 


At last, we should register the above services in startup class.
    public class Startup 
    { 
        // ... 
         
        public void ConfigureServices(IServiceCollection services) 
        { 
            var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379"); 
            RedisHelper.Initialization(csredis); 
     
            services.AddSingleton<ITaskServices, TaskServices>(); 
            services.AddHostedService<SubscribeTaskBgTask>(); 
     
            services.AddControllers(); 
        } 
    } 

Here is the result after running this application.



European ASP.NET Core Hosting - HostForLIFE.eu :: ASP.NET Core Custom Authentication

clock April 3, 2020 07:23 by author Scott

ASP.NET Core Identity is popular choice when web application needs authentication. It supports local accounts with username and password but also social ID-s like Facebook, Twitter, Microsoft Account etc. But what if ASP.NET Core Identity is too much for us and we need something smaller? What if requirements make it impossible to use it? Here’s my lightweight solution for custom authentication in ASP.NET Core.

We don’t have to use ASP.NET Core Identity always when we need authentication. I have specially interesting case I’m working on right now.

I’m building a site where users authenticate using Estonian ID-card and it’s mobile counterpart mobile-ID. In both cases users is identified by official person code. Users can also use authentication services by local banks. Protocol is different but users are again identified by official person code. There will be no username-password or social media authentication.

In my case I don’t need ASP.NET Core Identity as it’s too much and probably there are some security requirements that wipe classic username and password authentication off from table.

Configuring authentication

After some research it turned out that it’s actually very easy to go with cookie authentication and custom page where I implement support for those exotic authentication mechanisms.

First we have to tell ASP.NET Core that we need authentication. I’m going with cookie authentication as there’s no ping-pong between my site and external authentication services later. Let’s head to ConfigureServices() method of Startup class and enable authentication.

public void ConfigureServices(IServiceCollection services)
{
    // Enable cookie authentication
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();
 
    services.AddHttpContextAccessor();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

In Configure() method of Startup class we need to add authentication to request processing pipeline. The line after comment does the job.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ...
 
    // Add authentication to request pipeline
    app.UseAuthentication();
 
    app.UseStaticFiles();           
 
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

No we have done smallest part of work – ASP.NET Core is configured to use cookie authentication.

Implementing AccountController

Where is user redirected when authentication is needed? We didn’t say anything about it Startup class. If we don’t specify anything then ASP.NET Core expects AccountController with AccessDenied and Login actions. It’s bare minimum for my case. As users must be able to log out I added also Logout() action.

Here’s my account controller. Login() action is called with SSN parameter only by JavaScript that performs actual authentication. There’s always SSN when this method is called (of course, I will add more sanity checks later). Notice how I build up claims identity claim by claim.

public class AccountController : BaseController
{
    private readonly IUserService _userService;
 
    public AccountController(IUserService userService)
    {
        _userService = userService;
    }
 
    [HttpGet]
    public IActionResult Login()
    {
        return View();
    }
 
    [HttpPost]
    public async Task<IActionResult> Login(string ssn)
    {
        var user = await _userService.GetAllowedUser(ssn);
        if (user == null)
        {
            ModelState.AddModelError("", "User not found");
            return View();
        }
 
        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.Ssn));
        identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName));
        identity.AddClaim(new Claim(ClaimTypes.Surname, user.LastName));
 
        foreach (var role in user.Roles)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, role.Role));
        }
 
        var principal = new ClaimsPrincipal(identity);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
 
        return RedirectToAction("Index","Home");
    }
 
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync();
 
        return RedirectToAction(nameof(Login));
    }
 
    public IActionResult AccessDenied()
    {
        return View();
    }
}

And this is it. I have now cookie-based custom authentication in my web application.

To try things out I run my web application, log in and check what’s inside claims collection of current user. All claims I expected are there. 

Wrapping up

ASP.NET Core is great on providing the base for basic, simple and lightweight solutions that doesn’t grow monsters over night. For authentication we can go with ASP.NET Core Identity but if it’s too much or not legally possible then it’s so-so easy to build our own custom cookie-based authentication. All we did was writing few lines of code to Startup class. On controllers side we needed just a simple AccountController where we implemented few actions for logging in, logging out and displaying access denied message.



European ASP.NET Core Hosting - HostForLIFE.eu :: Read and Write a CSV File in ASP.NET Core

clock March 31, 2020 11:06 by author Peter
For this blog, my agenda is to provide a step-by-step solution to read and write CSV files in ASP.NET Core 3.0, and CSVHelper. The Same Logic will work for Web Application, Windows Application, and Console Application. In this post, I'm going to create a sample Console Application to show you the process.

Steps:
  1. Create a Console Application project
  2. Create a student class inside the project
  3. Install the CSVHelper from NuGet Package Manager
  4. Add Mappers folder and inside add a mapper Class for Student
  5. Add Services Folder in the project and Add StudentService Class inside it
  6. Write the Logic inside the main method of Program file as its starting point of the application
Create a Console Application project
Give the Name to The Project as "ReadWriteCSVFile". You can give any name.
 
Create a student class inside the project 
Write the below code inside the Student class:

namespace ReadWriteCSVFile {  
    public class Student {  
        public int RollNo {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string Course {  
            get;  
            set;  
        }  
        public decimal Fees {  
            get;  
            set;  
        }  
        public string Mobile {  
            get;  
            set;  
        }  
        public string City {  
            get;  
            set;  
        }  
    }  

In the next step, we are going to install the CSVHelper package so that it will help us to read and write the CSV file in an easy way.

Now Install the CSVHelper from NuGet Package Manager --Version (12.2.1),

  • Step 1 - Right Click on the Project
  • Step 2 - Go To "Manage NuGet Packages..."
  • Step 3 - Go To Browse Tab then move to the Search area
  • Step 4 - Type "CSVHelper" in the search box

Here you will see a list of packages. Choose the first one and move it to the right-side panel. You will see one option as Version: (If not installed, if you already installed, then you will see both Installed and Version, two options). Select Version 12.2.1 and click on the install button and follow the steps to install successfully.

Add "Mappers" folder and inside it add mapper Class for Student

  • Here you can give any name to the folder and class
  • Give the proper name to the class as "StudentMap"
  • Make this class as sealed

Write the below code inside the StudentMap Class:

namespace ReadWriteCSVFile.Mappers {  
    public sealed class StudentMap: ClassMap < Student > {  
        public StudentMap() {  
            Map(x => x.RollNo).Name("RollNo");  
            Map(x => x.Name).Name("Name");  
            Map(x => x.Course).Name("Course");  
            Map(x => x.Fees).Name("Fees");  
            Map(x => x.Mobile).Name("Mobile");  
            Map(x => x.City).Name("City");  
        }  
    }  

Add "Services" Folder in the project and Add StudentService Class inside it:

  • Here, you can give any name to the folder and class
  • Give the proper name to the class as "StudentService"

Write the below Code inside the StudentService Class

namespace ReadWriteCSVFile.Services {  
    public class StudentService {  
        public List < Student > ReadCSVFile(string location) {  
            try {  
                using(var reader = new StreamReader(location, Encoding.Default))  
                using(var csv = new CsvReader(reader)) {  
                    csv.Configuration.RegisterClassMap < StudentMap > ();  
                    var records = csv.GetRecords < Student > ().ToList();  
                    return records;  
                }  
            } catch (Exception e) {  
                throw new Exception(e.Message);  
            }  
        }  
        public void WriteCSVFile(string path, List < Student > student) {  
            using(StreamWriter sw = new StreamWriter(path, false, new UTF8Encoding(true)))  
            using(CsvWriter cw = new CsvWriter(sw)) {  
                cw.WriteHeader < Student > ();  
                cw.NextRecord();  
                foreach(Student stu in student) {  
                    cw.WriteRecord < Student > (stu);  
                    cw.NextRecord();  
                }  
            }  
        }  
    }  

Write the Logic inside the main method of Program file as its starting point of the application.
Change the code inside the Main method of Program class as shown below:

 

namespace ReadWriteCSVFile {  
    class Program {  
        static void Main(string[] args) {  
            Console.WriteLine("Start CSV File Reading...");  
            var _studentService = new StudentService();  
            var path = @ "D:\Tutorials\Student.csv";  
            //Here We are calling function to read CSV file  
            var resultData = _studentService.ReadCSVFile(path);  
            //Create an object of the Student class  
            Student student = new Student();  
            student.RollNo = 5;  
            student.Name = "Lucy";  
            student.Course = "B.Tech";  
            student.Fees = 75000;  
            student.Mobile = "7788990099";  
            student.City = "Pune";  
            resultData.Add(student);  
            //Here We are calling function to write file  
            _studentService.WriteCSVFile(@ "D:\Tutorials\NewStudentFile.csv", resultData);  
            //Here D: Drive and Tutorials is the Folder name, and CSV File name will be "NewStudentFile.csv"  
            Console.WriteLine("New File Created Successfully.");  
        }  
    }  

 



European ASP.NET Core Hosting - HostForLIFE.eu :: How to Use AutoMapper with ASP.NET Core 3

clock March 19, 2020 09:20 by author Scott

AutoMapper is well known in the .NET community. It bills itself as "a simple little library built to solve a deceptively complex problem - getting rid of code that maps one object to another," and it does the job nicely.

In the past, I've used it exclusively with ASP.NET APIs. However, the method for utilizing it via dependency injection has changed. So let's review how to get started, how to define mappings and how to inject our mappings into ASP.NET Core APIs.

Getting Started

Like most .NET libraries, we can install the AutoMapper package from Nuget.

Install-Package AutoMapper

For our purposes, we'll focus on two classes that are related; User and UserDTO.

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string FavoriteFood { get; set; }
    public DateTime BirthDate { get; set; }
}

public class UserDTO
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int BirthYear { get; set; }
}

These classes will serve as source and destination types that we can work with.

Default Mappings

Without specific configuration, AutoMapper will match properties based on their name. By default, it will ignore null reference exceptions when mapping source and destination types. Below is a snippet mapping the source and destination types using the default configuration.

var config = new MapperConfiguration(cfg => cfg.CreateMap<User, UserDTO>());

var user = new User()
{
    Id = Guid.NewGuid(),
    Name = "Wayne Curry",
    FavoriteFood = "Sushi",
    BirthDate = new DateTime(1986, 10, 12)
};

var mapper = config.CreateMapper();
UserDTO userDTO = mapper.Map<UserDTO>(user);

The above will create a UserDTO object with an Id and Name that matches the original user object, but no error is thrown as a result of not having the FavoriteFood property on the UserDTO type. Also, the BirthYear property of the UserDTO will be zero.

Custom Mappings

We can use projection to translate properties as they are mapped. For instance, the code snippet below shows how we can map the BirthDate property of the User type to the BirthYear property of the UserDTO type.

var config = new MapperConfiguration(cfg =>
    cfg.CreateMap<User, UserDTO>()
        .ForMember(dest => dest.BirthYear,
                   opt => opt.MapFrom(src => src.BirthDate.Year));

var user = new User()
{
    Id = Guid.NewGuid(),
    Name = "Wayne Curry",
    FavoriteFood = "Sushi",
    BirthDate = new DateTime(1986, 10, 12)
};

var mapper = config.CreateMapper();
UserDTO userDTO = mapper.Map<UserDTO>(user);

The resulting userDTO object will be similar to our first example, but this time it will
include the BirthYear property of 2000.

Profiles

A clean way to organize and maintain our mapping configurations is with profiles. Many times these Profile classes will encapsulate business areas (e.g. Ordering, Shipping). To start, we'll create a class that inherits from Profile and put the configuration in the constructor.

public class UserManagementProfile : Profile
{
    public UserManagementProfile()
    {
        CreateMap<User, UserDTO>()
            .ForMember(dest => dest.BirthYear,
            opt => opt.MapFrom(src => src.BirthDate.Year));

        // Configurations for other classes in this business
        // area can be included here as well, like below:

        // CreateMap<Role, RoleDTO>();
        // CreateMap<Permission, PermissionDTO>();
    }
}

For added isolation, we can create a project just for our Profile configurations. Using profiles helps us keep configurations more manageable as our application grows.

Dependency Injection

Dependency injection is baked into ASP.NET Core, but to use AutoMapper with it we'll need additional configuration and an additional Nuget package.

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

Register AutoMapper

Once installed, we can define the configuration using profiles. In the Startup.ConfigureServices method, we can use the AddAutoMapper extension method on the IServiceCollection object as shown below:

// By Marker
services.AddAutoMapper(typeof(ProfileTypeFromAssembly1) /*, ...*/);

// or by Assembly
services.AddAutoMapper(profileAssembly1, profileAssembly2 /*, ...*/);

Inject AutoMapper

With AutoMapper registered and its configurations set, we can now inject an IMapper into our controllers.

public class UsersController
{
    private readonly IMapper _mapper;

    public UsersController(IMapper mapper) => _mapper = mapper;

    // use _mapper.Map
}

With the IMapper we can map our objects to their DTO equivalents using the .Map method.

Wrap It Up

Now that ASP.NET Core is injecting AutoMapper to our controllers, we can add configurations to our profiles or create new profiles for new business areas and still map appropriately without further configuration.

Of course, we didn't cover all of the features of AutoMapper so I'd suggest checking out their documentation for more information about their capabilities. Hopefully this post gave you enough information to start trying AutoMapper yourself. Let me know in the comments how you use AutoMapper in your applications.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in