Monday, February 8, 2016

Ref Vs Out Keywords in C#

Ref and out parameters are used to pass an argument within a method. In this article, you will learn the differences between these two parameters. Ref and out change the behavior of method parameters. Sometimes we want the actual value of a variable to be copied as the parameter. Other times we want a reference. These modifiers affect definite assignment analysis.



Ref
The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out
The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Example using ref and out:

using System;

class Program
{
    static void Main()
    {
 string value1 = "cat"; // Assign string value
 SetString1(ref value1); // Pass as reference parameter
 Console.WriteLine(value1); // Write result

 string value2; // Unassigned string
 SetString2(1, out value2); // Pass as out parameter
 Console.WriteLine(value2); // Write result
    }

    static void SetString1(ref string value)
    {
 if (value == "cat") // Test parameter value
 {
     Console.WriteLine("Is cat");
 }
 value = "dog"; // Assign parameter to new value
    }

    static void SetString2(int number, out string value)
    {
 if (number == 1) // Check int parameter
 {
     value = "one"; // Assign out parameter
 }
 else
 {
     value = "carrot"; // Assign out parameter
 }
    }
}

Output:
Is cat
dog
one 

Ref and out in method overloading
Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn't differentiates between the two while it created IL for ref and out). Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.

class MyClass
{
 public void Method(out int a) // compiler error “cannot define overloaded”
 {
 // method that differ only on ref and out"
 }
 public void Method(ref int a) 
 {
 // method that differ only on ref and out" 
 }
}

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.

class MyClass
{
 public void Method(int a) 
 {
 
 }
 public void Method(out int a)
 {
 // method differ in signature.
 }
}

Note:
The out and ref keywords are useful when we want to return a value in the same variables as are passed as an argument.

Ref Vs Out


Ref
Out
The parameter or argument must be initialized first before it is passed to ref.
It is not compulsory to initialize a parameter or argument before it is passed to an out.
It is not required to assign or initialize the value of a parameter (which is passed by ref) before returning to the calling method.
A called method is required to assign or initialize a value of a parameter (which is passed to an out) before returning to the calling method.
Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter.
Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method.
It is not compulsory to initialize a parameter value before using it in a calling method.
A parameter value must be initialized within the calling method before its use.
When we use REF, data can be passed bi-directionally.
When we use OUT data is passed only in a unidirectional way (from the called method to the caller method).
Both ref and out are treated differently at run time and they are treated the same at compile time.
Properties are not variables, therefore it cannot be passed as an out or ref parameter.

Thursday, January 14, 2016

Copy a table into new table with and without data - SQL Server

This article explains  how to copy an existing table to new table in SQL Server.
Lets see how to copy an existing table to new table in SQL Server. There are two options. They are
  • Copy only the structure of an existing table into new table
  • Copy only the structure with data of an existing table into new table

Copy only the structure of an existing table into new table:

SELECT * INTO tblNew FROM tblOld WHERE 1=2


The above query will copy the structure of  an existing table(tblOld) into the new table(tblNew).

Copy only the structure with data of an existing table into new table:

SELECT * INTO tblNew FROM tblOld

This is also same like the previous query, but it copies the structure of existing table(tblOld) with data as well into the new table(tblNew).

Note:-  This will not copy indexes, keys, etc.

If you want to copy the entire structure, you need to generate a Create Script of the table. You can use that script to create a new table with the same structure. You can then also dump the data into the new table if you need to.

If you are using Enterprise Manager, just right-click the table and select copy to generate a Create Script.

Wednesday, January 13, 2016

Why we use Static Class

Introduction:
This article explains why we use static class and what main features of a static class are. A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. Read More

If a class is declared as static then the variables and methods should compulsorily be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Struct in C#

A struct uses syntax similar to a class. It is a type definition. A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:


Example:-

using System;

class Program
{
    public struct Book
    {
    public decimal price;
    public string title;
    public string author;
    public bool IsAvailable;
    };

    static void Main()
    {
    // ... Create struct on stack.
    Book B;
    B.price = 100.00;
    B.title = "MS";
    B.author = "Vepsh";
    B.IsAvailable=true;

    // ... Write struct field.
    Console.WriteLine(B.title);
    }
} 

Output:- MS

Note:-
  • Please notice how, in Main, the struct is created on the stack. No "new" keyword is used. It is used like a value type such as int.
  • Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.
  • Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.

