Monday 7 January 2013

Using Automapper with ASP.NET MVC application

Automapper is a convention based object - object mapper.  It is available in GitHub.  Here I explain about how to use Automapper to map between domain model objects and view model objects in ASP.NET MVC applications.  Install Automapper to the project through Nuget.  
Let us take a simple example of Employee model as follows : 
public class Employee
    {
        public int EmployeeId { get; set; }
        
        public string EmployeeName { get; set; }
    }
And my Employee view model as follows :
public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }
        
        public string EmployeeName { get; set; }

    }
 Consider there is a strongly typed view which expects a model object of type EmployeeViewModel.  So after querying with the Emplyee model object, we need to map this to EmployeeViewModel object.
Here is the use of AutoMapper.
AutoMapper can be configured in the web project.  To make this more maintainable, create a folder (say Mappings) in the solution.
Here we can create two profile classes.  One for mapping from domain model object to view model object and another one for reverse mapping.
public class DomainToViewModelMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "DomainToViewModelMappings"; }
        }

        protected override void Configure()
        {
            Mapper.CreateMap<Employee, EmployeeViewModel>();
        }
    }

public class ViewModelToDomainMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "ViewModelToDomainMappings"; }
        }

        protected override void Configure()
        {
            Mapper.CreateMap<EmployeeViewModel, Employee>();
        }
    }
Now create a configuration class inside Mappings folder.
public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<DomainToViewModelMappingProfile>();
                x.AddProfile<ViewModelToDomainMappingProfile>();
            });
        }
    }
And then call this configuration from Global.asax.
AutoMapperConfiguration.Configure();
And from the controller easily map the employeeObject (domain model object) to employeeViewModelObject (view model object) and vice versa.
var employeeViewModelObject = Mapper.Map<Employee, EmployeeViewModel>(employeeObject);
In advanced scenario we can even customize the configuration.  For example we can map a particular property from source to destination. 
Mapper.CreateMap<X, XViewModel>()
                .ForMember(x => x.Property1, opt => opt.MapFrom(source => source.PropertyXYZ));
Automapper gives really a better and easy way to map between objects.

Tuesday 24 April 2012

Running Android Apps On Windows PC


Now it is possible to run Android applications on Windows PC.   BlueStacks  has introduced an App Player which allows you to run Android applications on Windows XP, Vista and 7.  Beyond PC's this App Player could also allow Windows tablets to run Android applications.



The software provides options to download applications from Google's Android Application Market.  It is also possible to sync your Android device with this emulator and can run the apps in your device.  The software can be downloaded from www.bluestacks.com.

The only requirement for installing this software is Microsoft .NET Framework 3.5 which you will be prompted to install if it is missing.
Read more here.

Thursday 15 March 2012

Offline Data Storage Using HTML 5 (Offline Web Applications)

The users of a typical online web application are not able to use the application without internet connection.  In offline mode they cannot access data such as inbox of mail, calender appointments etc.  But in a desktop application everything is stored locally as some data files.

Now we have a solution for this .  HTML 5 is much more than a typical markup language.  HTML 5 provides some solutions for this problem.  The two major features of HTML 5 for data storage are :

  • SQL-based database API.
  • Offline Application HTTP Cache.

SQL-based database API

This API helps in structured data storage using a client-side SQL database.  The window object has the openDatabase() method to create database objects.  The arguments for this method are:

  • Database name
  • Database version
  • Display name
  • Estimated size in bytes
For example

var db=openDatabase('mydb','1.0','TestDB',1048576);

The transaction() method is used to have further transactions with the created database.  The arguments of this method are:
  • Transaction callback
  • Error callback
  • Success callback
On the transaction callback a SQL transaction object is passed on which we can use executeSQL() method.  There are one to four arguments for this method:
  • SQL statement
  • Arguments
  • SQL statement callback
  • SQL statement error callback
The SQL statement's resultant object gives access to the rows, last inserted ID etc.

Executing Queries

var db=openDatabase('mydb','1.0','TestDB',1048576);
db.transaction(function(tx){
    tx.executeSql('CREATE TABLE IF NOT EXIST MYTABLE(id unique,name)');
});

Insertion

tx.executeSql('INSERT INTO MYTABLE (id, name) VALUES (1, "SomeName")');

Read

tx.executeSql('SELECT * FROM MYTABLE', [], function (tx, results) {
   var len = results.rows.length, i;
   msg = "<p>Found rows: " + len + "</p>";
   document.querySelector('#status').innerHTML +=  msg;
   for (i = 0; i < len; i++){
      alert(results.rows.item(i).log );
   }
 }, null);

Offline Application Caching API
The manifest attribute of <html> element helps to make the web applications available even when the internet is not connected.  The manifest attribute takes an URI to be cached. It stores some information in a file like this :

