Showing posts with label Dynamic. Show all posts
Showing posts with label Dynamic. Show all posts

Monday, 11 August 2014

Difference between Object and Var and Dynamic type in C#

C# is rich in data type. It provides three types Object, Var and Dynamic to store data of any type. In this article, I am trying to explore the differences among these three.

Difference between Object, Var and Dynamic type

Object
1.       Object was introduced with C# 1.0
2.       It can store any kind of value, because object is the base class of all type in .NET framework.
3.       Compiler has little information about the type.
4.       Object type can be passed as method argument and method also can return object type.
5.       Need to cast object variable to original type to use it and performing desired operations.
6.       Cause the problem at run time if the stored value is not getting converted to underlying data type.
7.       Useful when we don’t have more information about the data type.

Var
1.       Var was introduced with C# 3.0
2.       It can store any type of value but It is mandatory to initialize var types at the time of declaration.
3.       It is type safe i.e. Compiler has all information about the stored value, so that it doesn't cause any issue at run-time.
4.       Var type cannot be passed as method argument and method cannot return object type. Var type work in the scope where it defined.
5.       No need to cast because compiler has all information to perform operations.
6.       Doesn't cause problem because compiler has all information about stored value.
7.       Useful when we don’t know actual type i.e. type is anonymous.

Dynamic
1.       Dynamic was introduced with C# 4.0
2.       It can store any type of the variable, similar to old VB language variable.
3.       It is not type safe i.e. Compiler doesn't have any information about the type of variable.
4.       Dynamic type can be passed as method argument and method also can return dynamic type.
5.       Casting is not required but you need to know the properties and methods related to stored type.
6.       Cause problem if the wrong properties or methods are accessed because all the information about stored value is get resolve only at run time.
7.                  7           Useful when we need to code using reflection or dynamic languages or with the COM objects, because             you need to write less code.

Sunday, 14 July 2013

Dynamic column genrate jqgrid in asp.net mvc razor

how to create dynamic jqgrid in asp.net mvc razor

How to make Dynamic jqgrid in asp.net mvc Razor

to create dynamic jqgrid  Dynamically

Step1: create Dyanmic column model from service and return as Json

example    

        DataTable dcm = new DataTable("colModel");

            dcm.Columns.Add("name");
            dcm.Columns.Add("index");
               for (int i = 0; i < mdt.Rows.Count; i++)
                    {
                        DataRow DR = dcm.NewRow();
                        DR[0] = mdt.Rows[i][0].ToString();
                        DR[1] = mdt.Rows[i][0].ToString();
                        dcm.Rows.Add(DR);
                    }
then conver dcm to json format

Step2:Create Jqgrid dynamic strucure using Ajax call

Example:

  <div id="did" style="width:100%"  align="center">
    <table id="empsummary" width="100%" border="0" cellspacing="0" cellpadding="0">
    </table>
    <div id="pager"></div>
    </div>
