DCSIMG
July 2011 - Posts - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

July 2011 - Posts

HTML5 Web Notifications

HTML5 Web Notifications

HTML5 Web NotificationsEver wanted to notify your site clients/users while they are surfing in your site? notifications like “Mail message arrived”, “Printer out of paper” are available through smart clients for decades but in web applications they are not so easy to implement. In the past you could have implemented a blinking behavior that will make the icon of the browser blink or you could add a popup which will annoy your users. There are ways to implement this behavior in a browser specific way (for example Overlay Icon API in IE9) but in HTML5 there is a new option – Web Notifications API. This API isn’t a recommendation yet so things might change in the future and using it is on your own risk.

What is Web Notifications API?

The Web Notifications API is a mechanism for building simple notifications that will alert users outside of the web page. These notifications can be used passively (notify about new tweets, calendar events and more) or actively (with user interactions) and they are not bound to the tab that has focus. The API relay on a permission that is granted by the user. Without indication that notifications were requested by the user the notifications mechanism won’t work.

Granting Permissions

The first step in using Web Notifications is to check with the user whether he wants to be notified. The following code sample shows how to use the requestPermission and checkPermission functions that are part of the notifications API:

$('#btnGrantPermission').click(function () {
    if (window.Notifications.checkPermission() == 0) {
        createNotification();
    } else {
        window.Notifications.requestPermission();
    }
});

In the sample I use jQuery to bind a click event to a button that will check whether we have permission to use notifications. If there is a permission then the checkPermission function will return 0 and in the sample I call the createNotification function. If we don’t have permissions then we use the requestPermission function to request a permission to use notifications in the web page.

Pay attention that the requestPermission must run under an event handler that is triggered by a user!

How to Use Web Notifications API?

In order to use the web notifications API you need to create a notification. Here is a sample of creating a notification using the createNotification function:

function createNotification() {
    var notification = window.Notifications.createNotification("1.png", "New HTML5 Notification Received - Subject", "More Content...");
    notification.onshow = function () {
        setTimeout(notification.cancel(), 1500);
    }
    notification.show();
}

In the sample I use the createNotification factory function to create a notification. The function gets a Uri for an image to show in the notification, a subject string and a content string. After that I wire to the onshow event a setTimeout function to cancel the notification. The show function which is used last will display the notification to the user. In the specification you can also use the Notification object and instantiate it with the same parameters. 
The createNotification is coming from webkit engine implementation.

The Full Example

<!DOCTYPE html>
<html>
<head>
    <title>Notifications</title>    
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
    <div>
        <input id="btnGrantPermission" type="button" value="Grant Notification Permission" />
    </div>
    <script type="text/javascript">
        $(document).ready(function () {        
            if (window.webkitNotifications) {
                window.Notifications = window.webkitNotifications;
                $('#btnGrantPermission').click(function () {
                    if (window.Notifications.checkPermission() == 0) {
                        createNotification();
                    } else {
                        window.Notifications.requestPermission();
                    }
                });
            }            
        });        
 
        function createNotification() {
            var notification = window.Notifications.createNotification("1.png", "New HTML5 Notification Received - Subject", "More Content...");
            notification.onshow = function () {
                setTimeout(notification.cancel(), 15000);
            }
            notification.show();
        }
    </script>
</body>
</html>

A few things to pay attention about the sample:

  • I remove the webkit prefix since in the specifications it doesn’t exists. It will be omitted when the specifications will be a recommendation (I hope…).
  • The sample will work only in browsers that use webkit engine such as Google Chrome.
  • I use jQuery to add event listener to the click event.

Here is the notification that you’ll get when you use this piece of code:
Notification

Summary

Web Notifications API can add more power for web developers by helping them to create simple notifications to their clients when things like arriving mail, event alert and more happens in the web application. The specifications are currently in working draft so they might change in the future. Moreover, only the browsers that use webkit engine implement it currently so it is very early to adapt this API.

Using The Viewport Meta Tag

Using The Viewport Meta Tag

Many smartphone browsers support the viewport meta tag which controls the logical dimensions and scaling of the browser’s viewport window. In this post I’m going to describe what is the viewport meta tag and how you can use it in your web pages.

Using The Viewport Meta Tag in my Blog

