13 January 2014

Ignite UI Code Sample

This article is an attempt to learn Infragistics Ignite UI [which itself built on jQuery], How powerful features it has and how easily it can be used to achieve many of our UI requirements. Best part of Ignite UI Grid is that it has built in support for Filtering, Column Hiding, Sorting, Column Rearrange, etc with just few lines of code. Including pagination!
Infragistics Ignite UI (formerly Net Advantage for jQuery) includes high-performance ASP.NET MVC and jQuery controls based on CSS3 and HTML5 for Web Developers who need to deliver the best cross-platform user experiences.
The below sample code is to demonstrate few of features and properties:

   1:  <!DOCTYPE html>
   2:  <html>
   3:  <head>
   4:      <title>Ignite Grid Sample</title>
   5:      <!-- Ignite UI Required Combined CSS Files -->
   6:      <link href="http://cdn-na.infragistics.com/jquery/20132/latest/css/themes/infragistics/infragistics.theme.css" rel="stylesheet" />
   7:      <link href="http://cdn-na.infragistics.com/jquery/20132/latest/css/structure/infragistics.css" rel="stylesheet" />
   8:      <script src="http://modernizr.com/igsb-highlights/modernizr-latest.js"></script>
   9:      <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  10:      <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
  11:   
  12:      <!-- Ignite UI Required Combined JavaScript Files -->
  13:      <script src="http://cdn-na.infragistics.com/jquery/20132/latest/js/infragistics.core.js"></script>
  14:      <script src="http://cdn-na.infragistics.com/jquery/20132/latest/js/infragistics.lob.js"></script>
  15:  </head>
  16:   
  17:  <body>
  18:    <div class="content-wrapper">
  19:          <!-- the igGrid target element-->  
  20:          <table id="grdIgnite" style="width: auto;"></table>
  21:    </div>
  22:  <script type="text/javascript">
  23:      $(function () {
  24:          var data = [
  25:          { "Charactor": "Rajesh koothrappali", "Portrayed by": "Kunal Nayyar", "TV series": "Big Bang Theory" },
  26:          { "Charactor": "Leonard Hofstadter", "Portrayed by": "Johnny Galecki", "TV series": "Big Bang Theory" },
  27:          { "Charactor": "Sheldon Cooper", "Portrayed by": "Jim Parsons", "TV series": "Big Bang Theory" },
  28:          { "Charactor": "Neal Caffrey", "Portrayed by": "Matt Bomer", "TV series": "White Collar" },
  29:          { "Charactor": "Peater Burke", "Portrayed by": "Tim DeKay", "TV series": "White Collar"},
  30:          { "Charactor": "Seeley Booth", "Portrayed by": "David Boreanaz", "TV series": "Bones"},
  31:          { "Charactor": "Brennan Bones", "Portrayed by": "Emily Deschanel", "TV series": "Bones"},
  32:          { "Charactor": "Ted Mosby", "Portrayed by": "Josh Radnor", "TV series": "How I Met Your Mother" },
  33:      { "Charactor": "Barney Stinson", "Portrayed by": "Neil Patrick Harris ", "TV series":"How I Met Your Mother" },
  34:      { "Charactor": "Jake Peralta", "Portrayed by": "Andy Samberg", "TV series": "Brooklyn Nine-Nine" },
  35:          { "Charactor": "Jessica ", "Portrayed by": "Zooey Deschanel ", "TV series": "New Girl"},
  36:          { "Charactor": "Nicholas Miller", "Portrayed by": "Jake Johnson", "TV series": "New Girl" },
  37:          { "Charactor": "Leslie Knope", "Portrayed by": "Amy Poehler", "TV series": "Parks and Recreation" },
  38:          { "Charactor": "Tom Haverford", "Portrayed by": "Aziz Ansari", "TV series": "Parks and Recreation" },
  39:          { "Charactor": "Andy Dwyer", "Portrayed by": "Chris Pratt", "TV series": "Parks and Recreation" },
  40:          { "Charactor": "Ron Swanson", "Portrayed by": "Nick Offerman", "TV series": "Parks and Recreation" }
  41:                  ];
  42:          $("#grdIgnite").igGrid({
  43:              caption: 'TV Shows',
  44:              height: "550px",
  45:              width: "900px",
  46:              dataSource: data, //JSON Array           
  47:              features: [
  48:                      {
  49:                          name: 'Filtering'
  50:                      },
  51:                      {
  52:                          name: 'GroupBy'
  53:                      },
  54:                      {
  55:                          name: 'Hiding'
  56:                      },
  57:                      {
  58:                          name: 'Paging',
  59:                          type: 'local',
  60:                          pageSize: 6
  61:                      },
  62:                      {
  63:                          name: "ColumnMoving",
  64:                          mode: "immediate",
  65:                          addMovingDropdown: true,
  66:                          mode: "deferred",
  67:                          type: "render"
  68:                      }
  69:                  ]
  70:   
  71:          });
  72:      });
  73:      </script>
  74:  </body>
  75:  </html>

