Tuesday, August 4, 2020

Enable local SQL Server with localhost

On windows,
  1. Start --> Run
  2. Then type "c:\windows\sysWOW64\SQLServerManager12.msc" and press enter. (The Sql Server Manager version may vary. Hence, replace "12" with whatever version installed in your machine)
  3. In the SQL Server Configuration Manager window,  go into "SQL Server Network Configuration" and double click TCP/IP. Click the "IP Addresses" tab and scroll to the bottom. Under "IP All" remove TCP Dynamic Ports if it is present and set TCP Port to 1433. Click OK 
  4. Then go back to "SQL Server Services" and restart SQL Server instance. Now you can connect via localhost
    enter image description here


Thursday, July 14, 2016

Encrypt / Decrypt data at db context

Override savechanges method and object materialized methods to automatically encrypt/decrypt data without manually doing it.
Here, the custom attribute [Encrypted] is used to mark a property as encrypted or secured data.
Use your way of security for encryption and decryption.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

public class BaseDbContext : DbContext
    {
        public BaseDbContext() : base("mydbcontext")
        {
            ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += new ObjectMaterializedEventHandler(ObjectMaterialized);
        }

        public override int SaveChanges()
        {
            var contextAdapter = ((IObjectContextAdapter)this);

            contextAdapter.ObjectContext.DetectChanges();

            var pendingEntities = contextAdapter.ObjectContext.ObjectStateManager
                .GetObjectStateEntries(EntityState.Added | EntityState.Modified)
                .Where(en => !en.IsRelationship).ToList();

            foreach (var entry in pendingEntities) //Encrypt all pending changes
                EncryptEntity(entry.Entity);

            int result = base.SaveChanges();

            foreach (var entry in pendingEntities) //Decrypt updated entities for continued use
                DecryptEntity(entry.Entity);

            return result;
        }

        void ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
        {
            DecryptEntity(e.Entity);
        }

        private void EncryptEntity(object entity)
        {
            //Get all the properties that are encryptable and encrypt them
            var encryptedProperties = entity.GetType().GetProperties()
                .Where(p => p.GetCustomAttributes(typeof(Encrypted), true).Any(a => p.PropertyType == typeof(String)));
            foreach (var property in encryptedProperties)
            {
                string value = property.GetValue(entity) as string;
                if (!String.IsNullOrEmpty(value))
                {
                    property.SetValue(entity, SimpleEncrypt(value));
                }
            }
        }

        private void DecryptEntity(object entity)
        {
            //Get all the properties that are encryptable and decyrpt them
            var encryptedProperties = entity.GetType().GetProperties()
                .Where(p => p.GetCustomAttributes(typeof(Encrypted), true).Any(a => p.PropertyType == typeof(String)));

            foreach (var property in encryptedProperties)
            {
                string encryptedValue = property.GetValue(entity) as string;
                if (!String.IsNullOrEmpty(encryptedValue))
                {
                    Entry(entity).Property(property.Name).OriginalValue = SimpleDecrypt(encryptedValue);
                    Entry(entity).Property(property.Name).IsModified = false;
                }
            }
        }

        public string SimpleEncrypt(string value)
        {
            // your encryption logic
            return value;
        }

        public string SimpleDecrypt(string value)
        {
            // your decryption logic
            return value;

        }
    }

    public class Encrypted : Attribute { }

Enable simple Token based authorization in Web API

Set /token endpoint for request token

using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Web;
using System.Web.Http;
using MyApp.Providers;

[assembly: OwinStartup(typeof(MyApp.Startup))]
namespace MyApp
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Allow cross domain access
            app.UseCors(CorsOptions.AllowAll);

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new MyAuthServerProvider(),
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            // Important: Enable Suppress redirect to login page if token is invalid
            app.Use((context, next) =>
            {
                HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;
                return next.Invoke();
            });

            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }
    }
}

Define MyAuthServerProvider()

using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Security.Claims;
using MyApp.Models;
using Newtonsoft.Json.Linq;