When I got my HTC HD7 smartphone I wanted to see how my blog is looking in the smartphone’s browser. So I entered my blog’s address and this is how it was rendered in my phone:
WithoutViewport
The view is not so good since the blog is squeezed and it doesn’t look well at all. So I started to look for a solution and I found the viewport meta tag. The viewport meta tag controls the logical dimensions and scaling of the smartphone browser’s window and tell it that the web page is optimized for mobile. You use the meta tag like in this example:

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

Pay attention that if you use this meta tag there are some smartphones that doesn’t support it!

Now my blog’s display will look like this in my mobile’s browser:
WithViewport

Since my blog is optimized only for desktop view (it is based on Community Server and the theme isn’t optimized for mobile display), then the blog isn’t displayed so well either. So the experiment went wrong but I got to know the viewport meta tag. If you'll look at my blog in your mobile's browser then you'll get the first display (with no viewport meta tag) which let you scan my blog, zoom in and out when you find something interesting.

The Viewport Meta Tag Options

The demo showed only two properties of the viewport meta tag which are the width and initial-scale. There are much more options which are:

  • width – width of the viewport in pixels. It can also get the device-width (like in the previous example) value which indicates that the viewport should be the current device’s width.
  • height – height of the viewport in pixels. Like the width it can get the device-height value to take the device’s height.
  • initial-scale – sets the the initial scaling of the viewport. The 1.0 value displays unscaled web page.
  • user-scalable – specifies whether the user can scale the web page (zoom in or zoom out). Can get the yes or no values.
  • maximum-scale or minimum-scale – sets the maximum or minimum scaling for the web page. Can get values between 0.25 to 10.0.

Summary

The viewport meta tag enables the web developers to indicate that the web page they built is optimized for mobile devices. Most of the new devices support it including iPhone, Android, webOS, WP7’s Internet Explorer and more. For further reading about the viewport meta tag you can go to the this link.

Razor Helpers Syntax

Razor Helpers Syntax

One hidden gem of Razor View Engine is the declarative helper syntax. Razor Helpers SyntaxWith this syntax we can create helper components that are stored as .cshtml files, and enable reusability of view code. The name of the syntax might sound familiar and it is since it reminds the HtmlHelper class that was provided as part of MVC 1. In this post I’ll explain the Razor helper syntax and discuss why it sounds familiar to HtmlHelper.

@helper Syntax and The HtmlHelper Class

When you want to encapsulate a view code and make it reusable you’ll probably create an extension method to extend the HtmlHelper class. By doing so all you’ll need to do when that view code is needed is to call the @Html with the method name you’ve created. Here is an example of a HtmlHelper method for building a simple HTML5 video tag:

public static class HtmlHelpers
{
  public static MvcHtmlString Video(this HtmlHelper helper, string id, string sourceUrl, bool controls)
  {      
    TagBuilder builder = new TagBuilder("video");
    builder.MergeAttribute("id", id);
    builder.MergeAttribute("src", sourceUrl);
    if (controls)
    {
      builder.MergeAttribute("controls", "controls");
    }      
    return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
  }
}

and integrating it inside a view:

@{
    ViewBag.Title = "Home Page";
}
@using AsyncMVC
 
<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.    
</p>
@Html.Video("prolog", Url.Content("~/Prolog.mov"), true)

Razor view engine makes it even easier. You can use the @helper syntax and create an inline helper code inside your view (without the creation of an extension method) or make it reusable as a different cshtml file. How does it work? lets take a look at an inline example:

 
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
        http://asp.net/mvc</a>.
</p>
@helper Video(string id, string sourceUrl, bool controls)
{      
    TagBuilder builder = new TagBuilder("video");
    builder.MergeAttribute("id", id);
    builder.MergeAttribute("src", sourceUrl);
    if (controls)
    {
        builder.MergeAttribute("controls", "controls");
    }
    var video = new MvcHtmlString(builder.ToString());
    @video         
}
@Video("prolog", Url.Content("~/Prolog.mov"), true)

As you can see most of the code that was in the HtmlHelper was transferred to the view with a little change of using a variable for the returned type. This inline code makes it easier to call the method (no HtmlHelper class in the middle) and we don’t need to create extension methods in our application. On the other hand using inline code isn’t reusable outside the scope of the view so what can we do about that? we can separate the helper block to a different cshtml file and use it in our other application views.