<script type="text/javascript" id="getdata">
//creating the dyanamic colmodel
   $("#empsummary").jqGrid('GridUnload');
        $.ajax(
    {
        type: "POST",
        url: '@Url.Action("gdata")',
        data: { tid: data },
        dataType: "json",
        success: function (result) {
            var obj = jQuery.parseJSON(result);
            colM = obj.DocumentElement.colModel;
            jQuery("#empsummary").jqGrid({
                colModel: colM,
//                width: 100%,
                caption: "EMPLOYEE SUMMARY",
                pager: jQuery('#pager'),
                rowNum: 3,
                rowList: [5, 10, 20, 50],
                viewrecords: true,
                gridComplete: function () {
                },
                loadComplete: function (data) { }
            })
        },
        error: function (x, e) {
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
setTimeout(function () { $("#empsummary").jqGrid('setGridParam', { datatype: 'json' }); }, 500);

//binding the data to  dyanamic colmodel
        $.ajax({
            url: '@Url.Action("empsummarygrid")',
            type: "POST",
            datatype: "json",
            data: { tid: data },
            async: false,
            success: function (response) {
                $('#empsummary').jqGrid('clearGridData');
                var obj = jQuery.parseJSON(response);
                var obs1 = obj.DocumentElement.et;
                var tcount = obj.DocumentElement.et.length;
                if (tcount > 0) {
                    for (var i = 0; i < obj.DocumentElement.et.length; i++) {
                        jQuery("#empsummary").jqGrid('addRowData', i + 1, obs1[i]);
                    }
                }
                else {
                    var obs11 = obj.DocumentElement.et[0];
                    jQuery("#empsummary").jqGrid('addRowData', i + 1, obs1);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Your Request is Failed at this time Please Try after some time");
            }
        });
</script>


FullCode:

 <div id="did" style="width:100%"  align="center">
    <table id="empsummary" width="100%" border="0" cellspacing="0" cellpadding="0">
    </table>
<div id="pager">
</div>
</div>
<script type="text/javascript" id="getdata">
//creating the dyanamic colmodel
   $("#empsummary").jqGrid('GridUnload');

        $.ajax(
    {
        type: "POST",
        url: '@Url.Action("gdata")',
        data: { tid: data },
        dataType: "json",
        success: function (result) {

            var obj = jQuery.parseJSON(result);
            colM = obj.DocumentElement.colModel;


            jQuery("#empsummary").jqGrid({
                colModel: colM,
//                width: 100%,
                caption: "EMPLOYEE SUMMARY",
                pager: jQuery('#pager'),
                rowNum: 3,
                rowList: [5, 10, 20, 50],
                viewrecords: true,
                gridComplete: function () {




                },
                loadComplete: function (data) { }

            })
        },
        error: function (x, e) {
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });

        setTimeout(function () { $("#empsummary").jqGrid('setGridParam', { datatype: 'json' }); }, 500);

//binding the data to  dyanamic colmodel


        $.ajax({

            url: '@Url.Action("empsummarygrid")',
            type: "POST",
            datatype: "json",
            data: { tid: data },

            async: false,
            success: function (response) {

                $('#empsummary').jqGrid('clearGridData');
                var obj = jQuery.parseJSON(response);

                var obs1 = obj.DocumentElement.et;


                var tcount = obj.DocumentElement.et.length;

                if (tcount > 0) {


                    for (var i = 0; i < obj.DocumentElement.et.length; i++) {

                        jQuery("#empsummary").jqGrid('addRowData', i + 1, obs1[i]);

                    }

                }
                else {
                    var obs11 = obj.DocumentElement.et[0];
                    jQuery("#empsummary").jqGrid('addRowData', i + 1, obs1);

                }

            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Your Request is Failed at this time Please Try after some time");
            }
        });


</script>
       



 

Friday, 28 June 2013

DYNAMIC PIVOT Table in Sql server

This is fine only when you know how many columns you need. But when columns vary according to the query then how could you apply them on your scripts. The only way is to store them in a string variable at runtime and apply them in a dynamic SQL query, shown below.


USE [tempdb]
GO
 
-- Create test tables
create table table1 (number int, desc varchar(20),
location int, numberatlocation int)
create table table2 (code int, name varchar(20))
 
-- Insert test data
insert into table1 values (12345,'test',1000,5)
insert into table1 values (12345,'test',1001,2)
insert into table1 values (12345,'test',1002,4)
insert into table1 values (12345,'test',1003,9)
insert into table1 values (12345,'test',1004,7)
 
insert into table2 values (1000,'loc1')
insert into table2 values (1001,'loc2')
insert into table2 values (1002,'loc3')
insert into table2 values (1003,'loc4')
insert into table2 values (1004,'loc5')
 
-- Static PIVOT
select number, description, [loc1], [loc2], [loc3], [loc4], [loc5]
from (select number, desc, numberatlocation, name
from table1 join table2 on table1.location=table2.code)p
PIVOT(MAX (numberatlocation) FOR Name IN ( [loc1], [loc2], [loc3], [loc4], [loc5] )
) AS pvt
ORDER BY number
 
 
Output of Static query:
number desc loc1 loc2 loc3 loc4 loc5
12345 test    5       2       4       9       7
 
-- Dynamic PIVOT
 
-- Lets add one more record on both the tables to check the results
insert into table1 values (12345,'test',1005,3)
insert into table2 values (1005,'loc6')
 
declare @col varchar(1000)
declare @sql varchar(2000)
 
select @col = COALESCE(@col + ', ','') + QUOTENAME(name)
from table2
 
select @col -- This gives: [loc1], [loc2], [loc3], [loc4], [loc5], [loc6]
 
-- Now setting this @col variable in the Dynamic SQL.
set @sql = '
select number, desc, ' + @col + '
from (select number, desc, numberatlocation, name
from table1 join table2 on table1.location=table2.code)p
PIVOT(MAX (numberatlocation) FOR Name IN ( ' + @col + ' )
) AS pvt
ORDER BY number'
 
print @sql
 
exec (@sql)
 
Output of Dynamic query:
number desc loc1 loc2 loc3 loc4 loc5    loc6
12345 test    5       2       4       9       7       3
 
 
-- Final Cleanup
drop table table1
drop table table2