Working with Constructors in C# - Type of constructors and their properties

In our everyday programming we must have came across Constructors, In this article we will see some basics of Constructors, type of constructors, and their properties.

If you are a beginner, then this article will help you clear all your doubts about constructors and their usage.

What is a Constructor?


A Constructor is a special method, whose name is same as the class name and do not have any return type. Constructors are usually used to initialize the data members of the class.

Key Points about Constructors;
  • Constructors have the same name as the class.
  • Constructors are used to initialize the data members of the class
  • Constructors do not have any return type not even void.
  • Constructors can not be called explicitly by user.
  • If you want some code to get executed automatically then you can write those inside the constructors.



Example of a Constructor


Below is a simple example of a constructor that is used to initialize some data members of a class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee("015-0012", "Tapan kumar");

            Console.WriteLine("EmpID: " + objEmployee.EmpID);
            Console.WriteLine("FullName: " + objEmployee.FullName);

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string EmpID { get; set; }
        public string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee(string empId, string fullName)
        {
            EmpID = empId;
            FullName = fullName;
        }
    }
}
So, in the above example we have a class named Employee, which has two data members EmpID and FullName.

As you can see I have defined a Constructor whose name is same as the Class name, Employee. It takes two parameters and then inside it initializes the data members.

If you have marked then you will find the Constructor did not have any return type. And we have to parse the parameters in the time of initialization of the object of the class.

Below is the output of this program.


Type of Constructors


There are four type of constructors as listed below.
  • Default Constructors
  • Parameterized Constructors
  • Static Constructors
  • Private Constructors
  • Copy Constructors
Let's explore these constructors one by one.

Default Constructor


Default Constructor is a constructor which does not take any parameters. By default C# creates a default constructor and whenever an object of the class is created, it instantiates the data members.

Basically it initializes all integer values to 0 and string values to null.

Here is an example of a default constructor.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee();

            Console.WriteLine("EmpID: " + objEmployee.EmpID);
            Console.WriteLine("FullName: " + objEmployee.FullName);

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string EmpID { get; set; }
        public string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee()
        {
            EmpID = "015-100";
            FullName = "Tapan kumar";
        }
    }
}
The above code gives the output as below;

OutPut: 
EmpID: 015-100
FullName: Tapan kumar


Parameterized Constructors


These are the constructors those take at least one parameter to initialize the data members. The advantage of parameterized constructor is that each instance of the class can be initialized to different values.

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee("015-0012", "Tapan kumar");

            Console.WriteLine("EmpID: " + objEmployee.EmpID);
            Console.WriteLine("FullName: " + objEmployee.FullName);

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string EmpID { get; set; }
        public string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee(string empId, string fullName)
        {
            EmpID = empId;
            FullName = fullName;
        }
    }
}
Here you can see that, during the object creation we are passing some parameters to the The above code gives the output as below;

OutPut:
EmpID: 015-100
FullName: Tapan kumar


Note: In case of parameterized constructors if you do not declare a default constructor then in each place while creating an object of the class, you have to pass the parameters.

 Static Constructor


The static constructor is the special type that does not take access modifiers or have parameters. It is called automatically to initialize the class before the first instance is created or any static members are referenced. The static constructor is not called directly. Users can't control the execution of the static constructor.

Example:
using System;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee("015-0012", "Tapan kumar");

            Employee.ShowEmpDetails();

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public static string EmpID { get; set; }
        public static string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee(string empId, string fullName)
        {
            EmpID = empId;
            FullName = fullName;
        }

        public static void ShowEmpDetails()
        {
         Console.WriteLine("EmpID: " + EmpID);
            Console.WriteLine("FullName: " + FullName);
        }
    }
}
Note: A Static Constructor do not take any access modifier. It can not be called directly by user code.
OutPut:
EmpID: 015-100
FullName: Tapan kumar

Private Constructors


As the name suggests Private Constructor must have a private access modifier before it. And we can neither create any object of the class nor can inherit the class. 

Private constructors are used in classes that contain only static members. We can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining


Copy Constructors


Copy Constructor is one which takes an object of the same class as parameter. It is being used to copy variables from another object.

It is basically used to initialize the object with the same data values of another instance of the class.

Example:
using System;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Implementing the constructor and passing values to it.
            Employee objEmployee = new Employee("015-0012", "Tapan kumar");

            Employee objEmployeeCopy = new Employee(objEmployee);

            Console.WriteLine("EmpID: " + objEmployeeCopy.EmpID);
            Console.WriteLine("FullName: " + objEmployeeCopy.FullName);

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public  string EmpID { get; set; }
        public  string FullName { get; set; }

        /// <summary>
        /// The is a constructor to initialize the member variables EmpID and FullName
        /// </summary>
        /// <param name="empId"></param>
        /// <param name="fullName"></param>
        public Employee(string empId, string fullName)
        {
            EmpID = empId;
            FullName = fullName;
        }

        public Employee(Employee objEmployee)
        {
            EmpID = objEmployee.EmpID;
            FullName = objEmployee.FullName;
        }

    }
}
OutPut:
EmpID: 015-100
FullName: Tapan kumar

In the above code you can see we are passing the Employee object into the copy constructor which retains the values of the data members as in the objEmployee.

Now I guess you have a clear overview on Constructors and its types and how and where to use these constructors.

If you got any questions then please let me know by putting your valuable comments below.

Happy Codding...