CACHE MANIFEST
index.html
help.html
style/default.css


NETWORK:
server.cgi

The server.cgi should never be cached so that any attempt to access that file will bypass the cache.  All other files specified get cached.
The manifest is linked by declaring like this

<!DOCTYPE HTML>
<html manifest="cache-manifest">

The server.cgi is in Network: section so that it can be accessed to get updated from the server as in

<event-source src="server.cgi">

HTML 5 introduced the new element <event-source> to continuously stream updates from server to a webpage.
HTML 5 contains some other APIs also which helps in data storage.  For example onLine attribute of Navigator object determine whether the user is currently online.


localStorage attribute of Window object also helps in simple synchronous storage access.
The offline storage is helpful for mobile web applications to work offline.  The user can work offline with the local database and can share the data with the server database when going online

Wednesday 14 March 2012

KendoUI, It's All About User Experience

Kendo UI is an HTML5jQuery-based framework for building modern web apps.  It is not only UI but much more. It is based on HTML 5, CSS 3, Javscript etc. Kendo UI provides some core features which you need:

  • UI widgets
  • Client-side Data source
  • High-Performance Templates
  • Data Binding 
  • Drag-and-Drop API
  • Animations
  • Built-in Touch support
Kendo UI contains three frameworks.
  • Web
  • Mobile
  • DataViz
Developers can choose according to their needs.  Cross platform mobile app development is becoming much easier by the introduction of such frameworks.  
Installing and getting started with Kendo UI is very easy
  1. Download Kendo UI. You can download here.
  2. Copy the Kendo UI CSS and Javascript resources to your project.
  3. Configure your page to use Kendo UI scripts and skins.
  4. Now you can use Kendo UI.
Let's see a demo of using panel bar (accordion) in Kendo UI.
The panel bar utilizes the list to define its structure and content.
  1. Create a list of items.
    <ul id="panelId">
        <li>
            Item 1
                <ul>
                    <li>Sub Item 1</li>
                    <li>Sub Item 2</li>
                </ul>
        <li>
        <li>Item 2</li>
    </ul>
  2. Using an ID selector initialize the panlbar.
    $(document).ready(function() {
        $("#panelId").kendoPanelBar();
    });
Check the Demos to see how you can build HTML 5 applications using Kendo UIhttp://demos.kendoui.com/  
The Kendo Mobile provides necessary tools to build native looking mobile applications.

Tuesday 13 March 2012

HTML 5, The Next Generation Web Technology



HTML5 is the next generation of HTML.  It includes the fifth revision of HTML, CSS 3 and a series of Javascript APIs.  The major browsers support many of the elements and APIs of HTML 5. 
HTML5 helps developers to create apps and websites with the functionality, speed, performance etc. of a desktop application.   But for a web application there is broader audience and wider array of devices. 


Some rules for HTML5 set by W3c and WHATWG are:
  • New features should be based on HTML, CSS, DOM and Javascript.
  • Reduce the need of external plugins like Flash.
  • Replace scripting by using more markups.
  • Should be device independent.
HTML 5 has only one <doctype> declaration which is <!DOCTYPE html>.  Some of the new features include <canvas> element for 2D drawing, <video> and <audio> elements for media playback, local storage support etc.  Some new content-specific elements are also introduced in HTML5 such as <article> , <footer>, <header>, <nav>, <section> etc.  New form controls like calender, date, time, search, email, url etc. are also introduced.


Before HTML 5  we used <div> tags for any kind of structuring the web pages.  But HTML 5 provides a wide range of tags for structuring the web pages.
HTML 5 includes API for GeoLocation.  This is a very useful functionality to find out the geographical location through a device's user agent like mobile devices.  Now it is very easy to embedding media to web pages.  The video and audio tags are really some cool stuffs in HTML 5.

<video width="600" height="500" src="somevideo.mp4"/>


The form is also upgraded in HTML 5.  See some iput types newly includes in HTML 5.

  • <input type="number">
  • <input type="email">
  • <input type="search">
  • <input type="date">
  • and more...
For an extent  some form validations are also possible in HTML 5.  We can specify the minimum value for an input field just by setting the "min" attribute(eg: min="1").


Mobile development became a revolution by the introduction of HTML5. 

See the anatomy of a HTML 5 mobile app. 


The key features of HTML5 for mobile devices includes:
  • Offline Support.
  • Canvas Drawing.
  • Video and Audio Streaming support.
  • GeoLocation API.
  • Advanced Forms.
Using HTML 5, developers can create modern applications with great user experience which can smoothly cross the platforms.  Since the technology giants such as Apple, Google etc are promoting, HTML 5 mobile development is quickly changing the face of the mobile-market.  All major browsers like Safari, Chrome, Firefox, Opera, Internet Explorer continue to add more features of HTML5 in their new versions.