Conclusion:
Means that struct stores its data in its type. It is not allocated separately on the managed heap. Structs often reside on the evaluation stack. Every program uses simple structs. All value types (int, bool, char) are structs.




Tuesday, December 8, 2015

Difference Between ViewData, ViewBag and TempData with Example

Introduction:
In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to view and in next request. Like WebForm, you can also use Session to persist data during a user session. Now question is that when to use ViewData, VieBag, TempData and Session. Each of them has its own importance. This article explains the differences among ViewData, ViewBag and TempData.

Difference Between ViewData, ViewBag and TempData with Example


ViewData

    1- ViewData is used to pass data from controller to view
    2- It is derived from ViewDataDictionary class
    3- It is available for the current request only
    4- Requires typecasting for complex data type and checks for null values to avoid error
    5- If redirection occurs, then its value becomes null

Example:- 
In controller

public ActionResult Index()
{
    ViewData["Name"] = "Vepsh Tech";
    return View();
} 

In View

@ViewData["Name"]


ViewBag

    ViewBag is also used to pass data from the controller to the respective view
    ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
    It is also available for the current request only
    If redirection occurs, then its value becomes null
    Doesn’t require typecasting for complex data type

Example:-
In Controller 

public ActionResult Index()
{
    ViewBag.Name = "Vepsh Tech";
    return View();
}

In View

@ViewBag.Name 

TempData

    1- TempData is derived from TempDataDictionary class
    2- TempData is used to pass data from the current request to the next request
    3- It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
    4- It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages

Example:-

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}

public ActionResult About() 
{     
    var model= TempData["ModelName"];     
    return View(model); 
}

Monday, December 7, 2015

Understanding jQuery Ajax - to async or not ?

Introduction:
This article explains a clear understanding on making synchronous and asynchronous ajax calls through jQuery ajax method. After going through it you can have a clear idea on how and when to do asynchronous ajax calls.

Ajax(Asynchronous Javascript + XML) is a new approach now a days very popular in web development.
Ajax taken our classic web development to a different level. It is a new approach to create
fast and dynamic web pages.It toally removed the reloading part from the classical web development.

There are many Ajax methods provided by jQuery library to accomplish ajax calls as listed below :-
get
post
getScript
getJSON
ajax

These all ajax methods can be used as per requirements you are having but, if you need extensive configurability and want to handle errors by yourself then '.ajax()' method is the best.

To work with the jQuery ajax method we need to set the options available for it properly, from which
'async' is an important setting about which we are going to discuss here as setting its value will have a major impact in getting response properly.

As async is an boolean property, we can set either TRUE or FALSE value for it.
Here i will explain various scenarios on setting each values for the particular property(async) and to help you understanding its importance and usability by situation.

Example:
Here i am explaining simple examples how and when to make your choice in between asynchronous or synchronous ajax calls using jQuery.

Both methods independent of each other :-

There will be no impact on result if both are independent whether it is a asynchronous or synchronous ajax calls :-

$(function () {
    // When both the method are independent & async=false
    // Ajax call will happen one by one
    GetData1(false); // called first
    GetData2(false); // called after GetData1 method processing finished

    // When both the method are independent & async=true
    // Call will happen simultaneously
    GetData1(true); // Both are called simultaneously in different threads
    GetData2(true); // Both are called simultaneously in different threads
});

First Method:-

function GetData1(isAsync) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData1",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            var result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Second Method:-


function GetData2(isAsync) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData2",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            var result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Second method dependent on first one :-

But when second method is dependent on result supplied from first method it will definitely have impact

$(function(){
// When second method depends on result of the first method & async=false
// If it is a synchronous call then you can get 
the result from first method before the second method call
    var result = GetData3(false); 
// As second method will be called after first method execution completed 
// so proper result can be found in above method
    GetData4(false, result);

// When second method depends on result of the first method & async=true
// If it is an asynchronous call then both the calls will 
happen asynchrously/simultaneously and 
    // you will not get the result from first method before call of 
second method as happens in below example
    var result = GetData3(true); 
// As both the methods will be called simultaneously second method will be called 
// before first method returning the result and here it will get NULL value in result.
    GetData4(true, result);
});

First Method:-

function GetData3(isAsync) {
    var result = null;
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData3",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
    return result;
}

