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?.…

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.Clone()).ToList();  

the above extension will clone the list and return the cloned list using linq.

you can now use the extension in your code where you want to cloned generic list.

 List<MyClassDto> lst=new List<MyClassDto>();  
 lst.Add(new MyClassDto{id=1,Time="10.20",user=2})  
 lst.Add(new MyClassDto{id=2,Time="10.21",user=3})  
 var userInfoPush = lst.Clone<MyClassDto>(); 

That's it. Now your generic list will be cloned successfully


Popular posts from this blog

Restore the lost focus of Auto post back controls in asp.net update Panel control

Add Comma automatically while entering amounts in textbox using Javascript

Devexpress Datebox date formatting in angular 6 with example