Asynchronous Programming with Async and Await in ASP.NET and C#

Performance is one of the most important thing we developers keep in our mind while developing any type of applications, be it a web application or a windows application or a mobile app.

Performance depends on various parameters but here in this article we will see how Asynchronous Programming will help us in achieving better performance for our application by usage of async and await key words.

In this article we will see what is asynchronous programming and how can we achieve it through async and await keywords in ASP.NET and C#.

What is Asynchronous Programming?


As the name suggests, asynchronous means occurring at the same time. In programming language we can define it like; more than one functionalities are being executed at the same time.

Asynchronous Programming improves responsiveness of the entire application. It is essential for activities those are potential blocking such as accessing some web resources, reading a large file or images, sending multiple emails etc. In Traditional programming such activity is blocked within a synchronous process, hence the entire application has to wait till the process ends. But in asynchronous process the application can continue with some other tasks that is not dependent on the time taking process.




Let's take an example to clear the puzzle around Asynchronous programming.

Consider we have two methods: Method 1, responsible for inserting enquiry record into data base and Method 2, responsible to send an email from an enquiry form.

In this case both methods are independent. Once we got an enquiry from our website we want to save that record in Database and also at the same time we want to send a notification mail to the admin about the enquiry.

Below is the code for this situation. Check it and I will explain bit by bit.
protected void btnSendQuote_Click(object sender, EventArgs e)
  {
      ContactDetails objContactDetails = new ContactDetails();

      objContactDetails.Name = txtQuoteName.Text.Trim();
      objContactDetails.Email = txtQuoteEmail.Text.Trim();
      objContactDetails.Phone = txtQuotePhone.Text.Trim();
      objContactDetails.Message = txtQuoteMessage.Text.Trim();

      int retId = AddContactDetails(objContactDetails);

      bool isSent = SendNotificationEmail(objContactDetails);


      if (retId > 0 && isSent == true)
      {
          Response.Redirect("thank-you.aspx");
      }
      else
      {
          Response.Redirect("error.aspx");
      }
  }

  public int AddContactDetails(ContactDetails objContactDetails)
  {
      using (SqlConnection sqlConnection = new SqlConnection(_dbConnectionString))
      {
          using (SqlCommand sqlCommand = new SqlCommand("SaveContactDetail", sqlConnection))
          {
              sqlCommand.CommandType = CommandType.StoredProcedure;
              sqlCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = objContactDetails.Name;
              sqlCommand.Parameters.Add("@Phone", SqlDbType.VarChar).Value = objContactDetails.Phone;
              sqlCommand.Parameters.Add("@Email", SqlDbType.NVarChar).Value = objContactDetails.Email;
              sqlCommand.Parameters.Add("@Message", SqlDbType.NVarChar).Value = objContactDetails.Message;

              sqlConnection.Open();

              return Convert.ToInt32(sqlCommand.ExecuteScalar());
          }
      }
  }

  public bool SendNotificationEmail(ContactDetails objContactDetails)
  {
      //Assign the smtp credentials for gmail
      SmtpClient smtp = new SmtpClient();
      if (true)
      {
          smtp.Host = "smtp.zoho.com";
          smtp.Port = 587;
          smtp.EnableSsl = true;
          smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
          smtp.UseDefaultCredentials = false;
          smtp.Credentials = new NetworkCredential("test@gmail.com", "Password");
          smtp.Timeout = 10000;
      }

      MailAddress fromAddress = new MailAddress("test@gmail.com", "Enquiry From iCodeFor.NET");      MailAddress toAddress = new MailAddress("youremail@gmail.com", "Your Name");

      //Passing values to smtp object
      dynamic message = new MailMessage(fromAddress, toAddress);


      message.Subject = "[Reminder]Need to take action in " + objContactDetails.TimeDifference + " min for '" + objContactDetails.ClientName + "'";
      message.Body = "<p>Hello Mama, <br/><br/>" +
                     "You need to take action against below reminder:<br/><br/>" +
                     "<table  border='1' style='min-width:700px;border-collapse: collapse;border-color: #ddd;'><tr> <td align = 'left' style='width:110px;'> <strong>Info Header </strong></td> <td align = 'left'> <strong>Details</strong> </td>" +
                     "<tr><td align = 'left'>Client Name: </td><td align = 'left'>" + objContactDetails.ClientName + "</tr>" +
                     "<tr><td align = 'left'>Email: </td><td align = 'left'>" + objContactDetails.Email + "</tr>" +
                     "<tr><td align = 'left'>Phone: </td><td align = 'left'>" + objContactDetails.Phone + "</tr></table>" +
                     "<tr><td align = 'left'>Message: </td><td align = 'left'>" + objContactDetails.Message + "</tr></table>" +
                     "<br/> Thanks <br/> TaxPhobia</p>";
      message.IsBodyHtml = true;
      message.Priority = MailPriority.High;

      //Send email
      smtp.Send(message);

      return true;
  }
As you can see in the above code; The button click event btnSendQuote_Click is responsible to call both the send email and save data to database method.

So what happens there is, during the course of execution of AddContactDetails method the application gets blocked and SendContactEmail mwthod waits till the completion of the previous method although there is no dependency between these two methods.



This was an example of Synchronous Program, where one method has to wait for the previous method to get executed.

In Asynchronous programming we can make these two methods execute at the same time without waiting for each other. Which in turn improves the performance and the entire application has not to be blocked during the course of execution.

