C# : Convert model class from database table using stored procedure

declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '

print @Result

Convert DataTable to List in c#

DataTable dt = ‘…some service called to fill this datatable….’
List<DemoModel> demoDetails = new List<DemoModel>();
demoDetails = ConvertDataTable<DemoModel>(dt);


public static List<T> ConvertDataTable<T>(DataTable dt)
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
T item = GetItem<T>(row);
return data;


private static T GetItem<T>(DataRow dr)
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();

foreach (DataColumn column in dr.Table.Columns)
foreach (PropertyInfo pro in temp.GetProperties())
if (pro.Name == column.ColumnName)
pro.SetValue(obj, dr[column.ColumnName], null);
return obj;

get id of closest ‘ul’ or parent id and get value of ‘href’ attribute with Jquery


//if menu is created dynamically it is very useful
<ul id="slider" style="display: none;">
 <li class="panel cloned">test1</li>
 <li class="panel">
   <h1><a href="/Admin/RoleMaster"> Role Creation </a> </h1>
 <li class="panel cloned">test2</li>


var url = window.location.pathname; //or window.location.toString();

$('#slider li.panel h1 a').each(function(){
   var myHref= $(this).attr('href');
   if( url == myHref) //compare current url with url value

        var ulId = $(this).closest('ul').attr('id'); //get id of ul tag 
        $("#"+ulId).css("display", "block");

asp net mvc : why is html checkbox generating an additional hidden input

I noticed strange behaviour whilst coding and ASP.NET MVC CheckBox Html Helper. I noticed that the field which was in part of a GET form was creating the query string with the same field in it twice. When the box was checked one parameter was true and the other was false.

Say I have a boolean field, MyField, that I am creating a checkbox for. I would write this: @Html.CheckBoxFor("MyField"). You would expect this to output a single check box but if you actually look at the HTML that is generated you will notice that is also creates a hidden field.

<input id="MyField" name="MyField" type="checkbox" value="true">
<input name="MyField" type="hidden" value="false">



Simple solution really. Write the HTML you want in HTML, forget about the HtmlHelper:

<input type="checkbox" name="MyField" value="true" id="MyField"
@Html.Raw((Model.MyField) ? "checked=\"checked\"" : "") />

Remember the value="true" because the default value to be sent is “on” if it is checked, which obviously can’t be parsed to a Boolean.

Obviously, this doesn’t look that clean but I will continue to do this on forms that use the GET method.

failed to serialize the response in Web API

Open Global.asax file and add two lines given below in bold characters. Result will always be in json format.

namespace WebApiExample
public class WebApiApplication : System.Web.HttpApplication
protected void Application_Start()


//Add following lines in global.asax file
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;


Understanding Filters in MVC

The Different Types of Filters

The ASP.NET MVC framework supports four different types of filters:

  1. Authorization filters – Implements the IAuthorizationFilter attribute.
  2. Action filters – Implements the IActionFilter attribute.
  3. Result filters – Implements the IResultFilter attribute.
  4. Exception filters – Implements the IExceptionFilter attribute.

Filters are executed in the order listed above. For example, authorization filters are always executed before action filters and exception filters are always executed after every other type of filter.

Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.

Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns.

Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.

Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.

For more details please click on below link


Introduction to MVC4 asp.net

‘Hello World’ Web Application in MVC

This is basic approach for making you understand the structure and how MVC works.


1) Open Visual Studio 2012

2) Select File–>New–>Project

3) A popup will be open, where you can see the list of all available templates for Windows and Web application. Select the Web application from the left hand side and also select the Template from the right hand side of the popup i.e. “ASP.NET MVC 4 Web Application”. Here you also provide the Proper application name and also select the folder where you save the application.

4) Select the “Ok” button, then after again a Popup will be open where you have to select the proper template for the application. Here in this case “Empty” Template is selected from the “Project Template”.

5) Now Right click on the “Controller” folder and then select Add——->Controller. A popup will be open where you give the appropriate name with suffix as a controller and click the add button. HelloWorldController class is opened.

6) Right click on the “Index” function in the “HelloWorldController” and select the “Add View…” option and click the “Add” button.

7) “Index.cshtml” file is created inside the “HelloWorld” folder which is inside the “Views” folder.

8) Now Open the “Global.asax.cs” file and change the following code snipet .

                                                name: "Default",
                                                url: "{controller}/{action}/{id}",
                                                defaults: new { controller = "HelloWorld", action = "Index", id = UrlParameter.Optional }

9) Run the application by pressing the F5 key.