Separating Helpers into their own File

In order to put Razor helpers in their own cshtml file you’ll have to add the App_Code directory to your MVC application. In the application project create a new directory with the name App_Code. ASP.NET consider this directory name as special directory name and therefore it will get a special icon. After creating the directory add a View (cshtml file) into it and call it Helpers (for example):

 Helpers

In the created cshtml file, drop the code of the helper from the previous code block and add a using statement for System.Web.Mvc (which is needed for the TagBuilder and MvcHtmlString classes):

@using System.Web.Mvc
@helper Video(string id, string sourceUrl, bool controls)
    {      
        TagBuilder builder = new TagBuilder("video");
        builder.MergeAttribute("id", id);
        builder.MergeAttribute("src", sourceUrl);
        if (controls)
        {
            builder.MergeAttribute("controls", "controls");
        }
        var video = new MvcHtmlString(builder.ToString());
    @video         
}

After building the solution now the previous view can be used as follows:

@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
        http://asp.net/mvc</a>.
</p>
@Helpers.Video("prolog", Url.Content("~/Prolog.mov"), true)

Now the video helper is reusable and you can use it in all the views in your application.

Summary

The Razor helper syntax can be very usable and can help you to create helpers without the need for extension methods. On the other hand that doesn’t mean that the HtmlHelper extensions don’t have benefits. Since you can place them in different class libraries you can reuse their code in other applications. With the helper syntax you’ll have to create the App_Code directory and move the helper files to other applications. The choice is yours so pick what you think is more suiting for your implementation.

ASP.NET MVC Model Binders

ASP.NET MVC Model Binders

One thing that I’m always asked to talk about when I’m delivering ASP.NET MVC sessions or courses is ModelASP.NET MVC Model Binders Binders. In this post I’ll explain what are Model Binders in ASP.NET MVC and how you can use them in your MVC application.

Model Binders

ASP.NET MVC is providing a way to de-serialize complex types that are part of the incoming HTTP request input. After these types are de-serialize they are passed to the relevant controller’s action as method arguments. In the following controller action method code, during the execution of ASP.NET MVC pipeline, a binder is used to create the Customer instance from the request input:

[HttpPost]
public ActionResult Edit(Customer customer)
{
    if (ModelState.IsValid)
    {
        var mycustomer = _customerdb.GetCustomer(customer.Id);
        TryUpdateModel(mycustomer);
 
        return RedirectToAction("Index");
    }
 
    return View(customer);
}

ASP.NET MVC supplies some binders out of the box such as DefaultModelBinder that is using conventions (such as naming conventions) in order to create the model from the request or FormCollectionModelBinder that maps a request to a FormCollection object. You can use those defaults and of course you can create your own Model Binders.

Creating a Custom Model Binder

In order to create a Model Binder you need to get familiar with the IModelBinder interface:

public interface IModelBinder 
{ 
    object BindModel(ControllerContext controllerContext, 
        ModelBindingContext bindingContext); 
}

This interface declare the BindModel method which is the only method that you need to implement. The method gets as arguments the controller context and the model binding context. The ControllerContext object holds  information about the current HTTP request and about the associated controller. The ModelBindingContext holds information about the model itself and its metadata. In most of the time you won’t have to write your own binder but if you need to then follow the example.

Custom Model Binder Example

In the example I’ll use the following Course presentation model object:

public class Course
{
    #region Properties
    
    public int CourseID { get; set; }    
    public string Title { get; set; }    
    public string Days { get; set; }    
    public DateTime Time { get; set; }
    public string Location { get; set; }        
    public int Credits { get; set; }
    
    #endregion
}
Here is a simple implementation of a Model Binder for the Course model:
public class CourseModelBinder : IModelBinder
{
  #region IModelBinder Members
 
  public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
  {
    HttpRequestBase request = controllerContext.HttpContext.Request;
    int courseId = Convert.ToInt32(request.Form.Get("CourseID"));
    string title = request.Form.Get("Title");
    string days = request.Form.Get("Days");
    DateTime time = Convert.ToDateTime(request.Form.Get("Time"));
    string location = request.Form.Get("Location");
    int credits = Convert.ToInt32(request.Form.Get("Credits"));
 
    return new Course
    {
      CourseID = courseId,
      Title = title,
      Days = days,
      Time = time, 
      Location = location,
      Credits = credits
    };
  }
 
