Saturday, November 30, 2013

HTML5: Web storage explained and usage of local storage and session storage functions


HTML 5 brings lots of powerful features with it and for those who want alternative to cookies it has ‘Web Storage’ in its magic box.
 

What is web storage?
Web storage is more secure alternative to cookie to store data on client. We can store objects in the form of key value pairs. Its access is fast and secure.
 

What are the types?
There are two types of available storage. One is ‘Local Storage’ and other is ‘Session Storage’. 
1. Local Storage:
Object stored in this storage does not have any expiry you can store any JavaScript object here. Even if you close the browser, objects in local storage are persisted. 
2. Session Storage:
As the name suggests this storage is session specific. Object stored in this storage is persisted only for a browser session. If you close tab or browser window objects in this storage get automatically cleared.
 

My Findings
One interesting fact I found during my analysis of these storages that object stored in local storage gets shared across tabs. It means when I open my website in two different tabs of the same browser then object stored in local storage gets shared by both the instances. But if I use session storage then objects are maintained specific to that browser session considering different tabs. So if you want to share the data irrespective of the multiple tabs then use local storage. But if you don’t want the mix up of objects across instances then use session storage.
 

Functions
There are number of functions provided to set, get and remove item from local/session storage. If you want to clear all the objects in storage then ‘clear’ function is available. I don’t want to go into much details of each function instead I would like to give more power to you with some utility functions created by me.
 

Important
To use any HTML 5 feature it is important to check browser compatibility as not all the browsers support its features. My preference for checking the compatibility is Modermizr library.
 

And here are utility functions for you. Free of cost J
 

/*HTML5 Local Storage*/
/*------------------------------------------------------------------------------------*/
/*Sets or adds item in HTML5 local storage*/
function setLocalItem(key, value) {
    if (Modernizr.localstorage) {
        localStorage.setItem(key, value);
    }
}
 
/*Gets item in HTML5 local storage*/
function getLocalItem(key) {
    if (Modernizr.localstorage) {
        return localStorage.getItem(key);
    }
} 

/*Removes item in HTML5 local storage*/
function removeLocalItem(key) {
    if (Modernizr.localstorage) {
        localStorage.removeItem(key);
    }
} 

/*Clears all items in HTML5 local storage*/
function clearLocalStorage() {
    if (Modernizr.localstorage) {
        localStorage.clear();
    }
}
/*------------------------------------------------------------------------------------*/
 

/*HTML5 Session Storage */
/*------------------------------------------------------------------------------------*/
/*Sets or adds item in HTML5 session storage*/
function setSessionItem(key, value) {
    if (Modernizr.sessionstorage) {
        sessionStorage.setItem(key, value);
    }
} 

/*Gets item in HTML5 session storage*/
function getSessionItem(key) {
    if (Modernizr.sessionstorage) {
        return sessionStorage.getItem(key);
    }
} 

/*Removes item in HTML5 session storage*/
function removeSessionItem(key) {
    if (Modernizr.sessionstorage) {
        sessionStorage.removeItem(key);
    }
} 

/*Clears all items in HTML5 session storage*/
function clearSessionStorage() {
    if (Modernizr.sessionstorage) {
        sessionStorage.clear();
    }
}
 
Hope this will help you as it made my life simple. Keep watching this space for more about HTML 5……

JavaScript trick: Use two dimensional array as enum to get value

Ever thought of using Enum in JavaScript? Probably every developer thinks about it. I wanted to use two dimensional JavaScript array similar to Enum in C# and also wanted to use it as key value pair. And there is a way by which you can use it like Enum and then like a key value pair.

Let's declare an array first.

var browsers = { "Microsoft": "IE", "Google": "Chrome", "Apple": "Safari", "Opera": "Opera" };

This array lists companies and their browsers. My aim is to use it like Enum and then retrieve browser's name when company name is selected.

To get a browser by Microsoft, let's use following syntax:
var msBrowser = browsers.Microsoft;

You can observe that the syntax is very similar to Enum and it returns the value 'IE'.

This article might be very foolish for many. But may help learners like me. Who are you?

MVC: Passing C# enum collection as JSON object in model along with view



Okay...today I am gonna write about very weird requirement and a solution. I don't know how many of you already got into such scenario, but let's see what is it and then I would like to know if there is anything better.

What was my requirement?
Eternal question in developers' life, WHAT IS THE REQUIREMENT DUDE? And the answer is...

I had created a simple view using Razor syntax. I had created a model to bind it. I wanted to pass a collection of enum values to view and use that in JavaScript.
 Here is my model class