Why to choose Asynchronous Programming ?


Usually in an synchronous application, the entire application becomes unresponsive until all the processes/methods are not fully executed. Consider the above application; during the execution of both the methods the application gets stuck and do not allow you to resize the window, to navigate to any other page etc. basically it waits till the end of execution and becomes unresponsive.

So, to address this issue we can run all the methods in parallel by using the simple thread programming but it will block UI and wait to complete all the tasks. To come out of this problem, we have to write too many codes in traditional programming but if we will simply use the async and await keywords, then we will get the solutions in much less code.



Lets Convert the above program into an asynchronous one by using async and await keyword.
protected void btnSendQuote_Click(object sender, EventArgs e)
  {
      CallMethodsAsync();
  }

  public async void CallMethodsAsync()
  {
      ContactDetails objContactDetails = new ContactDetails();

      objContactDetails.Name = txtQuoteName.Text.Trim();
      objContactDetails.Email = txtQuoteEmail.Text.Trim();
      objContactDetails.Phone = txtQuotePhone.Text.Trim();
      objContactDetails.Message = txtQuoteMessage.Text.Trim();

      Task<int> taskSaveToDB = AddContactDetails(objContactDetails);

      Task<bool> taskSendEmail = SendNotificationEmail(objContactDetails);

      int retId = await taskSaveToDB;
      bool isSent = await taskSendEmail;

      if (retId > 0 && isSent == true)
      {
          Response.Redirect("thank-you.aspx");
      }
      else
      {
          Response.Redirect("error.aspx");
      }
  }

  public async Task<int> AddContactDetails(ContactDetails objContactDetails)
  {
      using (SqlConnection sqlConnection = new SqlConnection(_dbConnectionString))
      {
          using (SqlCommand sqlCommand = new SqlCommand("SaveContactDetail", sqlConnection))
          {
              sqlCommand.CommandType = CommandType.StoredProcedure;
              sqlCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = objContactDetails.Name;
              sqlCommand.Parameters.Add("@Phone", SqlDbType.VarChar).Value = objContactDetails.Phone;
              sqlCommand.Parameters.Add("@Email", SqlDbType.NVarChar).Value = objContactDetails.Email;
              sqlCommand.Parameters.Add("@Message", SqlDbType.NVarChar).Value = objContactDetails.Message;

              sqlConnection.Open();

              return await Convert.ToInt32(sqlCommand.ExecuteScalar().ConfigureAwait(false));
          }
      }
  }

  public async Task<bool> SendNotificationEmail(ContactDetails objContactDetails)
  {
      //Assign the smtp credentials for gmail
      SmtpClient smtp = new SmtpClient();
      if (true)
      {
          smtp.Host = "smtp.zoho.com";
          smtp.Port = 587;
          smtp.EnableSsl = true;
          smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
          smtp.UseDefaultCredentials = false;
          smtp.Credentials = new NetworkCredential("test@gmail.com", "Password");
          smtp.Timeout = 10000;
      }

      MailAddress fromAddress = new MailAddress("test@gmail.com", "Enquiry From iCodeFor.NET");      MailAddress toAddress = new MailAddress("yourmail@gmail.com", "Your Name");

      //Passing values to smtp object
      dynamic message = new MailMessage(fromAddress, toAddress);


      message.Subject = "[Reminder]Need to take action in " + objContactDetails.TimeDifference + " min for '" + objContactDetails.ClientName + "'";
      message.Body = "<p>Hello Mama, <br/><br/>" +
                     "You need to take action against below reminder:<br/><br/>" +
                     "<table  border='1' style='min-width:700px;border-collapse: collapse;border-color: #ddd;'><tr> <td align = 'left' style='width:110px;'> <strong>Info Header </strong></td> <td align = 'left'> <strong>Details</strong> </td>" +
                     "<tr><td align = 'left'>Client Name: </td><td align = 'left'>" + objContactDetails.ClientName + "</tr>" +
                     "<tr><td align = 'left'>Email: </td><td align = 'left'>" + objContactDetails.Email + "</tr>" +
                     "<tr><td align = 'left'>Phone: </td><td align = 'left'>" + objContactDetails.Phone + "</tr></table>" +
                     "<tr><td align = 'left'>Message: </td><td align = 'left'>" + objContactDetails.Message + "</tr></table>" +
                     "<br/> Thanks <br/> TaxPhobia</p>";
      message.IsBodyHtml = true;
      message.Priority = MailPriority.High;

      //Send email
      await smtpClient.SendMailAsync(message);

      return true;
  }
In the above code we have converted the synchronous program into an asynchronous program by the help of async and await keywords.

The return type of an async method is Task, Below code holds the returned TResults from the async method.
Task<int> taskSaveToDB = AddContactDetails(objContactDetails);

 Task<bool> taskSendEmail = SendNotificationEmail(objContactDetails);
And these two lines are responsible for parallel execution of both AddContactDetails and SendNotificationEmail methods, without waiting for each other.



But during the comparison of the returned values we need to wait for both methods so there we have to use the await keyword like below.
int retId = await taskSaveToDB;
 boolisSent = await taskSendEmail;
