Error log in catch block write Exception Detail in C#


This method helps you to trace or keeping log of your exception in a text file with a formatted manner. Just use as extension method and pass object of you Catch Exception obj.


public class ErrorLog
 public static void WriteError(Exception ex)
  string err = "";

   string path = System.AppDomain.CurrentDomain.BaseDirectory + "/ErrorLog/" + 
   DateTime.Today.ToString("dd-MM-yy") + ".txt";

   if (!File.Exists(path))
  using (StreamWriter w = File.AppendText(path))
    w.WriteLine("\r\nLog Entry : ");
    w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
    err = "Error Log at : " + ex.ToString() + "___. Error Message:" + ex.StackTrace;
    catch (Exception ex1)

And you can use this extension method anywhere in catch block with class name.

  //your Code
catch(Exception ex)


Highlight the tab according to action and controller in MVC


In Menu bar, while navigating, “Active” class will add in menu item according to your controller and action, that is fixed by you in your html code.

Just use this extension method in your menu item class.


public static string IsActive(this HtmlHelper html,
                                      string control,
                                      string action)
            var routeData = html.ViewContext.RouteData;

            var routeAction = (string)routeData.Values["action"];
            var routeControl = (string)routeData.Values["controller"];

            // both must match
            var returnActive = control == routeControl &&
                               action == routeAction;

            return returnActive ? "active" : ""; //Here you can change class name according to your theme like "active" or anything

Now you have to use this method as HTML helper in your razor page.

<li class="@Html.IsActive("About","Index")">
 <a href="@Url.Action("Index","About")">About Us</a>

<li class="@Html.IsActive("Contact","Index")">
 <a href="@Url.Action("Index","Contact")">Contact Us</a>

Now if your controller and action will “About” and “Index” then “active” named class will add in you li class.

Sending Mail To Admin On USB Insertion or Removal In C#

By | C#

Here is the c# console code to create a event watcher to monitor, if any usb attached or detached from PC.

Simple just create a console application in visual studio and install a package from nuget to import namespace System.Management.

Install-Package System.Management -Version 4.5.0

And Code is Bellow :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace USB
    class Program
        public enum EventType
            Inserted = 2,
            Removed = 3

        static void Main(string[] args)
            ManagementEventWatcher watcher = new ManagementEventWatcher();
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");

            watcher.EventArrived += (s, e) =>
                string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
                EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));

                string eventName = Enum.GetName(typeof(EventType), eventType);

                Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName);
                Console.WriteLine("Mail admin"); //You can write your email code here

            watcher.Query = query;


you can write your email sending code after Console.WriteLine(“{0}: {1} {2}”, DateTime.Now, driveName, eventName);

How to Create a byte array from stream in C#?

By | C#
Moslty we want to save images or any file in database as byte, so we can convert any stream in byte array in c#, here below a method to convert.

 public static byte[] StreamToBytes(Stream input)
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                    ms.Write(buffer, 0, read);
                return ms.ToArray();

Convert List or any type of object to XML string data in C#

By | C#, MVC
Here is a method to conver any type of object to string xml, this method will take parameters of T type and will return XML string.

public static string ConvertToXML<T>(T obj)

                using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(stringWriter, obj);
                    XDocument xDoc = XDocument.Parse(stringWriter.ToString());
                    xDoc.Declaration = null;
                    return xDoc.ToString();

            catch (Exception ex)
                return ex;

Best way to convert array of object into array of string in C#

By | C# | No Comments

I have an array of object in c#

object arrayofobject = new object[] {"Name", "Password", "Address"}

now i want to convert this array of object into array of string so i’ll use Array.CovertAll() method as string array.

string[] arr = Array.ConvertAll((object[])arrayofobject, Convert.ToString);

Full Code Here

object arrayofobject = new object[] {"Name", "Password", "Address"}
string[] arrayofstring = Array.ConvertAll((object[])arrayofobject, Convert.ToString);

now you can get arrayofstring.

Get Enum Description According to language culture or resource file in C#

By | ASP.NET, C#, MVC | No Comments

if i have an enum and i want to show the description on view or in dropdown than, than we can change the description according to resource language file.

Full example below:

We have an Enum First

public enum MeetingType
            [Description("Booked Meeting")]
            APPOINTMENTBOOKED = 1,
            [Description("Prescription Bookings")]
            [Description("Prescription Renewal")]

And then we will add these description strings in our resource files.

After Adding strings or key in resource file we have created a extension method for further use.

First import

using System.Resources;

public static string GetDisplayName(this Enum e)
            var rm = new ResourceManager(typeof(DoctorPanel.Resources.Resource));
            var resourceDisplayName = rm.GetString(ExtensionMethod.EnumDescription(e).Replace(" ",string.Empty));

            return string.IsNullOrWhiteSpace(resourceDisplayName) ? string.Format("[[{0}]]", e) : resourceDisplayName;

And use this method where you want to get enum description according to resource or language wise.

var GetString=YourEnum.GetDisplayName();

we used white space remover because, Resource file keys accept without spaces or you can write your enum description without spaces.


Get disease ICD code in C# using ICD10 API

By | ASP.NET, C#, MVC | No Comments
public string GetICDCode(string ICDCode)
            DiagnosisModel model = new DiagnosisModel();
            String postURL = string.Format("{0}&desc=short&r=json", ICDCode);
            WebRequest request = WebRequest.Create(postURL);
            request.Method = "GET";
            request.ContentType = "application/json; charset=utf-8";

            var response = (HttpWebResponse)request.GetResponse();
            string jsonText;
            using (var sr = new StreamReader(response.GetResponseStream()))
                jsonText = sr.ReadToEnd();
            return jsonText;


We created a method for getting icd code.

Create Model for icd code vlaues and data

public class ICDCode
            public string Name { get; set; }
            public string[] Inclusions { get; set; }
            public string[] ExcludesOne { get; set; }
            public string[] ExcludesTwo { get; set; }
            public string Description { get; set; }
            public string Valid { get; set; }
            public string Type { get; set; }
            public string Response { get; set; }

Just pass icd code in above method and it will give you result as json,

deserilize it with you model class and store in your model properties.

ICDCode model = new ICDCode();

var jsonResultICDCode = GetICDCode(yourICDcode);

model.ICDResponse = new JavaScriptSerializer().Deserialize<ICDCode>(jsonResultICDCode);

If your ICD code is valid than, it will return
model.ICDResponse.Valid=1 and model.ICDResponse.Response == “True”

Now you can get all information about icd code in your model properties.