Posts

Showing posts with the label C#

Step by step migration of ASP.NET Core 2.2 to 3.1

In order to upgrade/migrate asp.net core version to 3.1 following steps to be perform.
Download and install Visual Studio 2019 version 16.4 or higher.Download and install .NET Core 3.1  https://dotnet.microsoft.com/download/dotnet-core/3.1Upgrade the projects of solution to .NET Core 3.1 , because ASP.NET Core 3.1 requires it.Update existing Nuget packages to a version compatible with ASP.NET Core 3.1 in each projectUse IHost interface from a IHostBuilder instead of building and running a IWebHost from a IWebHostBuilder in Program.cs public static IHostBuilder CreateWebHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseKestrel() .UseSerilog() .UseStartup<Startup>(); }) Change AddMvc method has been replaced by AddControllers in Startup.cs of each projects.In Startup.cs,UseMvc method to be replaced by…

Log exception to file in c# .net core application explained

In production environment when any bug gets reported at that time as developer wants to get the exception details of bug to resolve the issue on high priority.
In some case there might be situation where exception is not logged in table but developer wants to check the bug immediately. for that purpose we need to write the
exception details including stack trace of bug in file. To implement this easily i am going to demonstrate the implementation of custom logging in file as below.

First we need to construct the exception and logger method in custom logger class as shown below.


public class CustomLogger { public static List<string> ConstructExceptionDetails(Exception ex,string FunctionName) { return new List<string>() { $"{DateTime.Now} - {FunctionName}", $"Exception: {ex.Message}", $"StackTrace: {ex.StackTrace}", $"InnerException: {ex.InnerException?.…

All about the IEnumerable VS IQueryable in c#

In Linq or entity framework, we use IEnumerable and IQueryable for data manipulation or query data. IEnumerable is inherited by IQueryable, Hence IQueryable has all the features of IEnumerable and except this, it has its own features and benefits.

Both have its own importance to query data and data manipulation in different situations in the application. we can go through with both the features and take the advantage of both the features to boost the LINQ Query performance. As per the need of application at some stage IEnumerable is useful and some stage in the application IQueryable is useful. Lets discuss about its use and features now.


IEnumerable Features:


IEnumerable exists in System.Collections Namespace.IEnumerable can move forward only over a collection, it can’t move backward and between the items.IEnumerable is best to query data from in-memory collections like List, Array etc.While query data from database, IEnumerable execute select query on server side, load data in-memory o…

clone a generic list in C# using extension method

In practical situation you need to clone of object so that change in cloned object will not affect the original one.
If you need a cloned list with the same capacity you need to do some extra stuff with your user type.

I came up with this easy solution using ICloneable interface in your custom type class.

The first step you need to implement the ICloneable interface in your class like below.


public class MyClassDto : ICloneable { public Int64 Id { get; set; } public string Time { get; set; } public int user{ get; set; } public object Clone() { return new MyClassDto{ Date = this.Date, Id = this.Id, user = this.user}; } }
after that you need to add extension method in common class so that you can use it everywhere you want.

public static class Extensions { public static List<T> Clone<T>(this List<T> listToClone) where T : ICloneable { return listToClone.Select(item => (T)item…

How to ping Azure VM using C# code explained

I was looking for the code which can ping the Azure VM and give me the details whether VM is UP or down since the ICMP protocol is not permitted through the Azure load balancer,
you will notice that you are unable to ping an Azure VM from the internet, and from within the Azure VM, you are unable to ping internet locations.

To get rid of the issue i digged the internet to get the solution so finally i got the below solution which I have contructed through the function,
below function will ping the azure vm machine and returns true if online or false if offline

public static bool PingServerWithSocket(string iporHostname,int portNo)
        {
            bool result = false;

                try
                {
                    var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sock.Blocking = true;

                    IPAddress ipaddes = Dns.GetHostEntry(iporHostname).AddressList[0];
                    sock.Connect(ipaddes, portNo);
   …

Asp.Net MVC best practices part 1

If you decided to develop the application using Asp.Net MVC application and. I am going to demonstrate you to follow the best practices in MVC to develop the robust web application. If you want to log the exceptions occurs in controllers you need to write try catch blocks in each action method. This approach is also not recommended because you need to write try catch block in each action method. To get ride of this you can handle exceptions and log each exception by using centralized approach. These approaches are as follows

Do not inherit the Controller base class directly to your ControllersCreate new base custom controller class which inherits the base controller classInherit created base custom controller class to your controllersFollowing is the sample code which demonstrate the above best practices


public class BaseController : Controller { }
In above code I have inherited the controller class to custom base controller class and below is the code to use this created custom…

Internet explorer Loads pages from cache issue resolution in asp.net

Internet explorer have tendency to load pages from cache for same requested URL. Which makes thing worse where the content of the web page updated frequently. In this situation Internet Explorer not send request to the server for page rendering. To resolve the issue in asp.net there are two option available. Write the HTML code in head tag or write server side code to tell Internet explorer to not to load pages from cache.

If you are trying to add code in design or HTML page then add following code

<HTML><HEAD> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Expires" CONTENT="-1"> </HEAD><BODY> </BODY> </HTML> 
In Asp.NET, you can do it on a page-by-page granularity by using this set of methods prior to calling the web page by following way.


HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1)); HttpContext.Response.Cache.SetValidUntilExpires(false); HttpContext.Response.C…

How to Import CSV File and bind csv file data to gridview in asp.net using c#

I am going to demonstrate in this article about importing CSV file data into datatable and then bind that data to Asp.net gridview control. i have tried to make code simpler and less line of code.

I am assuming that you have saved the csv file to server by using fileupload control.


After that create function which returns string[]

private IEnumerable<string[]> GetAllDataFromCSVFile(string FileName) { string str; using (StreamReader rd=new StreamReader(FileName)) { while ((str = rd.ReadLine()) != null) { yield return str.Split(','); } } }

Create another function which returns final data-table with CSV File data

private DataTable GetCSVData(string FileName) { var values = GetAllDataFromCSVFile(FileName); DataTable dt = new DataTable(); int j=0; foreach (var item in values.FirstO…

Send bulk Email in asp.net using excel file

When you want to send the mail to multiple person email id and your data exists in the excel file like email address and his name. you can accomplish this task using asp.net and c#. In C# under System.Net.Mail and System.Net namespace you can use classes which can help us to send mail effortlessly.

I am giving some sample code to understand the concept

Following is aspx design Page Sample


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LogDatails.aspx.cs" Inherits="LogDatails" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml" ><headrunat="server"><title>Untitled Page</title></head><body><formid="form1" runat="server"><div><a href="Default.aspx">Back</a><asp:GridViewID="GridView1&q…