namespace MyApp.Providers
{
    public class MyAuthServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // validate username by username/password using your custom logic
            bool isValid = ValidateUser(context.UserNamecontext.Password);

            if (isValid)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName)); 
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));

            context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            
        }
    }
}

Tuesday, April 26, 2016

Prevent Redirect to Login page for Unauthorized Calls to Web API

If you have implemented token based authorization to your Web API which resides in an ASP.NET MVC application, you would probably come across this situation. Because, you have login page to MVC application which will be shown if you are not logged in. In case of Web API calls, you are obviously not logged in, but credentials or access token is passed in the request header.

Just include the following code fragment in the startup class just before the app.UseWebApi(config); line, to prevent this redirect for unauthorized Web API calls such the access token is not provided or got expired.

            // Important: Enable Suppress redirect to login page if token is invalid
            app.Use((context, next) =>
            {
                HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;
                return next.Invoke();
            });

            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);

System.Web.Http.Authorize vs System.Web.Mvc.Authorize

You must use System.Web.Http.Authorize against an ApiController (Web API controller) and System.Web.Mvc.Authorize against a Controller (MVC controller).

Thanks to: Badri
Source: http://stackoverflow.com/a/19156530/1931848

Friday, April 22, 2016

Bug in MySql .NET Connector 6.9.8: Nested transactions are not supported

There is bug in MySQL connector for .NET version 6.9.8, that it will throw an error: “Nested transactions are not supported”


You have likely run into this bug in MySQL Connector/NET.
What triggers this bug:
  1. Code calls for execution of query A
  2. Transaction 1 for query A is started
  3. Query A is executed and causes an error in MySQL
  4. Transaction 1 is NOT rolled back
  5. Code calls for execution of query B
  6. Transaction 2 for query B is started
  7. MySQL Connector/NET throws the exception
The bug is point 4: transaction 1 is left open after an error (or at least the connector is still convinced it's left open). Because of connection pooling, the code calling for query A and query B can be completely unrelated. Also, if the time between point 4 and 5 is long enough, the transaction is rolled back, hence the rareness and randomness.
Unfortunately there's no fix by MySQL yet. The only workaround that I know of is downloading the source code of Connector/NET and fixing/building it yourself.
Otherwise, stick to the older stable version 6.8.7
Thanks: AronVanAmmers
Reference: http://stackoverflow.com/a/29265962/1931848

Tuesday, April 19, 2016

Single Sign On (SSO) with ASP.NET Web Application

If you want to have single sign in for multiple web applications, you have to share authentication data between.
You can achieve by using Forms Authentication with Same Machine key in all applications.
Machines keys are used to encrypt and decrypt cookies. Therefore, you have to set same machine key deliberately on each application's web.config to ensure single sign on works as expected.

Machine key contains 3 elements namely, validationkey, decryptionkey and validation (algorithm, eg. SHA1).

References:
http://www.developer-corner.com/blog/2006/10/01/aspnet-single-sign-on/
http://www.dotnetfunda.com/articles/show/979/aspnet-authentication-and-authorization
http://www.codeproject.com/Articles/6586/Single-sign-on-across-multiple-applications-in-ASP

Tuesday, April 12, 2016

sql_mode "only_full_group_by" in MySql

If you are getting one of the following errors, you have this problem;

  1. Error Code: 1055. 'test.somefield' isn't in GROUP BY
  2. SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.somefield' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Check the current sql_mode in your mysql server with the following command to see if the only_full_group_by is enabled;

SELECT @@sql_mode;

This will give a list of sql_modes enabled in the server. Example as follows,

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

As you can see from the above result, you have a value called "only_full_group_by". That means if you have a group by clause in your sql statement, only the fields which are listed in a group by clause can be used in the select clause or order by clause, unless you aggregate the fields. i.e, using aggregate functions such as min(), max() etc

NOTE: As of MySQL Server version 5.7.5, the only_full_group_by is enabled in the sql_mode by default.

Temporary Fix:
Temporarily you can fix this issue by disabling this check in the server by globally and/or only in the active session by issuing the following command respectively.

SET GLOBAL sql_mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";

SET SESSION sql_mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";

Permanent Fix:
- Make sure nonagregated field list in select or order by clause are in group by
- Restructure the sql statement

Thursday, December 17, 2015

ASP.NET MVC Controller Lifecycle

ASP.NET MVC Controller will be executed in the following  order:

Every controller action call go through the certain events events. Some of the methods I have listed below.

1) Initialize
Executed at the beginning of action call.