Here is the steps to understand the execution of this asynchronous program.
  1. The button click event named btnSendQuote_Click calls the CallMethodsAsync async method
  2. Now CallMethodsAsync has two async methods to call one for Database operation and another one for sending email.
  3. So now AddContactDetails is being called asynchronously which executes the sql command and here it should wait for some time for Db connection and operation and to avoid that blocking it yeilds control to its caller CallMethodsAsync.
  4. Same for the SendNotificationEmail; when this async method is called it also yields the control to its caller CallMethodsAsync 
  5. Now as both the async methods are running simultaneously we can call any synchronous method but here we do not have any. Hence we have to now wait for both the operations return value in order to make the redirection.
  6. Once both the methods returns their respective TResults we can compare accordingly and proceed with the redirection.
Now I guess we have gone through a basic example and have some basic idea of what asynchronous programming is and how it can serve us to boost performance and UI responsiveness.

Points to Remember about Asynchronous Programming.


  • The Asynchronous method must have async modifier
  • The async method must have at least one await expression.
  • The return type is of Task or void.
Happy codding...

Authentication and Authorization in ASP.NET

Authentication and Authorization in ASP.NET is a common question asked by most of the ASP.NET interview questions.

There are a lot of developers who do not use the inbuilt processes of authentication and authorization provided by ASP.NET framework, as they commonly use the normal process of user authentication and then storing the details in session variables to be accessed in various times.

In this article we will take a deep dive into the inbuilt methods provided by ASP.NET framework to achieve authentication and authorization in your application.



What is Authentication?


Authentication is the process of evaluating the identity of a user, trying to access some resource of the application. Basically it is the process of validating a user's username with its password.

Basically we need to authenticate a user when our application's resource is not public facing and we do not want everyone to access it over the internet.

What is Authorization?


Authorization is the process of authorizing a user to access some resources according to role assigned to him/her. let me give you a small example. 

Let's say we have a web application for a company where we have a sales department, a HR department and an admin department. And all the department have different works to do and we do not want them to peep into other's profiles and other details. So here we limit the access of a HR only to the HR related resources, sales person to access only sales related resources and admins to access only admin related resources. This process of evaluating if a user is a valid user to access certain resources of the application is called authorization.



Types of Authentication in ASP.NET


There are 3 type of authentication available in ASP.NET, such as
  • Windows Authentication
  • Form's Authentication
  • Passport Authentication
  • Anonymous Access
Now we will see each type in detail.

Windows Authentication


Windows Authentication is a process of authentication where we use the local windows users and groups for authentication and authorization.

This is basically used when we prefer to use an application in intranet than internet. Consider a company where an application is designed only to run within the organization and not outside, then we can implement windows authentication over there to validate the identity of the user using their own credentials for the system.

To achieve windows authentication you need to configure the application as well as the IIS for it.



In Web.config file you have to mention the type of authentication the application is going to have. For Windows Authentication we have to set the authentication mode to Windows as below;
<authentication mode="Windows"/>
Once the authentication mode is set we have to set the authorization accordingly.
<authorization>
  <deny users="?"/>
</authorization>
The above code will deny all users to access the website except the authorized users.

Form's Authentication


Form's Authentication is a process where user has to provide the username and password for authentication in a web page and after authentication the user details will be stored in a cookie at client's machine and will be accessed at various times for authorization.

Below is the code to set Form's Authentication in web.config.
<authentication mode="Forms">
Now the question in how to set the login url and all. Below is the code you have to write in the web.config file to achieve form's authentication and to set the login url for all users.
<system.web>
  <authentication mode="Forms">
    <forms loginUrl="logon.aspx" name=".ASPXFORMSAUTH">
    </forms>
  </authentication>
  <authorization>
<deny users="?" />
  </authorization>
</system.web>
The above code will set logon.aspx page as the login page where user has to provide his/her login credentials. and after verification he will be allowed to access the resources of the website.

Passport Authentication


passport authentication is the process where users are redirected to a third party website for authentication and after verification they are redirected back our website. Once authentication is done it creates a cookie in the client's machine which will be accessible to our website for authentication.



basically this type of authentication is being used mostly now-a-days to help users not to remember their username and password for every site. Just remember the username and password for a common site like facebook, google or microsoft and use that credential to login into any site.

In order to set this authentication you need not to do any configuration in your web.cofig file.

Anonymous Authentication


When your website is public facing and you do not want any type of authentication then this anonymous type of authentication is being used. Basically all the site resources are accessible to all users.

Hope in this article I have cleared all the concepts of authentication and authorization in ASP.NET.

Happy codding...

Create TreeView in JQuery using jsTree Plugin from flat JSON Data

In my previous article Create TreeView using jsTree Plugin and nested JSON Data we have seen how to create treeview structure using jsTree plugin and a nested JSON data.

This article will explain on creating Tree-View structure using jsTree plugin and a flat JSON data. This flat JSON data structure is more easy to implement rather than the nested structure as its very easy to get the data from database and hold it inside a custom list and just deserialize it into a flat JSON with some parent id.

Follow my previous article and setup the project to use jsTree plugin, once you set it up we are all set to consume the flat JSON data structure to use in the project.

Find out all the articles on jsTree here.

Tree View Example


View Live Demo


Creating container for the jsTree


Here is the html container that will use the flat JSON structure to create the jsTree.
<div class="panel panel-primary">
       <div class="panel-heading">
           <h3 class="panel-title">Flat JSON Example Data</h3>
       </div>
       <div class="panel-body">
           <div class="m-b-10">
               <asp:TextBox ID="txtSearchAPI" runat="server" placeholder="Serch JSTree" CssClass="search-input form-control"></asp:TextBox>
           </div>

           <div id="jstree-api">
           </div>
       </div>
       <div id="footer-api" class="panel-footer">You have not selected any node</div>
   </div>

 Now lets feed the jsTree with JSON Data