Second Method : Takes an extra argument which is the result of first method.

function GetData4(isAsync, result) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData4",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            if (result.id == 1) {
                var result = JSON.parse(response.d);
                // do your operation here
            }
            else alert('No operation required..');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Note-

This will definitely of help to the developers who started working on jQuery Ajax method. There are many scenarios and requirements, we need to understand the fundamentals so that we can make right choice one at right place.

How to find second highest or maximum salary of Employee in SQL - Interview question

Introduction:
In this section we will write SQL query to get second highest salary of Employee. Before writing query its good to be familiar with schema as well as data in table. Here is the Employee table we will be using this SQL example:

SQL query to find second maximum salary of Employee

How to find second highest or maximum salary of Employee in SQL - Interview question
If you look data, you will find that second maximum salary in this case is 6000 and employee name is Henry. Now let’s see some SQL example to find out this second maximum salary.

Second maximum salary using sub query and IN clause:
Sub queries in SQL are great tool for this kind of scenario, here we first select maximum salary and then another maximum excluding result of subquery.
How to find second highest or maximum salary of Employee in SQL - Interview question
Here is another SQL query to find second highest salary using subquery and < operator instead of IN clause:
How to find second highest or maximum salary of Employee in SQL - Interview question
Both of above SQL example will work on all database including Oracle, MySQL, Sybase and SQL Server as they are written using standard SQL keywords. But sometime you can also use database specific features like TOP keyword of SQL Server or Sybase database to find out second highest salary of Employee.

Second highest salary using TOP keyword of Sybase or SQL Server database:
TOP keyword of Sybase and SQL Server database is used to select top record or row of any result set, by carefully using TOP keyword you can find out second maximum or Nth maximum salary as shown below.
How to find second highest or maximum salary of Employee in SQL - Interview question
Here is what this SQL query is doing : First find out top 2 salary from Employee  table and list them in descending order, Now second highest salary of employee is at top so just take that value. Though you need to keep in mind of using distinct keyword if there are more than one employee with top salary, because in that case same salary will be repeated and TOP 2 may list same salary twice.

Second maximum salary using LIMIT keyword of MYSQL database:
LIMIT keyword of MySQL database is little bit similar with TOP keyword of SQL Server database and allows to take only certain rows from result set. If you look at below SQL example, its very much similar to SQL Server TOP keyword example.
How to find second highest or maximum salary of Employee in SQL - Interview question
That’s on How to find second highest salary of Employee using SQL query.



Friday, December 4, 2015

Basic SQL Query that Frequently asked in Interview Questions

Introduction:
In this article, I am giving some examples of SQL queries which is frequently asked when you go for a programming interview, having one or two year experience on this field.

These queries test your SQL skill on Joins, both INNER and OUTER join, filtering records by using WHERE and HAVING clause, grouping records using GROUP BY clause, calculating sum, average and counting records using aggregate function like AVG(), SUM() and COUNT(), searching records using wildcards in LIKE operator, searching records in a bound using BETWEEN and IN clause, DATE and TIME queries etc. If you have faced any interesting SQL query or you have any problem and searching for the solution, you can post it here for everyone's benefit.

SQL Query Interview Questions and Answers

Question 1: SQL Query to find second highest salary of Employee
Answer: There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery:

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Emp

Question 2: SQL Query to find Max Salary from each department.
Answer: You can find the maximum salary for each department by grouping all records by DeptId and then using MAX() function to calculate maximum salary in each group or each department.

SELECT DeptID, MAX(Salary) FROM Employee  GROUP BY DeptID.

These questions become more interesting if Interviewer will ask you to print department name instead of department id, in that case, you need to join Employee table with Department using foreign key DeptID, make sure you do LEFT or RIGHT OUTER JOIN to include departments without any employee as well.  Here is the query

SELECT DeptName, MAX(Salary) FROM Employee e 
RIGHT JOIN Department d ON e.DeptId = d.DeptID GROUP BY DeptName;

In this query, we have used RIGHT OUTER JOIN because we need the name of the department from Department table which is on the right side of JOIN clause, even if there is no reference of dept_id on Employee table.

Question 3: Write SQL Query to display the current date.
Answer: SQL has built-in function called GetDate() which returns the current timestamp. This will work in Microsoft SQL Server, other vendors like Oracle and MySQL also has equivalent functions.