protected override void Initialize(RequestContext requestContext)
{
}

2) On Authorization
Executed at the time of authorizing the action call

protected override void OnAuthorization(AuthorizationContext filterContext)
{
}

1) On Action Executing
Executed at the time of executing the action just after authorization.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
}

MySql prepare historic data for reporting purpose

-- Prepare a table for days to get sequence of numbers from 1 to 32

CREATE TABLE ids (
id INT UNSIGNED AUTO_INCREMENT NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM;

INSERT INTO ids SET id = 1;           #      1      1
INSERT INTO ids SELECT NULL FROM ids; #      2      2
INSERT INTO ids SELECT NULL FROM ids; #      4      4
INSERT INTO ids SELECT NULL FROM ids; #      8      8
INSERT INTO ids SELECT NULL FROM ids; #     10     16
INSERT INTO ids SELECT NULL FROM ids; #     20     32


set @enddate = "2015-12-01";
set @days = 15;

SELECT date(qb.date) as date, COALESCE(sum(net_amount), 0) as total from invoice qa
right join
(SELECT
(SELECT @enddate FROM invoice qc LIMIT 1) + INTERVAL 1 DAY - INTERVAL a.id DAY AS date
FROM test.ids a
    ) as qb
on date(qa.date) = qb.date
where qb.date > DATE_SUB(@enddate, INTERVAL @days day)
group by qb.date
order by qb.date asc;

Wednesday, October 7, 2015

Concrete, Abstract, Virtual and Sealed

Concrete class;
  1. Standard class that we write our methods
  2. Cannot contain abstract methods
  3. Can be used as base class or child class
  4. Can create object and call methods
Abstract class;
  1. It is declared with the keyword abstract
  2. Must be used only as a base class. i.e, cannot create object like concrete class
  3. Cannot create instance of class.
  4. Can contain abstract methods as well as concrete (standard) methods
Abstract method;
  1. An abstract member cannot provide any implementation. It is only a method definition.
  2. You must implement (override) using the keyword override in your child class with your own functionality when you derive the class that contains this method.
  3. An abstract member is implicitly virtual.
  4. Can only reside inside an abstract class
Virtual method; 
  1. A method which does something.
  2. You may either override with your own functionality or not. It is not a must to override.
  3. It is recommended to use the keyword override when doing so. Because, it will work without the override keyword also.
Sealed class;
  1. Is used to restrict a class from being inherited.
Sealed method;
  1. You can only make a method sealed for an overridden method.
  2. You seal a method to prevent making any changes to it in the derived classes.

Wednesday, August 26, 2015

Remove "NVRAM WARNING: ERR 0x10" from WIFI List

Many MTK device's users are facing the WiFi NVRAM WARNING err 0x10 Problem by formatting the whole flash by SP Flash Tool.

Following is an easy method I have found from Internet.

Required
1. A Rooted MTK device 
2. Root Explorer or Root Browser (download from Play Store)
3. Wifi Error Fix.rar (find the download link at the bottom)

Steps
1. Make sure you switch off the WIFI

2. On your rooted device go to the following location using a root explorer mentioned above
data/nvram/APCFG/APRDEB

3. Delete the following files from the above location
WIFI
WIFI_CUSTOM

4. Now extract the files from the WiFi fix.rar and copy / move them to the above location (data/nvram/APCFG/APRDEB)

5. Reboot the device and switch on the WIFI. That's it, it's gone.

I tested this on Lenovo a3000

Update: Broken link for download updated. Many people have requested permission. Sorry for the inconvenience.

Download

Tuesday, August 25, 2015

Restore lost IMEI on Android Phone

1. Use imei.exe via cmd. Download link found at the end of this post.
Code:
imei imei_sim1 imei_sim2
a) make sure you replace the imei_sim1 and imei_sim2 to your imei
b) skip imei_sim2 if your phone is not dual sim

