Tuesday, August 11, 2020

How to get Int value from enum in C#

Parsing the enumerator value to integer will give us the desired result. See below the sample code to get integer value from enumerator in C#.

class Program
{
    static void Main(string[] args)
    {
        int intVal = (int)LevelEnum.Three;
        Console.WriteLine(intVal);
    }
}
public enum LevelEnum
{
    One = 1,
    Two = 2,
    Three = 3,
    Four = 4
}
The result will be 3.

How to get the Count of items defined in an Enum in C#

We can use the static method Enum.GetNames which returns an array representing the names of all the items in the enum. The length property of this array gives the number of items defined in the enum.

class Program
{
    static void Main(string[] args)
    {
        var testEnumCount = Enum.GetNames(typeof(TestEnum)).Length;
        Console.WriteLine(testEnumCount);
    }
}
enum TestEnum
{
    A = 1,
    B = 2,
    C = 3,
    D = 4,
    E = 5
}
The result count will be 5

Monday, August 10, 2020

How to Convert JSON String to C# Object and Vice Versa | Serialize and Deserialize

Here is a sample code to convert C# object to JSON string and JSON string to C# object. This process is also called as Serializing and Deserializing. You need to install the Newtonsoft.Json library using Nuget manager to do this very easily.

Sample code will use the following class and properties as C# object.
    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Department { get; set; }
        public int Mark { get; set; }
    }

SERIALIZE :
using Newtonsoft.Json;
    var student = new Student()
    {
        Name = "Sachin",
        Age = 26,
        Department = "CSE",
        Mark = 790
    };
 var serializedString = JsonConvert.SerializeObject(student);
Serialized result will be,
"{\"Name\":\"Sachin\",\"Age\":26,\"Department\":\"CSE\",\"Mark\":790}"

DESERIALIZE :
using Newtonsoft.Json;
var jsonStr = "{\"Name\":\"Sachin\",\"Age\":26,\"Department\":\"CSE\",\"Mark\":790}";
var deserializedObject = JsonConvert.DeserializeObject<Student>(jsonStr);
Deserialized result will be,
    new Student()
    {
        Name = "Sachin",
        Age = 26,
        Department = "CSE",
        Mark = 790
    };

Wednesday, January 8, 2020

Install/Uninstall Windows service using Windows Command Prompt

Follow the below steps to Install or Uninstall Windows service using Windows Command Prompt
  • Run Command prompt as Administrator
  • Navigate to the .NET framework path using below command
  • CD C:\Windows\Microsoft.NET\Framework\v4.0.30319
  • Execute the below command to install,
  • installutil "C:\your_service_name_with_path.exe"
  • To uninstall use the below command
  • installutil /u "C:\your_service_name_with_path.exe"
  • You will get a success message.