  #endregion
}

The binder will create the instance of the course by converting all the relevant types from the incoming HTTP request.

Remark: The DefaultModelBinder will also do the same thing since it will use the naming conventions and the property types in order to make the conversion. This is only a simple example in order to explain the concept of Model Binders.

Integrating a Custom Model Binder

In order to integrate a Model Binder into your application you’ll use the ModelBinders class and its Binders collection. Here is how you’ll integrate the previous binder:

ModelBinders.Binders.Add(typeof(Course), new CourseModelBinder());

The perfect place to put this line of code is in the Application_Start event in the Global.asax file.

Summary

Model Binders are very useful and saves us a lot of development time. They help us to transform HTTP request input into model instances automatically and by that making our life easier. When in need, you can create your own custom Model Binder and integrate it into your MVC application.

HTML5 – Selectors API Level 1

HTML5 – Selectors API Level 1

Lately, I’m dealing a lot with HTML5. I co-authored a three days course in that topic for Sela, HTML5 – Selectors API Level 1the company I work for. During the process of creating the course I got to learn a lot about HTML5 and what to expect from the new specifications so expect more posts about this subject in the near future. In this post I’m going to describe what is the JavaScript Selectors API Level 1 and compare it with jQuery.  

Selectors API

The Selectors API enables web developers to select DOM elements and retrieve DOM nodes that match against a group of selectors. This approach simplifies the selection of elements and make it integrated directly in the browser. The API describes two new and powerful methods that enable selections -

  • querySelector – selects the first match for a given selection expression and returns a DOM element.
  • querySelectorAll – selects all the matches for a give selection expression and returns DOM elements array.

The selection expression is a CSS3 group of selectors that can be separated with commas (which means Logical Or between the selected elements). 
For further reading about the Selectors API go to the specifications.

Selecting Elements using Selectors API

Now that we got familiar with the specifications lets deep dive into an example. In the example I’m going to use the following HTML fragment:

<!DOCTYPE html>
<html>
<head>
    <title>Selectors Example</title>
    <style type="text/css">
        .red
        {
            color: Red;
        }
        .blue
        {
            color: Blue;
        }
    </style>
</head>
<body>
    <ul id="ulOfItems">
        <li>item 1</li>
        <li class="red">item 2</li>
        <li id="item3">item 3</li>
        <li class="red">item 4</li>
        <li>item 5</li>
    </ul>
</body>
</html>

When I want to use the Selectors API in order to grab the first list item with red class I’ll write the following line of code:

var elm = document.querySelector("ul li.red");

If I want to grab all the list items with red class I’ll write the following line of code:

var elements = document.querySelectorAll("ul li.red");

Here is a full example with two methods that select the single or multiple list items and then change their class name when a button is clicked:

<!DOCTYPE html>
<html>
<head>
    <title>Selectors Example</title>
    <style type="text/css">
        .red
        {
            color: Red;
        }
        .blue
        {
            color: Blue;
        }
    </style>    
</head>
<body>
    <ul id="ulOfItems">
        <li>item 1</li>
        <li class="red">item 2</li>
        <li id="item3">item 3</li>
        <li class="red">item 4</li>
        <li>item 5</li>
    </ul>
    <input type="button" name="btnFirstElm" value="Change First Element Class Name" onclick="changeClassNameToBlueToFirstLI()"/>
    <input type="button" name="btnAllElm" value="Change All Elements Class Name" onclick="changeClassNameToBlueToAllLI()"/>
    <script type="text/javascript">
        function changeClassNameToBlueToFirstLI() {
            var elm = document.querySelector("ul li.red");
            elm.className = "blue";
        }
 
        function changeClassNameToBlueToAllLI() {
            var elements = document.querySelectorAll("ul li.red");
            for (var i = 0; i < elements.length; i++) {
                elements[i].className = "blue";
            }
        }        
    </script>
</body>
</html>

Comparing Selectors API To jQuery Selectors