SELECT GetDate();

Question 4: Write an SQL Query to check whether date passed to Query is the date of given format or not.
Answer: SQL has IsDate() function which is used to check passed value is a date or not of specified format, it returns 1(true) or 0(false) accordingly. Remember ISDATE() is an MSSQL function and it may not work on Oracle, MySQL or any other database but there would be something similar.

SELECT  ISDATE('1/08/13') AS "MM/DD/YY"; 

It will return 0 because passed date is not in correct format. 

Question 5: Write an SQL Query to print the name of the distinct employee whose DOB is between 01/01/1960 to 31/12/1975.
Answer: This SQL query is tricky, but you can use BETWEEN clause to get all records whose date fall between two dates.

SELECT DISTINCT EmpName FROM Employees 
WHERE DOB  BETWEEN 01/01/1960 AND 31/12/1975;

Question 6: Write an SQL Query find number of employees according to gender  whose DOB is between 01/01/1960 to 31/12/1975.
Answer :

SELECT COUNT(*), sex from Employees  
WHERE  DOB BETWEEN '01/01/1960' AND '31/12/1975' GROUP BY sex;

Question 7: Write an SQL Query to find an employee whose Salary is equal or greater than 10000.
Answer :

SELECT EmpName FROM  Employees WHERE  Salary>=10000;

Question 8: Write an SQL Query to find name of employee whose name Start with ‘M’
Answer :

SELECT * FROM Employees WHERE EmpName like 'M%';

Question 9: find all Employee records containing the word "Joe", regardless of whether it was stored as JOE, Joe, or joe.
Answer :

SELECT * from Employees  WHERE  UPPER(EmpName) like '%JOE%';

Question 10: Write an SQL Query to find  the year from date.
Answer:  Here is how you can find Year from a Date in SQL Server 2008

SELECT YEAR(GETDATE()) as "Year";





Wednesday, December 2, 2015

Is MVC a design pattern or an architectural pattern?

Is MVC a design pattern or an architectural pattern?
Introduction:
MVC which stands for Model-View-Controller describes a software pattern that you can use in interactive computer systems. To understand if it is a design pattern or an architectural pattern, let's look at what these two are:

Architectural pattern: Concerned with the subsystems of an application with their relationships and collaborations with each other.
Design pattern: Concerned with the (further small) components of a subsystem with their relationships and collaborations with each other.

MVC is a pattern that you can use in both ways (as architectural or design) and ample amounts of real world cases where the pattern is used in both these worlds can be found.

MVC as an architectural pattern
Here the core functionality and data of an application are abstracted as the model. You have one or more views and one or more controllers collectively representing the user interface. A view is responsible for displaying information to the user. A controller is responsible for accepting user inputs, interpret them to understand what should be done and act accordingly (for example update data or invoke a functionality of the model).

A real world example is the implementation of a web application that follows the MVC architectural pattern. Many such web application frameworks exists. The key is that an application is broken down into components (call them subsystems) by the MVC pattern.

MVC as an architectural pattern
MVC architectural of a web application

MVC as a design pattern
Consider the many UI widget libraries available out there where MVC is used as a design pattern to implement widgets. Take for example the JSlider class (in Java Swing library). A JSlider instance represents a slider widget where a user can move the knob of the slider to change its position. JSlider is implemented as follows:

MVC as a design pattern
MVC design pattern

Note that in Java Swing library the xxxUI classes capture both the view and controller aspects of a widget. It's slightly different from MVC and Swing creators call this “separable model architecture”. For the purpose of this discussion, just don't care about this difference.

Here the model (BoundedRangeModel) doesn't represent the core functionality or data of the application. It's limited to represent the data (state) of the slider widget (Models of complex widgets may implement some amount of model specific functionality.). SliderUI's view related code is responsible for painting the slider (the background, knob,...). SliderUI's controller is responsible for interpreting a mouse click-and-drag as a semantic event that represents a slider position change. Accordingly the controller related code goes about updating the model. And then the view goes about painting the knob at a different position.

The scope of the MVC pattern here is just limited to implementing a slider widget. Would you call it architectural? I would not since I cannot consider the slider a collection of subsystems of an application. With the frame or reference set to a typical application, you wouldn't even recognize it as a top level subsystem. It's more appropriate to consider it a low level subsystem or a component and hence the MVC manifests as a design pattern in this context (Read initial paragraphs - What is considered a design pattern?).