03 January 2014

AngularJS Code Samples

AngularJS, a JavaScript framework developed by a Google and supported by Google. As the technology grows we have lost the patience to wait for a search results on web and wanted faster results. We do not want to render a HTML page on server side and the concept of Single page Application (SPA) started which leads to many front-end frameworks like Knockout, Ember, Angular, backbone what not!
Briefly:  AngularJS is focused on maintaining data models for objects, and how they are viewed on the front end. It  assists with running single-page applications (SPA).
AngularJS uses a Model-View-Controller programming concept. This involves separating the:
– Model (the data objects represented in your application), from the
– View (all the stuff the user sees — for example, all the differently tweaked screens and sub screens in Android vs iOS vs desktop browser versions of Chrome/Firefox/IE/Safari, etc), from the
– Controller (the glue code that manages the Model and connects it with the various Views).
Before we get into any theory, let us get our hands dirty with some actual Angular code. Thanks to Viral Patel (http://viralpatel.net/blogs/ ) for a nice sample application this was really helpful to understand the concepts.

Let us see a small Hello World application and we will try to see what the new terminologies it brings up. In above demo, just write something in the textbox and press Add button. This will adds whatever you type in text box in an array. The content of array is displayed below in a list.


   1:  <!DOCTYPE html>
   2:  <html ng-app id="ng-app"> 
   3:  <title>Hello World, AngularJS</title> 
   4:  <script type="text/javascript"     src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js">
   5:  </script> 
   6:  </head> 
   7:  <body> 
   8:  <div ng-controller="ContactController">      
   9:          Email:<input type="text" ng-model="newcontact"/>     
  10:      <button ng-click="add()">Add</button>     
  11:      <h2>Contacts</h2>       
  12:          <ul>         
  13:              <li ng-repeat="contact in contacts"> {{ contact }} </li>     
  14:          </ul>   
  15:  </div> 
  16:  <script type="text/javascript">
  17:      function ContactController($scope) {
  18:          $scope.contacts = ["Jijo.Venginikkadan@mail.com", "vgjijo@maildomain.com", "vgjijo@somedomain.com"];
  19:   
  20:          $scope.add = function () {
  21:              $scope.contacts.push($scope.newcontact);
  22:              $scope.newcontact = "";
  23:           }
  24:          }
  25:  </script> 
  26:  </body> 
  27:  </html> 
  28:   

Scope is nothing but an object that Glues the View with Controller. They hold the Model data that we need to pass to view. Scope uses Angular’s two-way data binding to bind model data to view.
ng-controller defines a Controller to be bound with the view. In this case we defined a controller called ContactController in DIV using ng-controller attribute.
ContactController is nothing but a plain vanilla JavaScript function. In the demo we defined it as function. Also see the definition of ContactController function. There is an object $scope which we pass as an argument. This object is used to bind the controller with view. When AngularJS initialize this controller, it automatically creates and injects the $scope object to this function using dependency injection
ngRepeat is one of the most used AngularJS attribute. It iterate through an array and bind the view with each element. So in our example it creates tag for each item within contacts array. ngRepeat takes expression as argument. In our case “contact in contacts” where contact is user defined variable and contacts is an array within $scope.
The function add() is bound to Add button using an attribute ng-click. ng-click binds the click event on the button or link or any clickable element with the function that is defined within $scope. So in this case, whenever Add button is clicked, the add() method on $scope will be called. In add() method we add (or push) a string in contacts array. This is the string that user types in text box

19 November 2013

Json object from MVC view to controller as Parameter

JSON (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. When working together with jQuery and ASP.NET MVC in building web applications, it provides an efficient mechanism to exchange data between the web browser and the web server. This includes built-in JSON binding support that enables action methods to receive JSON-encoded data and model-bind it to action method parameters. To see this feature in action, consider the client-side jQuery below.


   1:      $('#Save').click(function () {
   2:          var customer = {
   3:              Name: $('#Name').val(),
   4:              Code: $('#Code').val()
   5:          };
   6:          $ajax({
   7:              url: 'Custoer/Save',
   8:              type: "POST",
   9:              data: JSON.stringify(customer),
  10:              dataType: "json",
  11:              contentType: "application/json",
  12:              success: function () {
  13:                  $('#message').html('Data Saved').fadeIn();
  14:              },
  15:              error: function () { $('#message').html('Operation failed').fadeIn(); }
  16:          })
  17:          return fasle;
  18:      });

Next is to consume this data at the server side, i.e. at MVC control, create a model class with exact number of fields to hold the desterilized data.And then have a action method in your controller method.


   1:      public class Customer
   2:      {
   3:          public string Name { get; set; }
   4:          public string Code { get; set; }
   5:      }
   6:      public ActionResult Save(Customer jsonCustomerData)
   7:     {
   8:          bool result = true;
   9:          Customer customerData;
  10:          JavaScriptSerializer jss = new JavaScriptSerializer();
  11:          customerData = jss.Deserialize<Customer>(jsonCustomerData);
  12:          // Logic to save data
  13:          return Content(result.ToString());
  14:     }

As you see above sample server side we have an action which accepts strongly-typed Customer object as a parameter. Serialized json object will be routed here. That means ASP.NET MVC 3 automatically bind the incoming JSON post values to the .NET Customer type on the server – without you having to write any custom binding or marshalling logic. Now inside the method you may desterilize this data using JavaScriptSerializer which is available in System.Web.Script.Serialization library.

17 November 2013

Connection not found in the configuration exception

Problem:
I have a MVC 3 application which talks to Business Layer to get the Business objects that paint my UI. Client application consumes Business layer to pull the data from database and business library have one entity framework object. The connection string is added to app.config in connection string section, but when I want create new entity context and use this connection string, this error is appear:
“The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.”
Solution:
You need to copy the connection string in the app.config to your web.config, or copy the entire file to the project which displays the output. It is one of the conditions to consume the framework.

   1:    <connectionStrings>
   2:      <add name="ADONETEntities" connectionString="metadata=res:
//*/Customer.csdl|res://*/Customer.ssdl|res://*/Customer.msl;
provider=System.Data.SqlClient;provider connection string=&quot;
data source=DatabaseTest,10501\SQLEXPRESS;initial catalog=dbTest;
persist security info=True;user id=user_dbo;password=pwd123;
multipleactiveresultsets=True;App=EntityFramework&quot;
" providerName="System.Data.EntityClient" />
   3:    </connectionStrings>

07 November 2013

async/await with MVC4

The .NET 4.5 Framework introduced the new async/await asynchronous programming model. With ASP.NET MVC 4 comes the application of the async/await model to controller actions. A traditional ASP.NET MVC control action will be synchronous by nature; this means a thread in the ASP.NET Thread Pool is blocked until the action completes. Calling an asynchronous controller action will not block a thread in the thread pool. The greatest advantage of using this is to bring UI more responsive.
Well before .NET 4.5 (and MVC 4), we need to controller to inherit from AsyncController and implement this. With latest release this made simple and brought up to language level. To do Async in ASP.NET MVC, all you have to is return a Task and use the async keyword in your action methods.
As ASP.NET MVC 4 runs on top of .NET framework 4.5, we can use the magical async and await keywords to simplify this process. Using these keywords, we can easily create asynchronous controller actions just like we created methods. Following is a sample implementation of a controller action method:
Enough of theory, let’s walk the talk.

   1:  public class HomeController : Controller
   2:  {
   3:      public async Task<ActionResult> Index()
   4:      {
   5:          Task<int> weatherInfoTask = WeatherApi.GetFollowersAsync();
   6:          Task<int> stockTickerTask = StockTickerApi.GetFollowingAsync();
   7:          await Task.WhenAll(weatherInfoTask, stockTickerTask);
   8:          ViewBag.WetherInfo = await weatherInfoTask;
   9:          ViewBag.StockTicker = await stockTickerTask;
  10:          return View();
  11:      }
  12:  }

Here we first invoke both asynchronous Weather API calls and only then await them using Task.WhenAll. Finally, we use the Result property of each task to get the Weather and Stock Ticker info.
An async method will be run synchronously if it does not contain the await keyword.  In the above code, we are calling a WCF services asynchronously. As a method marked as async must return a Task, the return type is modified to Task.await pauses the method until the operation completes.
Well, to conclude:
async: A method modifier that signals to the .NET language compiler that the marked method will run within its own thread, and that execution cannot continue past the point until the awaited asynchronous process is finished. Meanwhile, control is returned to the caller of the async method.
await: An operator that suspends the execution of the method to which it applies. When called, an asynchronous method synchronously executes the body of the function up until the first await expression on an awaitable instance that is not yet completed, at which point the invocation returns to the caller.
In this tutorial we learned how writing asynchronous controllers is a powerful optimization that has become much easier to implement since MVC 4 and C# 4.5.

03 November 2013

Simple jQuery getJSON Example in ASP.NET MVC


First off, what is JSON? It is an alternative to XML as a way of sending information from one device to another. Now, how do we use it as a mediator between a database and a web page in ASP.NET MVC 4?
Well, it is going to be simple two step process as mentioned below:
1. Write a controller that contains a method that is called when a client requests a web page from the server.
2. Write a view that is linked to the controller method, and which generates the markup that is returned to the client.

The controller method will usually collect some data from some other source, such as a database or some other C# code (which is usually part of the Model in MVC). This data is then packaged up, possibly in a C#/JSon object, and sent to the View, where the View formats the data and generates the HTML which is interpreted by the browser.
Basically what happens is this:
1.    Client requests a web page.
2.    Controller method is called to process this request.
3.    The corresponding View is returned to the browser.
4.    The View contains some JavaScript code that makes another request to the server, this time asking for some data in JSON format.
5.    A different Controller method from that called in step 2 is called to generate the JSON, which is returned to the browser.
6.    The JavaScript code processes the JSON and generates some HTML which is displayed (JSON is not meant to be displayed as raw data by the browser; rather, it is retrieved by the browser and then processed on the client side before it is displayed)

In this post, I will create a very basic and simple example demonstrating jQuery's getJSON method using ASP.NET MVC.
First up, I create an empty MVC project with one Controller. The code for this controller is shown below. For simplicity, the data model is also stored here and we create the data on fly. In a production application, this will be separated   using multiple layers and the data, of course, would come from the database.
   1:  <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   2:      <script type="text/javascript">
   3:          $(document).ready(function () {
   4:              $('#btnGetCustomers').click(function () {
   5:                  $.getJSON("/Json/GetJsonData", null, function (data) {
   6:                      var div = $('#ajaxDiv');
   7:                      div.html("<br/> " + "Customeres received from server: " + "<br/>");
   8:                      $.each(data, function (i, item) {
   9:                          printCustomer(div, item);
  10:                      });
  11:                  });
  12:              });
  13:          });
  14:   
  15:          function printCustomer(div, item) {
  16:              div.append("<br/>" + "FName: " + item.FirstName + ", LName: " + item.LastName);
  17:              });
  18:          }
  19:      </script>
  20:   
  21:      <input id="btnGetCustmers" type="button" value="Get Customers" />
  22:      <div>
  23:          <div id="ajaxDiv">
  24:          </div>
  25:      </div>
  26:   
  27:  $(document).ready(function () {
  28:      $('#save').click(function () {
  29:          var person = {
  30:                          Id: 100,
  31:                          Name: $('#Name').val(),
  32:                          Age: $('#Age').val(),
  33:                          PhoneNumber: $('#PhoneNumber').val()
  34:                      };
  35:          $.ajax({
  36:              url: '/Home/CreatePerson',
  37:              type: "POST",
  38:              data: JSON.stringify(person),
  39:              dataType: "json",
  40:              contentType: "application/json; charset=utf-8",
  41:              success: function (result) {
  42:                  $('#message').html('Person Saved' + result).fadeIn();
  43:              },
  44:              error: function () {
  45:                  $('#message').html('Error Occurred').fadeIn();
  46:              }
  47:          });
  48:          return false;
  49:      });
  50:  });