The jsTree will work on only JSON data and it has two predefined structure, in which the JSON will be accepted.
  1. JSON with nested elements (parent-children structure)
  2. JSON with flat structure (with parent id structure)
The first one JSON with nested elements is a bit difficult to produce when you are using a database so I prefer using the second one as its pretty simple and easy because of its flat structure.



Below is the flat JSON format. This JSON format is easy to generate from backend; be it C# or PHP.
var jsonData = [
       { "id": "1", "parent": "#", "text": "Folder 1" },
       { "id": "2", "parent": "1", "text": "Sub Folder 1" },
       { "id": "3", "parent": "2", "text": "Sub - Sub Folder 1" },
       { "id": "4", "parent": "1", "text": "Sub Folder 2" },
       { "id": "5", "parent": "#", "text": "Folder 2" },
    ];
The jquery code for loading the jsTree is same for nested JSON and flat JSON.
function LoadJSTreeWithFlatJSONData() {

    var jsonData = [
       { "id": "1", "parent": "#", "text": "Folder 1", type: "root" },
       { "id": "2", "parent": "1", "text": "Sub Folder 1", type: "child" },
       { "id": "3", "parent": "2", "text": "Sub - Sub Folder 1", type: "child" },
       { "id": "4", "parent": "1", "text": "Sub Folder 2", type: "child" },
       { "id": "5", "parent": "#", "text": "Folder 2", type: "root" },
    ];

    $("#txtSearchAPI").keyup(function () {
        var searchString = $(this).val();
        console.log(searchString);
        $('#jstree-api').jstree('search', searchString);
    });

    $('#jstree-api').jstree({
        'core': {
            'data': jsonData
        },
        "types": {
            "child": {
                "icon": "glyphicon glyphicon-leaf"
            },
            "root": {
                "icon": "glyphicon glyphicon-folder-close"
            },
            "default": {
                "icon": "glyphicon glyphicon-folder-close"
            }
        },
        "search": {

            "case_insensitive": true,
            "show_only_matches": true


        },

        "plugins": ["search", "themes", "types"]
    });

    $('#jstree-api').on('changed.jstree', function (e, data) {
        var objNode = data.instance.get_node(data.selected);
        var note;
        note = 'Selected Node Data(Id: <strong>' + objNode.id + '</strong>, Name: <strong>' + objNode.text + '</strong>)'; e = 'Selected Category(Id: <strong>' + objNode.id + '</strong>, Name: <strong id="api-data" data-parent="' + objNode.parent + '" data-id="' + objNode.id + '">' + objNode.text + '</strong>)';

        $('#footer-api').html(note);
    });

    $('#jstree-api').on('open_node.jstree', function (e, data) {
        data.instance.set_icon(data.node, "glyphicon glyphicon-folder-open");
    }).on('close_node.jstree', function (e, data) { data.instance.set_icon(data.node, "glyphicon glyphicon-folder-close"); });
}

View Live Demo

That's it you have created a jsTree with nested JSON data. Check out my next article on creating jsTree with flat JSON data. And all articles on JsTree here.

Happy Codding...

Create Tree-view in JQuery using jsTree Plugin From Nested JSON Data

Treeview is a structure we mostly use to represent parent-children data for better observation.

But when it comes to ASP.NET development there is a server side control named treeview for it. But I am sure it's not that efficient now-a-days when everything is being done in front-end side by JavaScript frameworks we never gonna use this one.
There are many Jquery plugins available in the internet to create TreeView but I find jsTree very intuitive and easy to use.

There are few articles a good documentation on it in their site but I still found those not sufficient enough to get started with jsTree when you are using it for the first time. So I came up with an idea to create a series of blogs on jsTree that can help people who are trying to figure it out and want to use jsTree in their ASP.NET applications.

Find out all the articles on jsTree here.

Tree View Example
Before we get into the details of jsTree and its implementations you need to download the js and css files for it. Download jsTree plugin from here.


View Live Demo


Setting up a Project and adding jsTree resources


Now create a project in visual studio and add the jstree-src folder inside it, that you got from the download.

Contents of jsTree folder



The folder has two themes one is default and one is a darker one. You can use those according to your need. Now lets add the js and css references to your web page.

<script src="js/jquery.min.js"></script>
<script src="jstree-src/jstree.min.js"></script>

<link href="jstree-src/themes/default/style.css" rel="stylesheet" />
You also need to add a jquery reference in your page in order to use the jsTree plugin.

Creating container for the jsTree


Below is the html I have used in my demo project, but you might not want to use the entire html. Just use the container to populate the jsTree.
<div role="tabpanel" class="tab-pane active p-20-0" id="preview" aria-labelledby="preview-tab">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">Nested JSON Example Data</h3>
            </div>
            <div class="panel-body">
                <div class="m-b-10">
                    <asp:TextBox ID="txtSearchXML" runat="server" placeholder="Serch JSTree" CssClass="search-input form-control"></asp:TextBox>
                </div>

                <div id="jstree-xml">
                </div>
            </div>
            <div id="footer-xml" class="panel-footer">You have not selected any node</div>
        </div>
    </div>
You just need the below container for jsTree.
<div id="jstree-xml"> </div>

 Now lets feed the jsTree with JSON Data