Confusion:
Why is that the Swing creators gave the name “separable model architecture” to their widget design pattern? Probably because what is considered architectural itself is a question that leads to multiple explanations.

One such explanation is that if something (a quality, design aspect,.. ) is found spread throughout a system, it's considered architectural. That's a different way to think about architecture which is not the same as what I mentioned at the beginning of this article (See the description of a architectural pattern). Probably that's one reason why Swing creators used “architecture” in their pattern since it's found throughout the Swing library.

Yet another reason that I can think of is that they just focused on the UI “system”.

Fair  enough. Let's not argue. We understand what is what. Based on the first given description, this widget design pattern cannot be considered an architectural pattern.

Conclusion:

MVC can either be used as an architectural pattern or a design pattern.

Thursday, August 27, 2015

Read and Parse JSON String using ParseJSON Method with jQuery

Read and Parse JSON String using ParseJSON Method with jQuery
Introduction:
This article explains how to read and Parse JSON string in jQuery using ParseJSON method in JavaScript, asp.net and get string value from JSON string in jQuery.

To implement this functionality we need to write the code like as shown below

HTML Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Read and Parse Data using ParseJSON method</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
var name = '';
var jsonstr = '[{"UserName":"Ashwani","UserID":"1"},{"UserName":"VepshTech","UserID":"2"}]';
var obj = $.parseJSON(jsonstr);
$.each(obj, function() {
name += this['UserName'] + "<br/>";
});
$('#divjson').html(name); ;
})
</script>
</head>
<body>
<div id="divjson">
</div>
</body>
</html>

In above code we used parseJSON method to read formatted JSON string

Output:

Read and Parse JSON String using ParseJSON Method with jQuery


Convert JSON String to JSON Object with JavaScript

Introduction:
This article explains
This article explains how to convert JSON string to JSON object in JavaScript. To convert JSON string to JSON object in JavaScript we need to write the code as shown below.




Code-

 var str = '[{"title":"Chennai","lat":12.897400},
{"title":"Hyderabad","lat":17.266700},{"title":"Bangalore","lat":12.897400}]';
var obj=JSON.parse(str);

By using above code we can convert JSON string to JSON object in JavaScript

jQuery Convert JSON Data to HTML Table using jQuery Row Append Properties

Introduction:
This article explains how to convert JSON data to html table using jQuery or convert JSON data into html table using jQuery or jQuery convert JSON data into html table or jQuery create html table using JSON data.

To convert JSON data to html table using jQuery we need to write the code like as shown below


HTML Code-

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>convert json data to html table using jquery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
var myList = [{ "Name": "Ashwani", "Education": "B.Tech", "Location": "Lucknow" },
{ "Name": "Vin", "Education": "BMSC", "Location": "Guntur" },
{ "Name": "Ash", "Education": "Msc", "Location": "Nagpur" },
{ "Name": "Tom", "Education": "MBBS", "Location": "Nagpur" },
{ "Name": "Jack", "Education": "B.Tech", "Location": "Kakinada" },
{ "Name": "Mack", "Education": "MD", "Location": "Vizag" },
{ "Name": "Anu", "Education": "B.Tech", "Location": "Delhi" }]
Bindhtmltable(myList);
})
function Bindhtmltable(list) {
var cols = addheadercols(list);
for (var i = 0; i < list.length; i++) {
var row = $('<tr/>');
for (var colIndex = 0; colIndex < cols.length; colIndex++) {
var cellValue = list[i][cols[colIndex]];
if (cellValue == null) { cellValue = ""; }
row.append($('<td/>').html(cellValue));
}
$("#htmltable").append(row);
}
}

function addheadercols(list) {
var colset = [];
var headerTr = $('<tr/>');
for (var i = 0; i < list.length; i++) {
var rows = list[i];
for (var key in rows) {
if ($.inArray(key, colset) == -1) {
colset.push(key);
headerTr.append($('<th/>').html(key));
}
}
}
$("#htmltable").append(headerTr);
return colset;
}
</script>
</head>
<body>
<form id="form1" >
<div>
<table id="htmltable" border="1" cellpadding="5" style="border-collapse: collapse;">
</table>
</div>
</form>
</body>
</html>

Output-
Check below table it’s build by using above JSON data