C# code 

   1:       public ActionResult Index()
   2:          {
   3:              return View();
   4:          }
   5:   
   6:          public JsonResult GetJsonData()
   7:          {
   8:              var Customer = new List<Customer>
   9:                                {
  10:                                    new Customer{Id = 1, FirstName = "John", 
  11:                                        LastName = "Randy", PhoneNumber = "(614)370-0220"},
  12:                                                                                                          
  13:                                    new Customer{Id = 2, FirstName = "Sheila", 
  14:                                        LastName = "Wood", PhoneNumber = "(614)370-0200" }};
  15:   
  16:              return Json(Customer, JsonRequestBehavior.AllowGet);
  17:   
  18:          }
  19:   
  20:      }

07 August 2013

Record Filtering in XamDataGrid

Sample code which enable record filtering in XamDataGrid;-
Reference dlls-
InfragisticsWPF4.DataPresenter.v12.1
InfragisticsWPF4.v12.1

   1:  <Window x:Class="XamDataGridSamples.Window1"
   2:          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   4:          xmlns:igDP="http://infragistics.com/DataPresenter"
   5:          Title="Window1" Height="300" Width="300">
   6:      <Grid>
   7:          <igDP:XamDataGrid Name="xamDataGrid1" BindToSampleData="True">
   8:              <igDP:XamDataGrid.FieldSettings>
   9:                  <igDP:FieldSettings
  10:                      AllowRecordFiltering="true" 
  11:                      FilterLabelIconDropDownType="MultiSelectExcelStyle"/>
  12:              </igDP:XamDataGrid.FieldSettings>
  13:              <igDP:XamDataGrid.FieldLayoutSettings>
  14:                  <igDP:FieldLayoutSettings
  15:                      FilterUIType="LabelIcons"
  16:                      FilterRecordLocation="OnTopFixed" />
  17:              </igDP:XamDataGrid.FieldLayoutSettings>
  18:          </igDP:XamDataGrid>
  19:      </Grid>
  20:  </Window>