When I first heard about Selectors API you could probably hear me grin. jQuery and other JavaScript libraries are doing the same thing for years. The only difference between an external library and native support in the browser in this case is that you need to download the external library in all the pages they are needed. This can be minimized with the use of CDNs or client cache for better performance. So what gives? native browser support gives those libraries the ability to use and implement a better selection implementation. If you’ll open jQuery 1.6.2 (the latest version) and seek for the word querySelector you’ll see that jQuery is targeting the new selection functions first by applying feature detection. So under the hood jQuery will use the native selection support, if available in the browser, and that is perfect. So how will you refactor the previous example to use jQuery?
Here is a proposed implementation: 

<!DOCTYPE html>
<html>
<head>
    <title>Selectors Example</title>
    <script src="jquery-1.6.2.js" type="text/javascript"></script>
    <style type="text/css">
        .red
        {
            color: Red;
        }
        .blue
        {
            color: Blue;
        }
    </style>
</head>
<body>
    <ul id="ulOfItems">
        <li>item 1</li>
        <li class="red">item 2</li>
        <li id="item3">item 3</li>
        <li class="red">item 4</li>
        <li>item 5</li>
    </ul>
    <input type="button" id="btnFirstElm" value="Change First Element Class Name" />
    <input type="button" id="btnAllElm" value="Change All Elements Class Name" />
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnFirstElm').click(function () {
                $('ul li.red').first().toggleClass('blue');
            });
 
            $('#btnAllElm').click(function () {
                $('ul li.red').each(function () {
                    $(this).toggleClass('blue');
                });
            });
        });
    </script>
</body>
</html>

Even though the adding of better native browser support for selection is a great thing still jQuery and other JavaScript libraries offer more richness and more selection options. Since these external libraries depends upon native browser API then underneath they might be using the Selectors API and as I wrote jQuery is doing exactly that.

Summary

The post explained what are the new HTML5 Selectors API functions. It also compared the new API to the use of selectors in jQuery. The bottom line is that you might use the new API and gain native browser support for selectors or you might use jQuery (or other JavaScript libraries) that uses under the hood the same functions if they are available. The choice is yours.

Microsoft Entity Framework June 2011 CTP was Released

Microsoft Entity Framework June 2011 CTP was Released

Yesterday, ADO.NET team released a new EF CTP. If you attended my Sela Dev. Days EF4.1 tutorial day this week you heard about this release and the new features. Here is the list of new features to expect from EF4.2 that you can evaluate with the new EF CTP:

Runtime Features

  • The Enum data-type. At last we will have support for enums. You can use either the Entity Designer within Visual Studio to model entities that have Enum properties, or use the Code First workflow to define entities that have Enum objects as properties. You can use your Enum property just like any other scalar property, such as in LINQ queries and updates.
  • Geography and Geometry Spatial data-types which are natively supported by the Entity Framework.
  • Table-valued functions can be added to entity data models. A table-valued function is similar to a stored procedure, but the result of executing the table-valued function is composable, meaning you can use it as part of a LINQ query.
  • Stored procedures can now have multiple result sets in your entity data model.
  • The Entity Framework June 2011 CTP includes several SQL generation improvements.
  • LINQ queries are now automatically compiled and cached to improve query performance.

Entity Framework Designer Features

  • The Entity Designer now supports the creation of enums, spatial data-types and table-value functions from the designer surface.
  • You can now create multiple diagrams for each entity data model. Each diagram can contain entities and relationships to make visualizing your model easier.
  • The StoreGeneratedPattern for key columns can now be set on an entity Properties window and this value will propagate from your entity model down to the store definition.
  • Diagram information is now stored in a separate file from the edmx or entity code files.
  • Batch import for stored procedures as function imports. The result shape of each stored procedure will automatically become a new complex type in your entity model. This makes getting started with stored procedures very easy.
  • The Entity Designer surface now supports selection driven highlighting and entity shape coloring.

Mode Information About the CTP Release

For further information about the CTP you can go to this link. Pay attention for the Getting the Microsoft Entity Framework June 2011 CTP and the Getting Started sections in the announcement and also to the Uninstalling section.

Here are some CTP walkthroughs that were published in ADO.NET team blog:

Enjoy!