Showing posts with the label C#

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

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.InnerEx

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,

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];

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 Controllers Create new base custom controller class which inherits the base controller class Inherit created base custom controller class to your controllers Following 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 us

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

I am going to demonstrate in this article about importing CSV file data into datatable and then bind that data to 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 file-upload 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

Send bulk Email in 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 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 " " " > < html xmlns =" " > < head runat =" server " > < title > Untitled Page < / title > < / head > < body > < form id =" form1 " runat =" server " >