Author Archives: Hitesh Kumar

Avatar

About Hitesh Kumar

A Software Developer with more than 5+ years of rich experience in Software Development in Microsoft Dot Net Technology.

Global exception handling in asp.net core

Global exception handling is a way to handle unhandled exceptions in asp.net core.

Add a middleware UseExceptionHandler to the pipeline that will catch exceptions, log them, reset the request path and re-execute the request. The request will not be re-executed if the response has already started.

Add UseExceptionHandler code in Startup.Configure method as stated below. This will redirect to Error action.

if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseExceptionHandler("/Error");
     }

Now exception can be captured using IExceptionHandlerFeature in the Error Action.

 Public IActionResult Error()
 {    
     var errorFeature = HttContext.Features.Get<IExceptionHandlerFeature>();
     var error = errorFeature.Error;
     var errorMessage= error.Message;
     var errorStackTrace = error.StackTrace;
     return View();
 }

TempData is null in asp.net core

The TempData provider cookie isn’t essential. CheckConsentNeeded is used to get user permission to enable cookies. If user has denied cookies then TempData cookies will not be provided to browser.

In Asp.Net Core 2.1 to enable TempData cookies disable the CheckConsentNeeded option in Startup.ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure.CookiePolicyOptions(options =>
        {
            // This lambda determines whether user consent for non-essential cookies 
            // is needed for a given request.
            // options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
}

Asp.Net Core 2.2 has provided a new feature to configure the non-essential cookies even user has denied the cookie tracking permission. Add IsEssential property in Startup.ConfigureServices method as below.

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure.CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies 
            // is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.Cookie.IsEssential = true;
            options.MinimumSameSitePolicy = SameSiteMode.None;

        });
}

How to disable camel case in asp.net core?

In dotnet core default case for serializing output to json is camelCase. We can change the default case to Pascal by setting the new DefaultContractResolver

Steps

  1. Go to Startup.cs class file.
  2. Find Startup.ConfigureServices method and add the below line of code.
public void ConfigureServices(IServiceCollection services)
{
    // Add Services
    services.AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}

Delete, Backspace, Tab and Arrow keys are not working in Firefox when applying validation.

To get this work in Firefox.

<input id="Destination" value="" placeholder="Destination">


$('#Destination').on('keypress', function (e) {

    var regex = new RegExp("^[a-zA-Z0-9_ \b]+$");
    var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);   
    
    var keystobepassedout="ArrowLeftArrowRightDeleteBackspaceTab";
    if(keystobepassedout.indexOf(e.key)!=-1)
    {
      return true;
    }
    
    if (!regex.test(key)) {
        e.preventDefault();
        return false;
    }

});

Try it

How to encode URI components in javascript?

JavaScript provides an encodeURIComponent() function to encode uri components. This function encrypt the special characters provided in the url such as “space , / ? : @ & = + $ #“.
Syntax
encodeURIComponent(uri)
Example

var uri="codesolution.org/calculate-time-between-two-dates/";
var encodeduri=encodeURIComponent(uri);
$("#uri").html(uri);
$("#encodeduri").html(encodeduri);


Html

<h2>
How to encode URI components in javascript?
</h2>
<b>URI:</b> <div id=uri></div>
<b>Encoded URI:</b> <div id="encodeduri"></div>


Result
How to encode URI components in javascript?
URI:
codesolution.org/calculate-time-between-two-dates/
Encoded URI:
codesolution.org%2Fcalculate-time-between-two-dates%2F
Try it

Calculate time between two dates

Using moment.js, We can calculate time between two dates in jquery.
JavaScript

//Dates in string format
var strStartDate = "07/29/2017"; //MM/DD/YYYY
var strEndDate = "08/30/2017"; //MM/DD/YYYY

//Times in string format
var strStartTime="12:25";  //HH:MM
var strEndTime="22:30";  //HH:MM

//Convert string dates to Date format and adding time to dates
var StartDateTime = (moment(strStartDate,"MM/DD/YYYY").add(strStartTime.split(':')[0],'hours')).add(strStartTime.split(':')[1],'minutes');

var EndDateTime =(moment(strEndDate,"MM/DD/YYYY").add(strEndTime.split(':')[0],'hours')).add(strEndTime.split(':')[1],'minutes');

//Calculate duration
var duration = moment.duration(EndDateTime.diff(StartDateTime));

//Convert duration in hours
var hours = duration.asHours();
//Convert duration in minutes
var minutes = duration.asMinutes();