The jsTree will work on only JSON data and it has two predefined structure, in which the JSON will be accepted.
  1. JSON with nested elements (parent-children structure)
  2. JSON with flat structure (with parent id structure)
The first one JSON with nested elements is a bit difficult to produce when you are using a database so I prefer using the second one as its pretty simple and easy because of its flat structure.



But in this article we will use the first json format i.e JSON with nested element to populate the jsTree. Below is the JSON format.
var jsonData = [
      {
          id: 1,
          text: "Folder 1",
          state: {
              selected: false
          },
          children: [
            {
                id: 2,
                text: "Sub Folder 1",
                state: {
                    selected: false
                },
                children: [
                     {
                         id: 3,
                         text: "Sub - Sub Folder 1",
                         state: {
                             selected: true
                         },
                         children: []
                     }
                ],
            },
            {
                id: 4,
                text: "Sub Folder 2",
                state: {
                    selected: false
                },
            }
          ]
      },
      {
          id: 5,
          text: "Folder 2",
          state: {
              selected: false
          },
          children: []
      }
    ];
Now we will initiate the jsTree with required attributes.
$('#jstree-xml').jstree({
        'core': {
            'data': jsonData
        },
        "types": {
            "child": {
                "icon": "glyphicon glyphicon-leaf"
            },
            "root": {
                "icon": "glyphicon glyphicon-folder-close"
            },
            "default": {
                "icon": "glyphicon glyphicon-folder-close"
            }
        },
        "search": {

            "case_insensitive": true,
            "show_only_matches": true


        },

        "plugins": ["search", "themes", "types"]
    });
If you look into the above code you can find below attributes

core: this is taking the json data in the variable data. this is where we will attach ajax functions in our next articles to feed the jstree with json data.




type: this is the attribute that is responsible for styling nodes. If a node is of type root then the defined style will be applied to it and if of child then the specified style for child type will be added to that node.

search: this says about the search feature options if its case sensitive or not and all.

In the next section we will set up a search feature in the jsTree and the code is below. I have taken a textbox and will search the jsTree on keyUp function. You can customize it according to your need. You may take a textbox and a button and on click of it you can perform a search or whatever you want.
$("#txtSearchXML").keyup(function () {
        var searchString = $(this).val();
        console.log(searchString);
        $('#jstree-xml').jstree('search', searchString);
    });
And  now we will write another function to get the selected node information. Below is the code to get the selected node information of the jsTree.
$('#jstree-xml').on('changed.jstree', function (e, data) {
        var objNode = data.instance.get_node(data.selected);
        var note;

        note = 'Selected Node Data(Id: <strong>' + objNode.id + '</strong>, Name: <strong>' + objNode.text + '</strong>)';

        $('#footer-xml').html(note);
    });
Here I am getting the node information and printing it on the panel footer.

If you are looking for the whole jquery function to load the jsTree with nested JSON data then here it is.
function LoadJSTreeWithNestedJSONData() {

    $('#jstree-xml').jstree({
        'core': {
            'data': jsonData
        },
        "types": {
            "child": {
                "icon": "glyphicon glyphicon-leaf"
            },
            "root": {
                "icon": "glyphicon glyphicon-folder-close"
            },
            "default": {
                "icon": "glyphicon glyphicon-folder-close"
            }
        },
        "search": {

            "case_insensitive": true,
            "show_only_matches": true


        },

        "plugins": ["search", "themes", "types"]
    });

    $("#txtSearchXML").keyup(function () {
        var searchString = $(this).val();
        console.log(searchString);
        $('#jstree-xml').jstree('search', searchString);
    });

    $('#jstree-xml').on('changed.jstree', function (e, data) {
        var objNode = data.instance.get_node(data.selected);
        var note;

        note = 'Selected Node Data(Id: <strong>' + objNode.id + '</strong>, Name: <strong>' + objNode.text + '</strong>)';

        $('#footer-xml').html(note);
    });
}

View Live Demo

That's it you have created a jsTree with nested JSON data. Check out my next article on creating jsTree with flat JSON data. And all articles on JsTree here.

Happy Codding...

Deserialize n-level(multi level) JSON data to C# custom object

Ever wondered how to deserialize a multi level(nested) JSON data where you are not sure of the level. It my be upto level 5 or upto n level.

I faced a similar situation where I have to fetch the product information from an API, exposed by an eCommerce site. And the JSON I got is of a multi level nested JSON.

I searched a lot in Google on how to hold that JSON data into a custom C# List of objects, but found no help. After a long research and trying my hands here and there I found the best solution.



Here is the JSO format I was getting from API.
{
   "Categories":[
      {
         "Code":"2984",
         "Name":"Baby",
         "Children":[
            {
               "Code":"100978",
               "Name":"Christening & Gifts",
               "Children":[
                  {
                     "Code":"100980",
                     "Name":"Baby Jewellery"
                  },
                  {
                     "Code":"100981",
                     "Name":"Ornaments"
                  },
                  {
                     "Code":"121628",
                     "Name":"Gift Baskets"
                  },
                  {
                     "Code":"139760",
                     "Name":"Christening",
                     "Children":[
                        {
                           "Code":"100979",
                           "Name":"Gifts"
                        },
                        {
                           "Code":"139764",
                           "Name":"Silverware"
                        },
                        {
                           "Code":"139765",
                           "Name":"Other Christening"
                        }
                     ]
                  },
                  {
                     "Code":"32871",
                     "Name":"Other Gifts"
                  }
               ]
            }
         ]
      },
      {
         "Code":"100982",
         "Name":"Baby Carriers/Backpacks"
      },
      {
         "Code":"1261",
         "Name":"Other Baby"
      },
      {
         "Code":"134282",
         "Name":"Walkers"
      }
   ]
}
Here you can see there is 3 level of children but this can go upto n-level. So the question is how your C# object structure should be to hold this type of JSO data.

