Tuesday, December 29, 2015

How to apply Claim Based Authorization Framework for ASP.NET 5


Note, if you added WebMatrix.WebData.dll into your project reference, then every time your code called ClaimsPrincipal.Claims, system displayed HttpException with the message Unable to connect to SQL Server database WebMatrix.WebData.dll contains classes used with the SimpleMembership API introduced by WebMatrix. SimpleMembership, which uses a database, is automatically enabled because the dll uses PreApplicationStart method to initialize itself. The result is that Thread.CurrentPrincipal yields a System.Web.Security.RolePrincipal instead of the ClaimsPrincipal associated with the user. 
The resolution is simple, remove the dll and everything should work fine.

Reference:
http://michiel.vanotegem.nl/2013/05/fix-claimsauthorizationmanager-checkaccess-throws-httpexception/
https://social.msdn.microsoft.com/Forums/vstudio/en-US/57944284-9ec8-4780-995c-b872f2aa9688/authorizationcontext-parameter-of-claimsauthorizationmanager-does-not-contain-claims-of?forum=Geneva
http://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Existing-ASPNET-MVC-Application#Resources
http://dotnetcodr.com/2013/02/11/introduction-to-claims-based-security-in-net4-5-with-c-part-1/
http://dotnetcodr.com/2013/02/14/introduction-to-claims-based-security-in-net4-5-with-c-part-2-the-new-inheritance-model/
http://dotnetcodr.com/2013/02/25/claims-based-authentication-in-mvc4-with-net4-5-c-part-1-claims-transformation/
http://dotnetcodr.com/2013/02/28/claims-based-authentication-in-mvc4-with-net4-5-c-part-2-storing-authentication-data-in-an-authentication-session/

Tuesday, December 15, 2015

ASP.Net 5 Identity and Authentication - Customize with Your Own User Tables

Microsoft has an excellent Identity class to handle user authentication. You can simply apply the security pattern and avoid complex page and business logic inside. ASP.Net 5 included the pattern within their new ASP.Net 5 project template. The only issue is for legacy system, we usually have our own user tables, and in most cases we don't want to give up them.  So customize Microsoft Identity pattern with our own user database would be very import and useful.

First off, we need to understand ASP.Net Core Identity.
IUser
A user object must implement the IUser interface, which requires to have at least an Id and a UserName. Note Id property has type string, which can handle GUIDs.
public interface IUser
{
   string Id { get; }
   string UserName { get; set; }
}
IUserStore
IUserStore defines the basic CRUD functionality for users. If you want to create local accounts with passwords, you need to implement IUserPasswordStore to save user and password. For third party logins (Twitter and Facebook, for example), add IUserLoginStore, and for claim storage there is an IUserClaimStore. Note IUserStore has a generic constraint.
public interface IUserStore<TUser> : IDisposable where TUser : IUser
{
   Task CreateAsync(TUser user);
   Task DeleteAsync(TUser user);
   Task<TUser> FindByIdAsync(string userId);
   Task<TUser> FindByNameAsync(string userName);
   Task UpdateAsync(TUser user);
}
IUserClaimStore & IUserRoleStore & IUserPasswordStore
Microsoft Identity supports Claims through interface IUserClaimStore.
public interface IUserClaimStore<TUser> 
   : IUserStore<TUser>, IDisposable where TUser : IUser
{
   Task AddClaimAsync(TUser user, Claim claim);
   Task<System.Collections.Generic.IList<Claim>> GetClaimsAsync(TUser user);
   Task RemoveClaimAsync(TUser user, Claim claim);
}
It seemed Microsoft still want to keep User Role along with User Claims. Both of them are optional.
public interface IUserRoleStore<TUser> 
   : IUserStore<TUser>, IDisposable where TUser : IUser
{
   Task AddToRoleAsync(TUser user, string role);
   Task<System.Collections.Generic.IList<string>> GetRolesAsync(TUser user);
   Task<bool> IsInRoleAsync(TUser user, string role);
   Task RemoveFromRoleAsync(TUser user, string role);
}
For user account, password are also optional. However, in most cases, you need to implement this interface as you want your users to use their passwords to login. In addition, you can use this to persist passwords (actually, hashed passwords).
public interface IUserPasswordStore<TUser> 
   : IUserStore<TUser>, IDisposable where TUser : IUser
{
   Task<string> GetPasswordHashAsync(TUser user);
   Task<bool> HasPasswordAsync(TUser user);
   Task SetPasswordHashAsync(TUser user, string passwordHash); 
}
UserManager & AccountController
The UserManager is a concrete class to handle identity and membership business logic, such as hash a password, validate a user, and manage claims.


UserManager has a number of properties you can use. For example,  a custom UserValidator (any object implementing IIdentityValidator), a custom PasswordValidator, and a custom
PasswordHasher.

You can pass any object which implementing IUserStore via the UserManager constructor. You use UserManager to manage user information stored in SQL Server, a document database, or other forms of storage.