A file with the name "MP0B_001_NEW" created in the working folder

2. Rename it to "MP0B_001" and copy it to /data/nvram/md/NVRAM/NVD_IMEI folder of your Android phone
3. Then chown and chmod as shown below.
a) via adb
Code:
adb.exe shell "su -c 'chmod 660 /data/nvram/md/NVRAM/NVD_IMEI/MP0B_001'"
adb.exe shell "su -c 'chown nvram.nvram /data/nvram/md/NVRAM/NVD_IMEI/MP0B_001'"
OR
b) via terminal
Code:
su
chmod 660 /data/nvram/md/NVRAM/NVD_IMEI/MP0B_001
chown nvram.nvram /data/nvram/md/NVRAM/NVD_IMEI/MP0B_001
4. Restart the phone and check your IMEI via *#06#.
Enjoy!!!

Download

Wednesday, August 12, 2015

HTTP Error 500.19 - Internal Server Error

Have you ever get an error as follows;

HTTP Error 500.19 - Internal Server Error 
The requested page cannot be accessed because the related configuration data for the page is invalid. 
Error Code: 0x8007000d
Config Source:
-1:
0:


Solution:
Install URL Rewrite 2.0 via Web Platform installer

Sunday, May 17, 2015

Thursday, May 14, 2015

Prevent automatic hyperlinks in Email notifications in your code

Sometimes you want to send an email notification from your web application or any system that has a website address to be displayed as plain text when you view it on an email client such as Outlook, G-mail, etc. But nowadays, the email clients are so intelligent that even if you send a website address, email address, etc as plain text, they will be converted to links.

Therefore, in order to avoid email clients automatically making hyperlinks, you have to change the pattern but display the same.

I came across some findings to include a white-space character in the link text but not displayed to the user using the html code ​ to include white-space as follows.

www.google.com has to be written as www.google.&#8203com so that the email client will not identify this as a link, still there will not be difference when displaying it.

<p>Check out at www.google.&#8203com</p>

will be displayed as;
Check out at www.google.​com

Define Display Labels as attributes in BE class in C#

Assume that in your BE class you have certain properties to match with table fields. I want to expose descriptive name for each of these properties. for example to show it as column header in grid.
For example, there is a property called FirstName. I want to expose it's descriptive name as First Name
in BE define this.
[DisplayName("First Name"), Description("First Name of the Member")]
public string FirstName
{
    get { return _firstName; }
    set { _firstName = value; }
}
You can read these details of each property as below;
PropertyDescriptorCollection propertiesCol = TypeDescriptor.GetProperties(objectBE);

PropertyDescriptor property;

for (int i = 0; i < propertiesCol.Count; i++)
{
    property = TypeDescriptor.GetProperties(objectBE)[i];

    /*
    // Access the Property Name, Display Name and Description as follows
    property.Name          // Returns "FirstName"
    property.DisplayName   // Returns "First Name"
    property.Description   // Returns "First Name of the Member"
    */
}
* where objectBE is the object instance of BE class.

WCF GET URL Length Limit Issue: Bad Request - Invalid URL