Screenshot:

04 August 2013

HTML5 Introduction

Recently I got some time to take a dive in to HTML5 and I would like to share my experience here.  This was long pending as, the news of HTML5 was getting demands a while when companies like Apple started using this. Every new Apple mobile device and every new Mac supports HTML5 with Safari web browser. All major browsers (Safari, Chrome, Firefox, Opera, and Internet Explorer) continue to add new HTML5 features to their latest versions.
HTML5 is not one big thing; it is a collection of individual features like support for individual features like canvas, video etc. This will be my Introduction web log on HTML5 and I will try to go through most of them in my subsequent blogs. Like most of the cases my learning process starts with open questions and then tries to reach to answers.
What is HTML5?
HTML5 is a markup language for structuring and presenting content over web pages. HTML5 is the next revision of the Hypertext Markup Language (HTML). In theory, HTML5 will allow the Web browser to become a development platform. A primary goal for this is to ensure interoperability among browsers so that Web applications and documents behave the same way no matter across the devices. (Older browsers that do not support HTML 5 will be able to ignore the new constructs and still produce legible Web pages. That’s sounds cool right ?)
Why HTML5?
After the birth of original HTML it has gone through many years of updates. And all these updates they tried to integrate with different versions. HTML 5 is the most recent one among that. For example when video streaming came on web there was no in built support for this. So companies like Quick Time, Real Player, Windows Media player and flash introduced there on and in order to use this user has to download external plug-in.  The idea behind HTML5 is to come up with a consistent experience across all devices and browsers. Today, the different browser's are working together to achieve this goal.
New Features
Some of the most interesting new features in HTML5:
  • The canvas element for 2D drawing
  • The video and audio elements for media playback
  • Support for local storage
  • New form controls, like calendar, date, time, email, url, search
Here we will try to experiment with few among the above. Let’s take a small sample of Playing a YouTube Video in HTML. You can achieve this few lines-of code.

<!DOCTYPE html>
<html>
<body>
 
<iframe width="420" height="345"
src="https://www.youtube.com/watch?v=SE_X9cF431g">
</iframe>
 
</body>
</html>
Also please find samples of script and noscript tag. 

<!DOCTYPE html>
<html>
<script>
document.write("Hello World!")
</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>
</body>
</html>
We will continue exploring the other features in next logs.