UserManager will be created within AccountController by passing in a new UserStore, which implements IUserPasswordStore in addition to the other core identity interfaces for persisting claims, roles, and 3rd party logins.

Note The WebAPI and Single Page Application project templates also support user registration and password logins, but in these templates the AccountController is an API controller that issues authentication tokens instead of authentication cookies.




public class UserManager<TUser> : IDisposable where TUser : IUser
{
   public UserManager(IUserStore<TUser> store);
   public ClaimsIdentityFactory<TUser> ClaimsIdentityFactory { get; set; }
   public IPasswordHasher PasswordHasher { get; set; }
   public IIdentityValidator<string> PasswordValidator { get; set; }
   protected IUserStore<TUser> Store { get; }
   public virtual bool SupportsUserClaim { get; }
   public virtual bool SupportsUserLogin { get; }
   public virtual bool SupportsUserPassword { get; }
   public virtual bool SupportsUserRole { get; }
   public virtual bool SupportsUserSecurityStamp { get; }
   public IIdentityValidator<TUser> UserValidator { get; set; }
 
   public virtual Task<IdentityResult> AddClaimAsync(string userId, Claim claim);4
   public virtual Task<IdentityResult> AddLoginAsync(string userId, UserLoginInfo login);
   public virtual Task<IdentityResult> AddPasswordAsync(string userId, string password);
   public virtual Task<IdentityResult> AddToRoleAsync(string userId, string role);
   public virtual Task<IdentityResult> ChangePasswordAsync(string userId, string currentPassword, string newPassword);
   public virtual Task<IdentityResult> CreateAsync(TUser user);
   public virtual Task<IdentityResult> CreateAsync(TUser user, string password);
   public virtual Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType);
   public virtual Task<TUser> FindAsync(UserLoginInfo login);
   public virtual Task<TUser> FindAsync(string userName, string password);
   public virtual Task<TUser> FindByIdAsync(string userId);
   public virtual Task<TUser> FindByNameAsync(string userName);
   public virtual Task<Collections.Generic.IList<Claim>> GetClaimsAsync(string userId);
   public virtual Task<Collections.Generic.IList<UserLoginInfo>> GetLoginsAsync(string userId);
   public virtual Task<Collections.Generic.IList<string>> GetRolesAsync(string userId);
   public virtual Task<bool> HasPasswordAsync(string userId);
   public virtual Task<bool> IsInRoleAsync(string userId, string role);
   public virtual Task<IdentityResult> RemoveClaimAsync(string userId, Claim claim);
   public virtual Task<IdentityResult> RemoveFromRoleAsync(string userId, string role);
   public virtual Task<IdentityResult> RemoveLoginAsync(string userId, UserLoginInfo login);
   public virtual Task<IdentityResult> RemovePasswordAsync(string userId);
   public virtual Task<IdentityResult> UpdateAsync(TUser user);
   public virtual Task<IdentityResult> UpdateSecurityStampAsync(string userId);
}
Creating UserManager in AccountController:
new UserManager<ApplicationUser>(
    new UserStore<ApplicationUser>(new ApplicationDbContext()))
ApplicationDbContext & IdentityDbContext
UserStore has a dependency on an Entity Framework class named ApplicationDbContext which derives from IdentityDbContext
ApplicationDbContext provides all of the Entity Framework code-first mapping.  If we want to use our own user tables, we need to change ApplicationDBContext or use our own to replace it.
By default, IdentityDbContext uses a connection string named “DefaultConnection”, and all the new project templates will include a DefaultConnection connection string in the project’s web.config file. The connection string points to a SQL Local DB database in the AppData folder.

To change the SQL Server database being used, you can change the value of the connection string in web.config. You can also pass a different connection string name into the DB context constructor.

