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 :: Using The IComparable And IComparer Interface In C#

clock May 19, 2020 07:54 by author Peter

One of the most used functionalities in our C# classes is the ability to sort the different instances of a class. This is mostly done when we create a generic List of our class type and next, we want to sort our class based on some condition. Today, we will see how this is done in our C# classes

Creating the Class

We will create a .NET core console application using Visual Studio 2019 Community edition as below,

Next, we create a Student Class inside the “Program.cs” file as below,
  public class Student : IComparable<Student> 
  { 
   
      public int ID { get; set; } 
      public string Name { get; set; } 
      public string Program { get; set; } 
      public int Year { get; set; } 
      public float GPA { get; set; } 
   
      public int CompareTo(Student otherItem) 
      { 
          var status = (this.GPA > otherItem.GPA) ? 1 : ((this.GPA == otherItem.GPA) ? 0 : -1);  
          return status; 
      } 
  } 


Let us look at the code in detail. To make the class sortable we need to implement the IComparable<T> interface. In this interface we need to code the “CompareTo” function. In this function another instance of the same class is passed in and then we compare the two to order them. We base this on the GPA field and hence when we sort a List<Student> list, we will get the class items sorted by GPA in ascending order. Note that if the return value is zero, this means that the classes are equal in sort order, if the return value is 1 (positive number), then the current class is higher in the sort and if the value is -1 (negative number) then the input class is higher in the sort order.

To test this out, we write the following code in the Main function as below,
  class Program 
      { 
          static void Main(string[] args) 
          { 
   
              var students = new List<Student>(); 
   
              var studentA = new Student() { ID = 1, Name = "John Doe", Program = "BCS", Year = 2020, GPA = 2.75F }; 
              var studentB = new Student() { ID = 1, Name = "Jane Doe", Program = "BCS", Year = 2020, GPA = 3.4F }; 
              var studentC = new Student() { ID = 1, Name = "Mary Jane", Program = "BCS", Year = 2020, GPA = 2.71F }; 
   
              students.Add(studentA); 
              students.Add(studentB); 
              students.Add(studentC); 
   
              Console.WriteLine($"Items not in any order"); 
              foreach(var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.WriteLine(); 
   
              students.Sort(); 
   
              Console.WriteLine($"Items in ascending order"); 
              foreach (var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.WriteLine(); 
   
              students.Sort(new DescendingComparer()); 
   
              Console.WriteLine($"Items in descending order"); 
              foreach (var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.ReadKey(); 
          } 
      } 
   
      public class DescendingComparer : IComparer<Student> 
      { 
          public int Compare(Student a, Student b) 
          { 
              var status = (a.GPA > b.GPA) ? -1 : ((a.GPA == b.GPA) ? 0 : 1); 
              return status; 
          } 
      } 


In the first case, we print the list of student classes as entered in the list. Then, we sort the list which will list the students in ascending order based on the GPA field. Finally, if we want to reverse the order and sort the student classes in descending order by GPA field we create a new DescendingComparer class which implements the IComparer<Student> interface and sort the records in the reverse order of what we did before.



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 :: Object reference not set to an instance of object

clock April 7, 2020 09:01 by author Peter

Error "object reference not set to an instance of an object"
This is one of the most common errors when developing an application. In this article, I will be presenting five of the most common mistakes that result with this error and will explain how to avoid them.

Why does this error happen?
This error's description speaks for itself but when you do not have much experience in development, it is very difficult to understand. So, this error description says that an object that is being called to get or set its value has no reference. This means that you are trying to access an object that was not instantiated.

Why should I know this?
This is important in order to avoid runtime errors that could possibly expose your sensitive data and this could lead to a vulnerability breach. Vulnerability breaches are usually used by hackers for a cyber attack to steal your data or to take your server offline.

How to avoid exposing code and entities?
You must always wrap code that could possibly throw an exception inside try-catch blocks. There are others security approaches that you can use to protect your data that can be found here.

Common mistakes
Objects used in this sample.

Controller
public class HomeController : Controller 
   { 
       SampleObj sampleObj; 
       SampleChildObj sampleChild; 
       List<string> lstSample; 
       public IActionResult Index() 
       { 
           return View(); 
       } 
 
       public IActionResult About() 
       { 
           ViewData["Message"] = "Your application description page."; 
 
           return View(); 
       } 
 
       public IActionResult Contact() 
       { 
           ViewData["Message"] = "Your contact page."; 
 
           return View(); 
       } 
 
       public IActionResult Error() 
       { 
           return View(); 
       } 
       public IActionResult NewObject() 
       { 
           sampleChild.Item2 = "error"; 
           return View(); 
       } 
 
       public IActionResult ConditionStatement() 
       { 
           if (true == false) 
           { 
               sampleChild = new SampleChildObj(); 
               sampleChild.Item2 = ""; 
           } 
           else 
               sampleChild.Item2 = "error"; 
 
           return View(); 
       } 
       public IActionResult ObjectInsideObject() 
       { 
           sampleObj = new SampleObj(); 
           sampleObj.ChildObj.Item2 = "error"; 
           return View(); 
       } 
       public IActionResult AddInNullList() 
       { 
           lstSample.Add("error"); 
           return View(); 
       } 
   } 

Classes
public class SampleObj 

 
    public string Item1 { get; set; } 
    public SampleChildObj ChildObj { get; set; } 

public class SampleChildObj  

    public string Item2 { get; set; } 


New object not instantiated
Practical example:
Here, we have a sample situation of when we have this error.

public IActionResult NewObject() 

    sampleChild.Item2 = "error"; 
    return View(); 


This happens when you create a new object but do not instantiate it before getting/setting a value.
Condition statement(if, switch)

Practical example:
Here, we have a sample situation of when we have this error,

public IActionResult ConditionStatement() 

    if (true == false) 
    { 
        sampleChild = new SampleChildObj(); 
        sampleChild.Item2 = ""; 
    } 
    else 
        sampleChild.Item2 = "error"; 
 
    return View(); 


Why does this happen?
This is a very common mistake. It happens when you create an object that is going to be instantiated inside a conditional statement but forgets to instantiate it in one of the conditions and try to read/write on it.

Object Inside Object

Practical Example
Here, we have a sample situation of when we have this error:

public IActionResult ObjectInsideObject() 

    sampleObj = new SampleObj(); 
    sampleObj.ChildObj.Item2 = "error"; 
    return View(); 


Why this happens?
It happens when you have an object with many child objects. So, you instantiate the main object but forget to instantiate its child before trying to get/set its value.

Add item in a null list

Practical Example
Here we have a sample situation of when we have this error,
public IActionResult AddInNullList() 

    lstSample.Add("error"); 
    return View(); 
}


Why does this happen?
When you are trying to read/write data in a list that was not instantiated before.

Important
In order to avoid exposing your data, you must always handle exceptions. Read more about how to do that here.
The items listed above are some of the most common ways to throw this type of error but there are many other situations in which we may face it. Always remember to check if your objects are instantiated before reading or writing data into them.

Best practices
Tips about commenting your code, making it more readable in order to help others developers to understand it.
Object naming practices, creating a pattern to name variables, services, methods.
Handling errors to not show sensitive data to your users.
Security tricks to protect your data.
Reading/writing data without breaking your architecture.

*I am planning to write more about common mistakes and to share tips to improve code quality. If you have any specific topic that you would like to read here, please write it below in the comments section.



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.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in