public class UserDetails
{
    public string UserName { get; set; }

    public string UserEmail { get; set; }

    public string City { get; set; }
}

To achieve my goal I added a property of type string to the model class and class looks like

public class UserDetails
{
     public string UserName { get; set; }

     public string UserEmail { get; set; }

     public string City { get; set; }

     public string Hobbies { get; set; }
}

Here is the enum of hobbies:
public enum Hobby : int
{
   Reading = 500,
   Writing,
   Sports,
   Music
} 

Action method looks like this:
public ActionResult GetUserDetails(int userId)
{
     // Get user details
     UserDetails userDetails = Utility.GetUserDetailsById(userId);
 

     //Get hobbies
     Collection<Hobby> hobbies = Utility.GetHobbiesByUserId(userId);
         

     // Create serializer object
System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

     // Serialize the object
     userDetails.HobbiesString = javaScriptSerializer.Serialize(hobbies);

     return View();
} 

Key line of code to notice here is use of JavaScriptSerializer. When I serialize the collection object using this serializer it returns serialized string. I set that to newly added property of type string and return view.
In view I get this string from the model object. To use it in JavaScript, I used JQuery’s parseJSON function as follows:
var hobbies = $.parseJSON('@Model.HobbiesString');

I got following array as a result:
[‘502’, ’503’, ‘504’]

Conclusion:
I learnt something new about use of JavaScript serializer. You can do fancy things using it. Do share your experiences too.
 
 
 
 
 
 


 
 

Monday, May 27, 2013

Entity Selector in ASP.NET MVC using jQuery - An alternative approach to people picker in SharePoint

Developer’s life is full of challenges. On some sunny morning, your client comes with very cool idea or you think of very cool idea for implementation of a control. Even if idea seems cool, when it comes to implementation it annoys a lot many times. I wanted to implement something cool in my project too. For that I thought of one idea. I wanted to implement an entity selector control in ASP.NET MVC. A control which will allow user to select one or more users. You can say similar to people picker in SharePoint. I wanted to implement it differently. So I started thinking about implementation. I searched web for good implementations. After some research I started my work inspired by few of the social networking sites. I did not want to use any third party control or jQuery plug in. Therefore I started writing script. And to my surprise I finished my task using very less script. With the combination of some HTML, jQuery and jQuery UI, I created my control. It is nothing but a partial view. It can be plugged in any view in my MVC application. Following is the code:
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
    $(".remove").on('click', function () {
        $(this).parent().remove();
    });
    var t = 0;
    $('#userinput').on('keyup', function (event) {
        var query = '';
        query = $(this).val();
        if (event.keyCode == 8) {
            if (query == '' && t == 1) {
                if ($("#userList").children().length > 0) {
                    $("#userList").children().last().remove();
                    t = 0;
                }
            }           
        } else {
            t = 0;
        }
    });
 
    $('#userinput').on('keydown', function (event) {
        var inputWidth = (this.value.length + 1) * 10;
        $(this).width(inputWidth);
        var query = '';
        query = $(this).val();
        if (event.keyCode == 8) {
            if (query == '' && t == 0) {
                t++;
            }
        }
    });
 
    $(function () {
        var filteredUsers = ["Bhushan", "Nikhil", "Onkar", "Pranjali", "Prasad", "Prashant", "Sayali", "Ramiz", "Vikrant"];
        $("#userinput").autocomplete({
            source: filteredUsers,
            select: function (event, ui) {
                var user = '';
                user = ui.item.value;
                $("#userList").append('<div style="background-color:white;height:25px;margin:10px; float: left; display: inline-block;">' + user + '<a href="#" class="remove">X</a></div>');
                $(this).val('');
                $(this).focus();
                t = 1;
                return false;
            },
            messages: {
                noResults: '',
                results: function () { }
            }
        });
    });
 
 
</script>
<style type="text/css">
    .ui-autocomplete-input {
        border: none;
        background-color: azure;
    }
 
        .ui-autocomplete-input:focus {
            border: none;
            background-color: azure;
        }
</style>
<h3>Select User:</h3>
<div>
    <div id="picker" style="background-color: azure; float: left; display: inline-block">
        <div id="userList" style="background-color: azure; float: left; display: inline-block;">
        </div>
        <input id="userinput" />
    </div>
</div>

Please ignore style as I am not a designerJ. For demo I have hard-coded values bound to the autocomplete box. You can provide proper data source through view model. This is the basic implementation of control. You can do many fancy things by adding more features and applying styles. I would like to know your story about how you extended this control. So keep posting your stories and enjoy!!