ApplicationUser & UserStore
The ApplicationUser and UserStore are class implemented IUser and IUserStore using Entity Framework 6.  ApplicationUser includes Id, Username, PasswordHash, and other properties it inherits from IdentityUser.
public class ApplicationUser : IdentityUser {
}
 
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
    public ApplicationDbContext() : base("DefaultConnection") {
    }
}
Customize Microsoft Identity Framework
Then we can start to implement our own User class, and it should extends IUser interface. Actually we can mimic ApplicationUser class. Under Entity Framework, the User class would come from directly our database. We can change the generated code, which is actually bad. This is just offer one solution for customization.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;

    public partial class MyUsers : IdentityUser
    {
        public string UserId { get; set; }
        public string LanguageId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Password { get; set; }
        public bool Enabled { get; set; }

        [NotMapped]
        public string PasswordHash { get; set; }

        [NotMapped]
        public string Id
        {
            get { return UserId; }
        }
        [NotMapped]
        public string UserName
        {
            get { return FirstName + " " + LastName; }
            set { }
        }  

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<MyUsers> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
Note I added 3 NotMapped properties so that MyUsers can implements IdentyUser, which implements IUser Interface. I also added GenerateUserIdentityAsync which is required by IdentityConfig class under App_Start. All left codes are generated from Entity Framework.

Then create a class named UserStoreService which implements IUserStore<MyUsers>, IUserPasswordStore<MyUsers> and your own IService<MyUsers>.
    using System;
    using LinqKit;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Data.Entity;
    using System.Threading.Tasks;
    using System.Web.UI.WebControls;
    using MyApp.Models;
    using Microsoft.AspNet.Identity;
    public class UserStoreService : Service<MyUsers>, IService<MyUsers>, IUserStore<MyUsers>, IUserPasswordStore<MyUsers>
    {
        public UserStoreService(DbContext db)
            : base(db)
        {
        }

        public UserStoreService()
            : base()
        {
        }

        #region IUserStore implementation
        public Task<MyUsers> FindByIdAsync(string userId)
        {
            Logger.Log("UserStoreService:FindByIdAsync (userId = {0})", userId);

            if (string.IsNullOrEmpty(userId)) return Task.FromResult<MyUsers>(null);
            /*XmlNode n = m_doc.SelectSingleNode(string.Format("/users/user[@id='{0}']", userId));
            MyUsers u = null;
            if (n != null)
            {
                u = new MyUsers { Id = userId, UserName = userId, PasswordHash = n.Attributes["password"].Value };
            }*/
            Task<MyUsers> task = ((MyDBEntities)_db).MyUsers.Where(a => a.Id == userId).FirstOrDefaultAsync();
            return task;
        }

        public Task<MyUsers> FindByNameAsync(string userName)
        {
            Task<MyUsers> task = ((MyDBEntities)_db).MyUsers.Where(a => a.UserName == userName).FirstOrDefaultAsync();
            return task;
        }

        public Task CreateAsync(MyUsers user)
        {
            throw new NotImplementedException();
        }

        public Task DeleteAsync(MyUsers user)
        {
            throw new NotImplementedException();
        }

        public Task UpdateAsync(MyUsers user)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region IUserPasswordStore implementation
        public Task<string> GetPasswordHashAsync(MyUsers user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            return Task.FromResult(user.Password);
        }

        public Task<bool> HasPasswordAsync(MyUsers user)
        {
            return Task.FromResult(user.Password != null);
        }

        public Task SetPasswordHashAsync(MyUsers user, string passwordHash)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region IUserLockoutStore implementation

        public Task<int> GetAccessFailedCountAsync(MyUsers user)
        {
            throw new NotImplementedException();
        }

        public Task<bool> GetLockoutEnabledAsync(MyUsers user)
        {
            //Logger.Log("XmlUserStore:GetLockoutEnabledAsync (user = {0})", user);
            return Task.FromResult<bool>(false);
        }

        public Task<DateTimeOffset> GetLockoutEndDateAsync(MyUsers user)
        {
            throw new NotImplementedException();
        }

        public Task<int> IncrementAccessFailedCountAsync(MyUsers user)
        {
            throw new NotImplementedException();
        }

        public Task ResetAccessFailedCountAsync(MyUsers user)
        {
            throw new NotImplementedException();
        }

        public Task SetLockoutEnabledAsync(MyUsers user, bool enabled)
        {
            throw new NotImplementedException();
        }

        public Task SetLockoutEndDateAsync(MyUsers user, DateTimeOffset lockoutEnd)
        {
            throw new NotImplementedException();
        }

        public Task<MyUsers> FindByIdAsync(object userId)
        {
            throw new NotImplementedException();
        }

        #endregion

        //following 3 functions are used to Handle DataTable control for store procedure based object
        public override List<MyUsers> GetDataTableResultByPage(DataTableParameters param, List<MyUsers> list)
        {
            return GetSearchResult(param, list).Skip(param.Start).Take(param.Length).SortBy(param.SortOrder).ToList();
        }

        public override int GetSearchResultCount(DataTableParameters param, List<MyUsers> list)
        {
            return GetSearchResult(param, list).ToList().Count;
        }

        //Search based on param.Search only. 
        //TODO: can add each search for individual columns
        public override IQueryable<MyUsers> GetSearchResult(DataTableParameters param, List<MyUsers> list)
        {
            string search = param.Search.Value;
            return list.AsQueryable().Where(p => (search == null
                || p.UserName != null && p.UserName.ToLower().Contains(search.ToLower())));
        }
    }
Then replacing ApplicationUser with MyUsers from following class:  IdentityConfig class under App_Start, AccountController, ManageController class.  This solution has problem that once you update your model from database in Entity Framework, the MyUsers class will be changed with default codes. It seemed there is no good solution for this. You can extends ApplicationUser from MyUsers, but still MyUsers need to extends IUser.

Final word, if you check the UserStoreService, there are lots of unused code inside. Its a very complex class. I believe Microsoft will change this Identity Framework in future as they did several times before. So if we want to use our own user tables, it's better to implement our own authentication framework.

Reference:
http://aspnetguru.com/customize-authentication-to-your-own-set-of-tables-in-asp-net-mvc-5/
http://www.codeproject.com/Tips/855664/ASP-NET-MVC-Authentication-Using-Custom-UserStore
http://stackoverflow.com/questions/31584506/how-to-implement-custom-authentication-in-asp-net-mvc-5
https://github.com/KriaSoft/AspNet.Identity/blob/master/docs/Database-First.md
http://identity.codeplex.com/
http://odetocode.com/blogs/scott/archive/2013/11/25/asp-net-core-identity.aspx
http://odetocode.com/blogs/scott/archive/2014/01/09/customization-options-with-asp-net-identity.aspx
http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown
http://www.khalidabuhakmeh.com/asp-net-mvc-5-authentication-breakdown-part-deux
http://brockallen.com/2013/10/20/the-good-the-bad-and-the-ugly-of-asp-net-identity/
http://weblogs.asp.net/jeff/decoupling-owin-external-authentication-from-asp-net-identity
http://www.codeproject.com/Articles/875547/Custom-Roles-Based-Access-Control-RBAC-in-ASP-NET
https://lostechies.com/derickbailey/2011/05/24/dont-do-role-based-authorization-checks-do-activity-based-checks/

Sunday, December 13, 2015

Dynamically Change Connection String for Database-First Entity Framework

Entity Framework get connection string directly from web.config, thus we don't need to offer connection string to establish the Entity Framework as it will automatically setup, open, and close the database. In most case, it is very convenient, however, in real project, we usually need to dynamically change connection string for different working environment.

Reference:
https://msdn.microsoft.com/en-us/library/orm-9780596520281-01-16.aspx

Friday, December 4, 2015

How to deploy your Visual Studio Web Application to IIS 8.5

https://msdn.microsoft.com/en-us/library/dd465337(v=vs.110).aspx
http://www.iis.net/learn/install/installing-publishing-technologies/installing-and-configuring-web-deploy-on-iis-80-or-later

How to Change Your Visual Studio Web Application From SSL Enabled to SSL Disabled

You can easily change your visual Studio web application to use SSL through Project Properties window.


After that, your project's web properties will be changed to use the https link:


So by default, your project will be launched with SSL protocol on your local machine.

However, if you want to change back not to use SSL in your local, you may experience following issue after you change project properties window from SSL Enabled True to SSL Enabled False:

It said, "You can't remove SSL from this site because this Web project is currently configured to browse with this URL. You need to use the Web property page to change the project URL to the non-secure URL first."

It happened because your project's web properties still has https link. You need to change it to use http link and then you can change from SSL Enabled True to SSL Enabled False. 

But how to make it?

When you launch web application through Visual Studio, the IIS Express will be launched as well. Under your twindows task bar, there is IIS Express Icon.


Right click on the Icon, and you will see 2 http links with one https and one http. Copy that http link to your Project's Web Properties configuration for "Project Url link". Then you can change from SSL Enabled True to SSL Enabled False.

Wednesday, December 2, 2015

Applying jQuery DataTable 1.10+ with ASP.Net MVC 5 Tutorial

jQuery DataTable is a jQuery plugin to show table of data.
Note jQuery DataTable had used old-style attribute names like "bProcessing" instead of new name "processing" for older version. Thus Google DataTable will get lots of results based on the old naming style.

Creating DataTable with Customized Columns

The Model part:

The Html part:
<table id="example">
    <thead>
      <tr><th>Sites</th></tr>
    </thead>
    <tbody>
      <tr><td>SitePoint</td></tr>
      <tr><td>Learnable</td></tr>
      <tr><td>Flippa</td></tr>
    </tbody>
</table>
The javascript part:
<script type="text/javascript" charset="utf-8">
    var myTable;
    $(document).ready(function() {
        myTable = $('#jobs-table').dataTable( {
            "destroy": true,
            "processing": true,
            "serverSide": true,
            "ordering": false,
            "info": true,
            "paging": false,
            "searching": false,
            "scrollX": true,
            "ajax": {
                "url": "/DataController/GetDataForTable",
                "type": "GET",
                "data": { "date": startDate}
            },
            "columnDefs": [ {
                "targets": 0, /*column index counting from the left*/
                "searchable": false,
                "className": "dt-right", /* Right align text in the header and body */
                "render": function ( data, type, row ) {
                    return data +' ('+ row[3]+')';
                },
                { "visible": false,  "targets": [ 3 ] }
            }],
            "columns": [
                { "data": "StartDate" },
                { "data": "Players" },
                { "data": "TotalSession" },
            ]
        })
    });
</script>
Note the above javascript will set the data table to align right which defined in the columnDefs for the 1st column.

In addition, the first column will also display the 4th column combined through render function. And it hides the 4th column. The render function has 3 parameters, data, type, and row. The data refers the data for the cell, and also the type.

Serverside DataTable

Note above dataTable define contains serverSide as true, which means the data source will come from server side.  Actually, above code contains ajax parameter, which refers a MVC controller method named GetDataForTable, which returned json data to loading the data table.

    public class DataController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        
        public JsonResult GetDataForTable(string startDate)
        {
            try
            {
                if (startDate == null)
                {
                    return Json(null, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    MyDataModel model = (new MyDataModelService()).GetMyDataModel(startDate);
                    return Json(new {
                        draw = 1, 
                        recordsTotal = model.MyDataList.Count,
                        recordsFiltered = model.MyDataList.Count,
                        data = model.MyDataList }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
    }
Note the json data contained draw, recordsTotal, recordsFiltered, and data, which are needed for data table.

Reference:
http://www.codeproject.com/Tips/844403/jQuery-Datatables-For-Beginners
https://datatables.net/manual/styling/classes
https://datatables.net/manual/server-side
http://legacy.datatables.net/usage/columns
http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part
http://stackoverflow.com/questions/22737957/use-jquery-datatables-server-side-processing-with-mvc-serialize-criteria-form-a/22742742#22742742
https://www.echosteg.com/jquery-datatables-asp.net-mvc5-server-side

Applying Chart.js to get Combined Line chart and Bar chart

http://stackoverflow.com/questions/25811425/chart-js-how-to-get-combined-bar-and-line-charts

Tuesday, December 1, 2015

Apple Style JQuery Toggle Button

JQuery Toggle Button is an Apple style toggle button which has following very nice look and feel.
The light theme is very nice looking. To apply it in your web page, add following css  at first:
  <head>
    <title>My cool page</title>

    <link rel="stylesheet" href="css/toggles.css">
    <link rel="stylesheet" href="css/toggles-light.css">

    <!-- ALL OF THE THEMES -->
    <!-- <link rel="stylesheet" href="css/toggles-all.css"> -->

    <!-- ALL OF THE CSS AND THEMES IN ONE FILE -->
    <!-- <link rel="stylesheet" href="css/toggles-full.css"> -->
and javascript file at latter.
    <script src="js/toggles.js" type="text/javascript"></script>
    <!-- MINIFIED JS - recommended for production -->
    <!-- <script src="js/toggles.min,js" type="text/javascript"></script> -->
  </body>
</html>
Add following to your web page to place the toggle.
<div class="toggle toggle-light">
Add following javascript  to your web page javascript file.
// Simplest way:
$('.toggle').toggles();
// With options (defaults shown below)
$('.toggle').toggles({
  drag: true, // allow dragging the toggle between positions
  click: true, // allow clicking on the toggle
  text: {
    on: 'ON', // text for the ON position
    off: 'OFF' // and off
  },
  on: true, // is the toggle ON on init
  animate: 250, // animation time (ms)
  easing: 'swing', // animation transition easing function
  checkbox: null, // the checkbox to toggle (for use in forms)
  clicker: null, // element that can be clicked on to toggle. removes binding from the toggle itself (use nesting)
  width: 50, // width used if not set in css
  height: 20, // height if not set in css
  type: 'compact' // if this is set to 'select' then the select style toggle will be used
});


// Getting notified of changes, and the new state:
$('.toggle').on('toggle', function(e, active) {
  if (active) {
    console.log('Toggle is now ON!');
  } else {
    console.log('Toggle is now OFF!');
  }
});

Following Javascript code can be used to change toggle states:
// initiate a new Toggles class
$('.toggles').toggles({
  on: true
});

// the underlying Toggles class can be accessed
var myToggle = $('.toggles').data('toggles');

console.log(myToggle.active); // true
myToggle.toggle();
console.log(myToggle.active); // false

// set the state to 'false'
// will not do anything if the state is already false
myToggle.toggle(false);
console.log(myToggle.active); // false

// passing a boolean in place of options on an active toggle element
// will set the state
$('.toggles').toggles(true);
console.log(myToggle.active); // true

// the toggle-active data attribute stores the state too
console.log($('.toggles').data('toggle-active')); // true

// myToggle.toggle(state, noAnimate, noEvent)

// don't animate the change
myToggle.toggle(false, true);

// change the state without triggering an event 
myToggle.toggle(truefalsetrue);
Following javascript can be used to disable and enable your toggle control:
// your toggle element
var toggle = $('.toggle');

// initialise it
toggle.toggles();

// disable the toggle element (click + drag will no longer work)
toggle.toggleClass('disabled', true);

// setting the state via JS is NOT disabled, only user input
// toggle the toggle on
toggle.toggles(true);

// re-enable the toggle
toggle.toggleClass('disabled', false);
My own example:
Html part:
<div id="buttonAutoRefresh" class="toggle toggle-light"></div>
Javascript part:
    var autoRefresh;
    var SetAutoRefreshOnOff = function () {
        var button = $('#buttonAutoRefresh');
        var toggle = button.data('toggles');
        //alert(toggle.active);
        //button.Toggle(); //switch the states of the button
        if (toggle.active) {
            autoRefresh = setInterval(LoadPageContent, 15000); //only set one time
        }
        else if (typeof (autoRefresh) != "undefined") {
            clearInterval(autoRefresh); //clear autoRefresh
        }
    }

    // initiate a new Toggles class
    $('.toggle').toggles({ width: 50 });
    $('.toggle').on('toggle', SetAutoRefreshOnOff);
Reference:
https://github.com/simontabor/jquery-toggles
http://simontabor.com/labs/toggles/

Tuesday, November 24, 2015

How to schedule a SSIS package on SQL Server Agent


Source:
https://www.mssqltips.com/sqlservertutorial/220/scheduling-ssis-packages-with-sql-server-agent/

Tuesday, November 10, 2015

ASP.Net MVC draw chart.js with jQuery Ajax call

Following is a Ajax call example:
//Read
var GetDataList = function (date, callback) {
    $.ajax({
        type: 'GET',
        url: '/Test/GetMyDataList',
        dataType: 'html',
        data: {
            date: date
        },
        success: function (data) {
            if (callback) callback(data);
        }
     });
 };
The above example passed data as parameter which contains date, and once the call is success, another callback function will be used to process the returned data.
//Save
var UpdateDatalist = function (model, callback, callback2) {
    $.ajax({
        type: 'POST',
        url: '/Test/UpdateDatalist',
        dataType: 'json',
        processData : false,
        data: JSON.stringify(model),
        cache: false,
        success: function (data) {
            if (data.ReturnedModel) callback2(data);
            if (isError(data)) return;
            if (callback) callback(data);
        }
    });
};
The above example send a JavaScript object as a JSON string to the server with an AJAX request, you need to convert the JavaScript object to a JSON string and send the string as raw data.

HTTP requests can be send as either, GET, POST, PUT, DELETE or HEAD requests.

Note here it's better to use List<Class> over Dictionary<Key, String> because List can be converted directly into JSON while you need to write customized code to convert Dictionary to JSON data.

Source:
http://forums.asp.net/t/2000850.aspx?json+data+to+a+chart+via+a+JsonResult+Action+in+MVC
https://gist.github.com/dancameron/18ad7e46399406259323
http://stackoverflow.com/questions/19894952/draw-a-chart-js-with-ajax-data-and-responsive-a-few-problems-and-questions
http://tutorials.jenkov.com/jquery/ajax.html#receiving-json

Applying Generic Repository and Unit of Work Pattern with ASP.NET MVC and Entity Framework


Source:
http://www.thereformedprogrammer.net/is-the-repository-pattern-useful-with-entity-framework/
http://www.thereformedprogrammer.net/is-the-repository-pattern-useful-with-entity-framework-part-2/
http://stackoverflow.com/questions/25953881/unit-of-work-repository-service-layer-with-dependency-injection
http://blog.longle.net/2013/05/11/genericizing-the-unit-of-work-pattern-repository-pattern-with-entity-framework-in-mvc/
http://techbrij.com/generic-repository-unit-of-work-entity-framework-unit-testing-asp-net-mvc
http://stackoverflow.com/questions/16572743/generic-repository-with-data-access-layer
http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and-entity-framework.htm
http://ctrlcvprogrammer.blogspot.ca/2015/05/wanted-to-execute-stored-procedure-in.html

Wednesday, November 4, 2015

How to applying Store Procedures to build Entity Framework in ASP.Net MVC project


After you have successfully build your Entity Framework, you can update it if your tables or store procedures have been changed. Right click on the Entity Framework model in your solution explorer, choose Open, and click on Model Browser. Then right click on the root node of the model, and choose Update Model from Database, the data model will be updated. If you changed the database connection string in web.config, and create a new database connection using different connection name, the Model Browser will start a new wizard to connect to the new database. In this way you can switch different database for the predefined Entity Framework.

Source:
http://weblogs.asp.net/dotnetstories/using-stored-procedures-with-entity-framework-in-an-asp-net-application
http://beyondrelational.com/modules/2/blogs/64/posts/11620/entity-framework-40-bind-stored-procedure-with-result-entity-class.aspx

Monday, November 2, 2015

How to remove Source Control Binding from Visual Studio Project

If your project has been binding with TFS before, and you want to open the project locally, you will get following annoying information: The team foundation server http://some-tfs-server/ is currently not available, The solution will be opened locally. To remove the annoying information, deleted the .suo next to the .sln file, and then opened the .sln file in Notepad and deleted this entire section:
GlobalSection(TeamFoundationVersionControl) = preSolution
    SccNumberOfProjects = 2
    SccEnterpriseProvider = {xxxxx}
    SccTeamFoundationServer = http://some-tfs-server/
    SccLocalPath0 = .
    SccProjectUniqueName1 = xxDemo\\xxDemo.csproj
    SccProjectName1 = xxDemo
    SccLocalPath1 = xxDemo
EndGlobalSection
If you can connect to the TFS, you just want to simply unload the project from the source control server, go to File -> Source Control -> Change Source Control and then unbind and/or disconnect all projects and the solution.

This should remove all bindings from the solution and project files. (After this you can switch the SCC provider in Tools -> Options -> Source Control -> Plug-in Selection).

The SCC specification prescribes that all SCC providers should implement this behavior including VSS, TFS, etc.

Source:
http://stackoverflow.com/questions/358951/how-can-i-completely-remove-tfs-bindings

Wednesday, October 28, 2015

What's Breadcrumb on Web SIte?

Breadcrumb on  web site is a navigation menus which shows all position links from home page down to your current page. It offers tracking tools on which user can easily go back and would not get lost on big web sites  which host lots of contents.

Source:
http://www.hongkiat.com/blog/breadcrumb-menu-css3/

Monday, October 26, 2015

Best Bootstrap Plugins for Web BI and Reporting

Bootstrap is the best web front end framework designed for responsive design and mobile first. Except for standard Bootstrap functionality, there are lots of popular Bootstrap Plugins you can apply for your Web Reporting and BI requirement.

Fuel UX

is an incredible collection of enhancements to Twitter Bootstrap. All the controls are clean and lightweight, and they fit naturally into the bootstrap look and feel. The collection includes controls like datagrids, custom select boxes, spinners, trees, multi-step form wizards and more.
  1. Add the fueluxclass to a page wrapper (usually either <html> tag or <body> tag)
    <body class="fuelux">
  2. Include the CSS on your page somewhere:
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <link href="//www.fuelcdn.com/fuelux/3.11.5/css/fuelux.min.css" rel="stylesheet"> 
  3. Include the JS on your page somewhere:
    <!-- jQuery -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="//www.fuelcdn.com/fuelux/3.11.5/js/fuelux.min.js"></script>
Fuel UX has an excellent datepicker, repeater, and tree control,

Date Range Picker

is a component creates a drop down from which you can select a range of date. The component relies on Bootstrap, JQuery, and Moments.js. You need to add following scripts and links on your page:
<!-- Include Required Prerequisites -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/latest/css/bootstrap.css" />
 
<!-- Include Date Range Picker -->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />
The Date Range Picker is attached to a text input. It will use the current value of the input to initialize, and update the input if new dates are chosen.
<input type="text" name="daterange" value="01/01/2015 - 01/31/2015" />
<script type="text/javascript">
$(function() {
    $('input[name="daterange"]').daterangepicker();
});
</script>

Clock Picker

is a unique clock style time picker for Bootstrap.
ClockPicker was designed for Bootstrap in the beginning. So Bootstrap and JQuery are the only dependencies.

The component only used .popover and some of .btn styles of Bootstrap.
<div class="input-group clockpicker">
    <input type="text" class="form-control" value="09:30">
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-time"></span>
    </span>
</div>
<script type="text/javascript">
$('.clockpicker').clockpicker();
</script>

metisMenu

Stylish menu will give your website a perfect weapon to attract visitors. metisMenu can be a solution for this, it’s a JQuery based menu plugin for twitter Bootstrap 3. Here in this menu, you can give effects like animated accordion and supported with auto collapse system.
<script 
src="metisMenu.js"></script>
<script>
  $(function () {
    $('#menu').metisMenu();
  });
</script>

Bootstrap WYSIHTML5

A Javascript plugin that makes it easy to create simple WYSIWYG editors.

A file upload widget which features multiple file selection, drag and drop, progess bars, validation and preview images.
A JQuery plugin for validating forms within Bootstrap.


JQuery Pagination

A plugin that simplifies the usage of Bootstrap's Pagintion by using appropriate classes: .pagination, .active and .disabled.


Bootstrap Star Rating

A jQuery star rating plugin for Bootstrap that supports fractional star fill and RTL input support.

A JQuery based plugin for using select inputs with the multiple attributes.

Bootstrap Video Player

A customizable HTML5 video player plugin for jQuery based on Bootstrap's UI.

Data Tables

Data Tables is the most popular table enhancing add on for Bootstrap. This plugin not only makes your tables sort-able, but it also makes use of the framework’s pagination controls and makes the data searchable. This component is Web BI/Reporting must have tool.

Bootstrap Datagrid

bs_grid is a Bootstrap based jQuery Datagrid plugin. It comes with advanced row selection, pagination, sorting as well as filtering. This bs_grid is fully customizable, responsive, localization and Works sound with Bootstrap or individual.

Social Buttons

Chart.js

Chart.js (github) is a new charting library that uses the HTML5 canvas element and provides fallbacks for IE7/8. The library supports 6 chart types that are animated and fully customizable. Chart.js doesn’t have any dependencies and is less than 5kb in size. Say goodbye to flash!

Bootstrap Image Gallery

Bootstrap Image Gallery is a customizable image & video gallery extension to blueimp Gallery, a touch-enabled, responsive extension for images and videos in the modal dialog of the Bootstrap framework. It features swipe, mouse as well as navigation to keyboard, transition effects, fullscreen support and on-demand content loading. Bootstrap Image Gallery can be extended to display supplementary content types.

Source:
http://tutorialzine.com/2013/07/50-must-have-plugins-for-extending-twitter-bootstrap/
http://speckyboy.com/2014/06/16/plugins-for-extending-bootstrap/
https://medium.com/@themefisher/40-new-must-have-plugins-for-extending-twitter-bootstrap-possibilities-e2a79592c90b#.coqlx2gc7
http://tutorialzine.com/2013/04/50-amazing-jquery-plugins/

Friday, October 23, 2015

Bootstrap 3 Responsive Design Introduction

To add Bootstrap 3, insert following code to your web page.
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
Bootstrap requires HTML 5 doc type, so always put following at the beginning of your web page.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"> 
  </head>
</html>
Bootstrap is mobile first, to ensure proper rendering and zooming, put following at the beginning of your web page.
<meta name="viewport" content="width=device-width, initial-scale=1">
width=device-width sets the page width to screen width of the device. initial-scale=1 sets the initial zoom level when the page was first loaded.

Bootstrap divides screen size into 4 categories, and named with 4 classes accordingly.
  • Extra Small  < 768px       named with "xs"
  • Small            < 992px       named with "sm"
  • Medium        < 1200px     named with "md"
  • Large            >= 1200px   named with "lg"
Bootstrap used 2 types of containers to wrap all other web contents:
  • Fixed width container which has different fixed size for above 4 screens
<div class="container">
</div>
  • Full width container which takes up 100% of width regardless of screen size
<div class="container-fluid">
</div>
Note containers are not nestable, so you can't put container inside another container.

Following showed a basic Bootstrap web page:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
  <h1>My First Bootstrap Page</h1>
  <p>This is some text.</p> 
</div>
</body>
Bootstrap Grid System, one of the most powerful features, can create great responsive design for all kinds of screen.
  • Rows must be placed inside .container or .container-fluid for proper align and padding
  • Rows are used to create horizontal group of columns. 
  • The grid has maximum 12 columns for each row, thus any extra rows would be displayed in a new row. 
  • Each columns has padding, which are spacing between columns and can do align with other columns. 
Basic Structure of Bootstrap Grid:
<div class="container">
  <div class="row">
    <div class="col-*-*"></div>
  </div>
  <div class="row">
    <div class="col-*-*"></div>
    <div class="col-*-*"></div>
    <div class="col-*-*"></div>
  </div>
  <div class="row">
     ...  
  </div>
</div>
The first * could be xs, sm, md, lg, representing the 4 classes for different screen size, and the last * could be 1,2,3,4. The last * adds up should be always 12.

Example of Bootstrap Grid:
<div class="container">
  <div class="row">
    <div class="col-md-2"></div>
    <div class="col-md-2"></div>
    <div class="col-md-2"></div>
    <div class="col-md-2"></div>
  </div>
  <div class="row">
    <div class="col-sm-8"></div>
    <div class="col-sm-4"></div>
  </div>
  <div class="row">
     ...  
  </div>
</div>
The first row of columns will be stacked when  the screen size is less than 992px. The second row of columns will be stacked when the screen size is less than 768px.

Note the 4 different classes for different screen size can be combined together to create more flexible layout.

For example, for following code, if the screen is big enough, all will be displayed in one row. However, if the screen get smaller, col-sm-4 will be useless, and all col-xs-6 will be effective, and the last column will be displayed in another row.
<div class="row">
  <div class="col-xs-6 col-sm-4">.col-xs-6 .col-sm-4</div>
  <div class="col-xs-6 col-sm-4">.col-xs-6 .col-sm-4</div>
  <div class="col-xs-6 col-sm-4">.col-xs-6 .col-sm-4</div>
</div>
Bootstrap table has following classes:
.table .tablestrip .table-bordered .table-hover .table-condensed  .table-responsive

The .tablestrip adds zebra strips to a table.
The .table-bordered adds borders for all sides of the table and cells.
The .table-hover enables hover states on each row.
The .table-condensed makes a table more compact through reduce the cell padding by half.
The .table-responsive makes table scroll horizontally on devices with small screen. Note it should be used with <div> outside the table.

<div class="table-responsive">
  <table class="table tablestrip table-bordered table-hover table-condensed">
    ...
  </table>
</div>
Bootstrap table row and column has following classes:
.active .success .info .warning .danger
.active adds hover color to table cells.
<tr class="success">
  <td>John</td>
  <td>Doe</td>
  <td>john@example.com</td>
</tr>
Bootstrap will let some elements show or hide, depending on the screen size:

Images can scale based on screen size by using .img-responsive class. The image will be scale while keep its aspect ratio. To center responsive image, using .center-block class.

Source:
http://getbootstrap.com/css/
http://www.w3schools.com/bootstrap/bootstrap_get_started.asp
http://www.w3schools.com/bootstrap/bootstrap_grid_system.asp
http://www.devx.com/webdev/easily-create-responsive-websites-using-bootstrap.html