There is a free tool available that will take your JSON and give the respective C# object structure. Here it is. http://json2csharp.com/

This tool give me the below class structure.
public class Child3
{
    public string Code { get; set; }
    public string Name { get; set; }
}

public class Child2
{
    public string Code { get; set; }
    public string Name { get; set; }
    public List<Child3> Children { get; set; }
}

public class Child
{
    public string Code { get; set; }
    public string Name { get; set; }
    public List<Child2> Children { get; set; }
}

public class Category
{
    public string Code { get; set; }
    public string Name { get; set; }
    public List<Child> Children { get; set; }
}

public class RootObject
{
    public List<Category> Categories { get; set; }
}
I am sure this is not the optimum solution to the problem because it can hold data only up to 3 level. If the hierarchy goes on increasing then this will fail to perform.



So if you are looking for an optimum solution and here it is.
public class MyRootCategory
  {
      public Node[] Categories { get; set; }
  }
  
  public class Node
  {
      public string Code { get; set; }
      public string Name { get; set; }
      public Node[] Children { get; set; }
  }
This class structure can handle n-level hierarchy. And is the optimum solution we are looking for.

The code below will deserialize the json string to an object of type MyRootCategory
  var objJSON = JObject.Parse(result);
  var objResponse = objJSON["Response"].ToString();

  MyRootCategory categoryTree = JsonConvert.DeserializeObject<MyRootCategory>(objResponse);
If you are looking for, how to save this n-level list to database by iterating then stay tuned to my next article

Till then Happy Codding....