I tried to access a WCF Service through jQuery AJAX call with GET method. So, sometimes the URL is lengthy with parameters.
When the parameters becomes so lengthy, jQuery AJAX Call fails, and returns nothing. So I put a break point and took the URL out to test. When I try the same URL in the browser (I tried FireFox and Chrome), it returns the following when the URL length is too long.
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid.
I checked the length limitation as well. When the number of characters in the URL (in encoded format) exceeds 1011 characters (including http://) only I get the error.
I tried POST method, but I don't know I could not make it work. Because it needs some web.config changes.
My Parameters are set of Json Objects. I don't think any of the characters cause the problem, because, if I just reduce few alpha numeric characters to less than the limit, it works.
I'm running my application in Visual Studio 2012 Premium in Windows 8 Professional, so it's .NET 4.5 and IIS Express Came with it.
Further Research
When I try to investigate this further, this is not the limitation I have already mentioned which is the length of full url. But, there is a limitation of length in each parameter which is 260 characters.
So, I'm not sure about URL total length, but each parameter (seperated by "/") has the limit. The problem with the above URL which I have posted is Email Address JSON parameter is 261 characters long, given below.
SOLUTION
I Found a solution which worked for me, when I research further on this.
There is an IIS Setting
The problem is because, the default character limit of each parameter in REST url is 260 which is defined in the registry.
So, you have to update the registry to increase this size limit where the IIS Server / IIS Express is running.
Following is the location of Registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters
And the value name is UrlSegmentMaxLength. If it is not there, create one with Type of REG_DWORD. And specify a higher value for value data such as 1000 in hexadecimal or 4096 in decimal.
This is a http.sys setting. More about http.sys settings : http://support.microsoft.com/kb/820129
Make sure, you restart the server/machine to apply the registry changes. And that's it.

Basic Auditing in MySQL

Introduction

Keeping track of a record about the time it was created and the time it was last updated, may be important when you want that information.
This document explains how to implement this in any of the given table.

Implementation

There are two ways of implementing this in the database table. First method is to use ALTER TABLE and TRIGGER. The other method is to define in the ALTER TABLE itself. The second method will only work in MySQL 5.6.5 and later versions.
Before following the steps below, make sure you are selected the correct database and make sure the column names you use for created time and modified time do not already exists in the table.

Method 1

ALTER TABLE tblname
ADD COLUMN modifiedtime TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
ADD COLUMN createdtime DATETIME;

DELIMITER //
DROP TRIGGER IF EXISTS tblname_insert_trigger//
CREATE TRIGGER tblname_insert_trigger
BEFORE INSERT ON tblname
FOR EACH ROW
BEGIN
IF NEW.CreatedTime = '0000-00-00 00:00:00' THEN
SET NEW.CreatedTime = NOW();
END IF;
END;//
DELIMITER ;

Method 2

This method will only work in MySQL 5.6.5 and later versions.
ALTER TABLE tblname
ADD COLUMN modifiedtime TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
ADD COLUMN createdtime DATETIME NULL DEFAULT CURRENT_TIMESTAMP;

Update Existing Records

If you want to keep existing records’ audit fields as null to differentiate that those records were created and modified before implementing audit fields, execute the following statements just after the above steps.
SET SQL_SAFE_UPDATES = 0;  -- bypass the workbench safe mode, if you need
UPDATE tblname SET modifiedtime = null, createdtime = null;

References

1.       Automatic Create and Modified timestamps in MySQL
https://www.marcus-povey.co.uk/2013/03/11/automatic-create-and-modified-timestamps-in-mysql
2.       Having both a Created and Last Updated timestamp columns in MySQL 4.0
http://stackoverflow.com/a/267675/1931848

Wednesday, May 13, 2015

jQuery Datatables server-side pagination in ASP.NET MVC with Entity Framework

In order to capture datatable events we need to create a class as follows;

   /// <summary>  
   /// Class that encapsulates most common parameters sent by DataTables plugin  
   /// </summary>  
   public class jQueryDataTableParams  
   {  
     /// <summary>  
     /// Request sequence number sent by DataTable,  
     /// same value must be returned in response  
     /// </summary>      
     public string sEcho { get; set; }  
     /// <summary>  
     /// Text used for filtering  
     /// </summary>  
     public string sSearch { get; set; }  
     /// <summary>  
     /// Number of records that should be shown in table  
     /// </summary>  
     public int iDisplayLength { get; set; }  
     /// <summary>  
     /// First record that should be shown(used for paging)  
     /// </summary>  
     public int iDisplayStart { get; set; }  
     /// <summary>  
     /// Number of columns in table  
     /// </summary>  
     public int iColumns { get; set; }  
     /// <summary>  
     /// Number of columns that are used in sorting  
     /// </summary>  
     public int iSortingCols { get; set; }  
     /// <summary>  
     /// Comma separated list of column names  
     /// </summary>  
     public string sColumns { get; set; }  

Following is the method to load data for datatable. Assuming that we are going to show firstname, lastname, company and jobtitle from member table.
 public ActionResult GetDataForDatatable(jQueryDataTableParams param)  
 {  
    IQueryable<Member> memberCol = myDbContext.Member  
                      .Select(m => m.FirstName,  
                          m.LastName,  
                          m.Company,  
                          m.JobTitle)  
                      .AsQueryable();  
    int totalCount = memberCol.Count();  
    IEnumerable<Member> filteredMembers = memberCol;  
    if (!string.IsNullOrEmpty(param.sSearch))  
    {  
      filteredMembers = memberCol  
              .Where(m => m.FirstName.Contains(param.sSearch) ||  
                 m.LastName.Contains(param.sSearch) ||  
                 m.Company.Contains(param.sSearch) ||  
                 m.JobTitle.Contains(param.sSearch));  
    }  
    var sortIdx = Convert.ToInt32(Request["iSortCol_0"]);  
    Func<Member,string> orderingFunction = (m => sortIdx == 0 ? m.FirstName :  
                         sortIdx == 1 ? m.LastName :  
                         sortIdx == 2 ? m.Company :  
                         m.JobTitle);  
    var sortDirection = Request["sSortDir_0"]; // asc or desc  
    if (sortDirection == "asc")  
      filteredMembers = filteredMembers.OrderBy(orderingFunction);  
    else  
      filteredMembers = filteredMembers.OrderByDescending(orderingFunction);  
    var displayedMembers = filteredMembers  
             .Skip(param.iDisplayStart)  
             .Take(param.iDisplayLength);  
    var result = from a in displayedMembers  
           select new[] { a.FirstName, a.LastName, a.Company,   
                  a.JobTitle, a.ID.ToString() };  
    return Json(new  
       {  
         sEcho = param.sEcho,  
         iTotalRecords = totalCount,  
         iTotalDisplayRecords = filteredMembers.Count(),  
         aaData = result  
       },  
       JsonRequestBehavior.AllowGet);  
 }  

Following is how we initialize our datatable and design the HTML.

-> Reference to jQuery js, jQuery Datatable js, jQuery Datatable css

 <table id="tblMember" class="table" style="width: 100%">  
   <thead>  
     <tr>  
       <th>First Name</th>  
       <th>Last Name</th>  
       <th>Company</th>  
       <th>Job Title</th>  
       <th>Actions</th>  
     </tr>  
   </thead>  
   <tbody>  
   </tbody>  
 </table>  
 <script>  
   $(document).ready(function () {  
     // destroy existing datatable before, initiating  
     if (oTable != undefined) {  
       oTable.fnDestroy();  
     };  
     oTable = $('#tblMember').dataTable({  
       "bServerSide": true,  
       "sAjaxSource": '@Url.Action("GetDataForDatatable","Member")',  
       "bProcessing": true,  
       "aoColumns": [  
               { "sName": "FirstName" },  
               { "sName": "LastName" },  
               { "sName": "Company" },  
               { "sName": "JobTitle" },  
               {  
                 "sName": "ID",  
                 "bSearchable": false,  
                 "bSortable": false,  
                 'mRender': function (data, type, row) {  
                   return '<a href="@Url.Action("Edit", "Member")/' + row[4] + '" class="btn btn-warning btn-xs" role="button">@labels.btn_edit</a>' + '&nbsp;' +  
                       '<button onclick="confirmDelete(' + row[4] + ');" class="btn btn-danger btn-xs">@labels.btn_delete</button>';  
                 }  
               },  
       ]  
     });  
   }  
 </script>