//Display on screen
$("#StartDate").html(StartDateTime.format("MMM DD, YYYY, HH:mm:ss"));
$("#EndDate").html(EndDateTime.format("MMM DD, YYYY, HH:mm:ss"));
$("#Hours").html(hours);
$("#Minutes").html(minutes);


Html

<h2>Calculate time between two dates</h2>
Start Date Time : <div id="StartDate"></div>
End Date Time : <div id="EndDate"></div>
Hours : <div id="Hours"></div>
Minutes : <div id="Minutes"></div>


Result
Calculate time between two dates
Start Date Time :
Jul 29, 2017, 12:25:00
End Date Time :
Aug 30, 2017, 22:30:00
Hours :
778.0833333333334
Minutes :
46685
Try it

Calculate days between two dates in jquery.

Using moment.js, We can calculate days between two dates in jquery.
JavaScript

//Dates in string format
var strStartDate = "07/29/2017"; //MM/DD/YYYY
var strEndDate = "08/30/2017"; //MM/DD/YYYY

//Convert string dates to Date format
var StartDate = moment(strStartDate,"MM/DD/YYYY");
var EndDate = moment(strEndDate,"MM/DD/YYYY");

//Calculate duration
var duration = moment.duration(EndDate.diff(StartDate));

//Convert duration in days
var days = duration.asDays();

//Display on screen
$("#StartDate").html(StartDate.format("MMM DD, YYYY"));
$("#EndDate").html(EndDate.format("MMM DD, YYYY"));
$("#Days").html(days);


Html

<h2>Calculate days between two dates</h2>
Start Date : <div id="StartDate"></div>
End Date : <div id="EndDate"></div>
Days : <div id="Days"></div>


Result
Calculate days between two dates
Start Date :
Jul 29, 2017
End Date :
Aug 30, 2017
Days :
32

Try it

Fizz Buzz game C#

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

//FizzBuzz Game
for (int i = 1; i <= 100; i++)
{
    if (i % 3 == 0 && i % 5 == 0)
    {
        Console.WriteLine("FizzBuzz");
    }
    else if (i % 3 == 0)
    {
        Console.WriteLine("Fizz");
    }
    else if (i % 5 == 0)
    {
        Console.WriteLine("Buzz");
    }
    else
    {
        Console.WriteLine(i);
    }
}
Console.ReadKey();

Update List from another list C#.

To update a list from another list, Here is the Syntax.
Syntax

foreach (var item in List2)
{
   List1.Where(m=>m.UniqueField == item.UniqueField).FirstOrDefault().Property = item.Property;
}


Example
1. Create Student model

class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public double Marks { get; set; }

    public Student(int ID, string Name, int Age)
    {
        this.ID = ID;
        this.Name = Name;
        this.Age = Age;

    }
    public Student(int ID, double Marks)
    {
        this.ID = ID;
        this.Marks = Marks;
    }
}


2. Create Student List as listStudents

List<Student> listStudents = new List<Student>() 
{ 
    new Student(1, "Sam", 12),
    new Student(2, "Patrick", 15),
    new Student(3, "Adam", 10),
    new Student(4, "Raj", 9),
    new Student(5, "Seema", 14)
};


3. Create Student Marks as listMarks

List<Student> listMarks = new List<Student>() 
{ 
    new Student(1,89.5),
    new Student(2,97.5),
    new Student(3,96.0),
    new Student(4,78.0),
    new Student(5,84.7)            
};


4. Now Update listStudents from listMarks

Console.WriteLine("ID Name Marks");
foreach (var StudentMarks in listMarks)
{
    var selectedStudent = listStudents.Where(S => S.ID == StudentMarks.ID).FirstOrDefault();
    selectedStudent.Marks = StudentMarks.Marks;
    Console.WriteLine("{0} {1} {2} ", selectedStudent.ID, selectedStudent.Name, selectedStudent.Marks);
}
Console.ReadKey();

Convert a list of string to comma separated string C#.

Convert a list of string to Comma Separated String. String.join method is used to concatenate a list of string, Using a specified separator between each string.
Syntax : String.Join(string Separator, String[] Values);
Example :

static void Main(string[] args)
{           
    List<string> listStrings = new List<string>() { "C#", "Asp.Net", "SQL Server", "PHP", "Angular" };
    string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
    Console.Write(CommaSeparateString);
    Console.ReadKey();
}

private static string GenerateCommaSeparateStringFromList(List<string> listStrings)
{
    return String.Join(",", listStrings);            
}


Comma Separate String

Comma Separate String