Read XML file in ASP.NET(C#)

This is very often when we face such situations to read XML file and create custom objects of it. There might be many articles in the internet but as I came across this thing recently, I thought of sharing my experience with people who might find it helpful.

Alright, in this article I will read a XML file from C#(ASP.NET) and create a custom object from it and then use it according to my need.



Here is the XML file, that is generated from an eCommerce site and has some product information.
<?xml version="1.0"?>
<Products>
  <Product>
    <ProductId>25303611</ProductId>
    <Barcode>171-H007/1</Barcode>
    <CategoryCode>548</CategoryCode>
    <Brand></Brand>
    <Image>https://img.epttavm.com/prodotti/592/025/303/25303611_0.jpg</Image>
    <Price>10.8227</Price>
    <ListPrice>10.8227</ListPrice>
    <BuyingPrice>10.8227</BuyingPrice>
    <TryPrice>10.8227</TryPrice>
    <TaxedPrice>10.8227</TaxedPrice>
    <EftPrice>10.8227</EftPrice>
    <SpecialPrice>10.8227</SpecialPrice>
    <Quantity>100</Quantity>
    <Variant1></Variant1>
    <Variant2></Variant2>
    <Variant3></Variant3>
    <Variant4></Variant4>
    <PriceDiff1></PriceDiff1>
    <PriceDiff2></PriceDiff2>
    <PriceDiff3></PriceDiff3>
    <PriceDiff4></PriceDiff4>
    <Manufacture></Manufacture>
    <TaxRate>8</TaxRate>
    <ModelNumber></ModelNumber>
    <Status>0</Status>
    <Attributes/>
    <CategoryPath>Ev Dekorasyon &gt;&gt; Banyo Tekstili test 1</CategoryPath>
    <GetTranslation></GetTranslation>
    <Culture>tr</Culture>
    <Name><![CDATA[Apolena Dekoratif Havlu Set 171-h007-1]]></Name>
    <Description><![CDATA[<p><font face="Arial"><strong>SIZES:</strong> Large 70 x 140 cm Towel+ Small Towel 50X 90 cm </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>FABRIC:</strong> 100% cotton </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Material information:</strong> 2-Piece decorative Towel. Specialized manufacture of our fabrics and soft. Products used in textile dyes that are Oeko-Tex® Standard 100 certification standards because it does not contain carcinogenic substances harmful to human and animal health. </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Care information:</strong> wash at 40 with water by hand or in a washing machine. Waiting and wet do not use bleach. During washing light and dark colors to keep separate. At low rpm you can dry in the dryer drum. </font></p>]]></Description>
  </Product>
  <Product>
    <ProductId>25303635</ProductId>
    <Barcode>171-H081/1</Barcode>
    <CategoryCode>548</CategoryCode>
    <Brand></Brand>
    <Image>https://img.epttavm.com/prodotti/592/025/303/25303635_0.jpg</Image>
    <Price>10.8227</Price>
    <ListPrice>10.8227</ListPrice>
    <BuyingPrice>10.8227</BuyingPrice>
    <TryPrice>10.8227</TryPrice>
    <TaxedPrice>10.8227</TaxedPrice>
    <EftPrice>10.8227</EftPrice>
    <SpecialPrice>10.8227</SpecialPrice>
    <Quantity>100</Quantity>
    <Variant1></Variant1>
    <Variant2></Variant2>
    <Variant3></Variant3>
    <Variant4></Variant4>
    <PriceDiff1></PriceDiff1>
    <PriceDiff2></PriceDiff2>
    <PriceDiff3></PriceDiff3>
    <PriceDiff4></PriceDiff4>
    <Manufacture></Manufacture>
    <TaxRate>8</TaxRate>
    <ModelNumber></ModelNumber>
    <Status>0</Status>
    <Attributes/>
    <CategoryPath>Ev Dekorasyon &gt;&gt; Banyo Tekstili</CategoryPath>
    <GetTranslation></GetTranslation>
    <Culture>tr</Culture>
    <Name><![CDATA[Apolena Dekoratif Havlu Set 171-h081-1]]></Name>
    <Description><![CDATA[<p><font face="Arial"><strong>SIZES:</strong> Large 70 x 140 cm Towel+ Small Towel 50X 90 cm </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>FABRIC:</strong> 100% cotton </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Material information:</strong> 2-Piece decorative Towel. Specialized manufacture of our fabrics and soft. Products used in textile dyes that are Oeko-Tex® Standard 100 certification standards because it does not contain carcinogenic substances harmful to human and animal health. </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Care information:</strong> wash at 40 with water by hand or in a washing machine. Waiting and wet do not use bleach. During washing light and dark colors to keep separate. At low rpm you can dry in the dryer drum. </font></p>]]></Description>
  </Product>
  <Product>
    <ProductId>25303647</ProductId>
    <Barcode>171-H060/1</Barcode>
    <CategoryCode>548</CategoryCode>
    <Brand></Brand>
    <Image>https://img.epttavm.com/prodotti/592/025/303/25303647_0.jpg</Image>
    <Price>10.8227</Price>
    <ListPrice>10.8227</ListPrice>
    <BuyingPrice>10.8227</BuyingPrice>
    <TryPrice>10.8227</TryPrice>
    <TaxedPrice>10.8227</TaxedPrice>
    <EftPrice>10.8227</EftPrice>
    <SpecialPrice>10.8227</SpecialPrice>
    <Quantity>100</Quantity>
    <Variant1></Variant1>
    <Variant2></Variant2>
    <Variant3></Variant3>
    <Variant4></Variant4>
    <PriceDiff1></PriceDiff1>
    <PriceDiff2></PriceDiff2>
    <PriceDiff3></PriceDiff3>
    <PriceDiff4></PriceDiff4>
    <Manufacture></Manufacture>
    <TaxRate>8</TaxRate>
    <ModelNumber></ModelNumber>
    <Status>0</Status>
    <Attributes/>
    <CategoryPath>Ev Dekorasyon &gt;&gt; Banyo Tekstili</CategoryPath>
    <GetTranslation></GetTranslation>
    <Culture>tr</Culture>
    <Name><![CDATA[Apolena Dekoratif Havlu Set 171-h060-1]]></Name>
    <Description><![CDATA[<p><font face="Arial"><strong>SIZES:</strong> Large 70 x 140 cm Towel+ Small Towel 50X 90 cm </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>FABRIC:</strong> 100% cotton </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Material information:</strong> 2-Piece decorative Towel. Specialized manufacture of our fabrics and soft. Products used in textile dyes that are Oeko-Tex® Standard 100 certification standards because it does not contain carcinogenic substances harmful to human and animal health. </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Care information:</strong> wash at 40 with water by hand or in a washing machine. Waiting and wet do not use bleach. During washing light and dark colors to keep separate. At low rpm you can dry in the dryer drum. </font></p>]]></Description>
  </Product>
 <Products>
My Job is to extract the category and sub category details from that xml and save those to database for further usage.

I have created one class where I need the category and sub category to be stored. Below is the Category class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mpper.Entity
{
    public class Category
    {
        public int? Id { get; set; }

        public string Code { get; set; }

        public string Name { get; set; }

        public string SubCategoryName { get; set; }

        public string CategoryPath { get; set; }

        public int? ParentId { get; set; } 
    }
}



Now as the XML is having multiple nodes of products, I am expecting a list of Categories and here is how I get the data into the C# list from the XML file.
public List<Category> GenerateCategoryListFromProductFeedXML()
  {
      string path = System.Web.HttpContext.Current.Server.MapPath("~/Product Feed/product-feed.xml");

      XDocument xDoc = XDocument.Load(path);

      XElement xElement = XElement.Parse(xDoc.ToString());

      List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
      {
          Code = Convert.ToString(d.Element("CategoryCode").Value),
          CategoryPath = d.Element("CategoryPath").Value,
          Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
          SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
      }).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();

      return lstCategory;
  }
Here I am using the XDocument and XElement classes to parse the XML for which you need to add reference of "System.Xml.Linq" namespace in your project.

Now if you look into the above code you can see I am creating a XDocument object first, which will hold the XML data from the location. (I am using System.Web.HttpContext as my code was inside a class library. If you are going to use this method in a web project then you might not need that line to get the relative path).

Then XElement was responsible for parsing the string object we got from XDocument.



Once we parse the string xml data, we are ready to generate our custom C# object from the XElement. Here I am running a LINQ query on the xElement.Elements("Product"), where Product is the nested element inside the root element Products.

Then the LINQ code was simple enough, just create a new Category object and assign values from the XElement object to it.

That's it now return the List<Category> and do whatever you want to do with it.

Hope you like this article on how to read a XML file from C# and create a custom object from it.

Happy Codding....