Search This Blog

Sunday, February 24, 2013

KnockoutJS and MVC

KnockoutJS is one of the great JavaScript libraries that follows MVVM design pattern. MVVM pattern is originated from Microsoft with Silverlight/WPF application development. KnockoutJS is the JavaScript implementation of this pattern.

These are some of the key benefits of developing web applications in MVVM pattern with KnockoutJS.

1. Provide a clear separation between UI and business/backend logics.

Model - Data objects in business/backend. (This is JSON data object returned from a RESTful service or AJAX call.)
View - User Interface.
View Model - Model of the view or represent data in the UI. This provides an abstraction of a view. View interacts with View Model through data binding.

2. Two way data bindings and automatic UI refresh - This means when UI changes, View Model updates automatically. When View Model changes, UI refreshes automatically.

3. Dependency Tracking - Knockout automatically detects and handles dependencies between properties and cascades changes accordingly.

Visual Studio MVC 4 Internet and Mobile application templates come with reference to KnockoutJS. So, this is an indication of Microsoft’s continuous support of KnockoutJS as the JavaScript MVVM library.

Saturday, November 10, 2012

WebApi vs ServiceStack

While ServiceStack has good features that WebApi currently does not support, these are the good reasons why WebApi is a good choice as your enterprise RESTful service in the long run. 

WebApi fits well and easy to integrate with MVC 4 UI - WebApi comes as a part of MVC 4 templates and there is no need of installing additional dlls as in ServiceStack. On the other hand, we need to install about 8 ServiceStack dlls and configure MVC project before we start working with ServiceStack. If someone already knows MVC, it is very easy to pick up WebApi and integrate it with MVC 4 UI.

WebApi is easy to learn - There is a learning curve with ServiceStack mainly because of limited learning resources and no book is written in this subject as of now. In the future, I believe more and more people are going to be using WebApi. This is because most companies who use Microsoft products tend to use Microsoft's version of RESTful web service.

Possible issues with upgrading MVC 4 to a newer MVC version in the future - There is no guarantee that ServiceStack continually supports new versions of MVC after MVC 4. This is especially true if Microsoft changes the MVC architecture in a future release. However, we can be sure that WebApi evolves with MVC and no issue in upgrading to a new version of MVC in the future.

Saturday, October 13, 2012

MVC 4 New Feature - Bundling and Minification

“Bundling and Minification” is a new feature introduced in ASP.NET MVC 4. Bundling reduces the number of HTTP requests to the web server by combining group of JS or CSS files into one file. Most of current browsers only allow about 6-8 concurrent connections to the host web browser. That’s means if you have more than 8 JS or CSS files, the browser only loads them when the first concurrent connection(s) is closed. Bundling will improve the performance by combining multiple files into one and thereby improve the overall performance of the website. Minification improves the load time of a JS or CSS file by removing unnecessary whitespace, comments and characters.

The both Bundling and Minification provide in MVC 4 through Microsoft.Web.Optimization namespace.

In order to enable Minification and Bundling in your ASP.NET MVC 4.0 application, you can follow the steps below.

1. Open BundleConfig.cs file under App_Start folder. Enable Bundling and Minification by adding the following line into RegisterBundles method of BundleConfig.cs.

public static void RegisterBundles(BundleCollection bundles)
{
BundleTable.EnableOptimizations = true;
}

2. Add group of JS or CSS files into global BundleTable object. After specifying a virtual path for the bundle, include files you need in the bundle. The following code demonstrates how to bundle JS and CSS files. You can use ScriptBundle for bundling JS files and StyleBundle for bundling CSS files.

public static void RegisterBundles(BundleCollection bundles)
{
// Bundling different versions of JS files using wildcards
bundles.Add(new ScriptBundle("~/bundles/js")
.Include("~/Scripts/jquery-{version}.js")
.Include("~/Scripts/jquery-ui-1.*"));

// Bundling JS files regardless of version
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));

// Bundling multiple JS files.
bundles.Add(new ScriptBundle("~/bundles/AppJS").Include(
"~/Scripts/JS-File1.js",
“~/Scripts/JS-File2.js”,
“~/Scripts/JS-File3.js”));

// Bundling CSS files
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/site1.css",
"~/Content/site2.css"));
}

3. Add references to these bundles in the _Layout.cshtml page.

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("js")
@Scripts.Render("AppJS")

4. Set debug attribute of compilation property in the web.config to false. If this value is true, Bundling and Minification is disabled and ASP.NET MVC 4 runtime refers to individual CSS and JS files instead. So, if you are in development and you would like to debug, you can set debug to true and when you are ready to deploy, you can change this value to false.

<system.web>
<compilation debug="false"/>
</system.web>

Saturday, June 9, 2012

SOA Best Practices - Performance and Security

Services should be structured, designed with security in mind. Security includes service security, transport security and message security. However, Security measures introduce some overhead. So, the performance trade-offs need to be measured carefully. 

1. Avoid transmitting large amount of data between your service and service consumers.
  • Accelerator technologies, such as compression, may also be able to effectively reduce some of the processing load.
  • Send subsets of data if consumer requested large amount of data.

2. For maximum security, consider using transport layer security and message-based security.
  • Message-based security such as XML-Encryption and XML-Digital signatures does not encrypt the headers information. You need to use transport layer security (SSL) if you want to encrypt message headers. 
  • Many security measures introduce processing overhead, so the performance trade-offs that need to be measured carefully. 

3. If you need to call multiple services consider calling those services parallel. 
  • Calling multiple services sequentially reduce the overall performance of your service. Consider using Parallel Activity workflow of Windows Workflow Foundation 4.0 to call multiple services parallel. 

Thursday, April 26, 2012

SOA Best Practices - Developing and Deploying a Service

Web services open the door to new integration opportunities and the quality of the interface they expose is very important. For example, changing an interface after it has been deployed can be a costly and messy task. So, it is very important to pay attention to reliability, quality and extensibility of the service. These are some of the points you can consider when designing and developing a service.

1. Operation and data contracts should be designed in such a way that if possible, you can extend them without affecting existing consumers of the service.
  • If the existing contracts cannot be extended, consider developing a different service for new business requirements or new service clients. 
  • It is very important to make sure that the service consumers are not blocked from using your service after modifying or adding new functionality to your service. This ensures the quality and reliability of your service. 

2. Design against an Interface not vice versa. Design the service interface first rather than building application logics and then expressing that functionality through an appropriate service interface.
  • If you design interfaces first and know the purpose of those interfaces, it is easy to start writing business functionalities under it. This also ensures the consistency and reusability of service interface design. 

3. Implement validation logic to check all input based on value, range and type; and reject all invalid data. 
  • If your service consumers call your service with invalid requests, your service may fail to respond or throw an exception inside your business logics and it may very difficult to debug the issue. 
  • If you do not capture invalid inputs and notify the service consumers for the service failure, your service consumers may not know the reason why they did not get a valid response. 

4. Expose your WCF service both with basicHttpBinding and wsHttpBinding so that wide range of clients can consume it.
  • Non .NET/legacy clients only able to consume your service using basicHttpBinding. 

5. Try to use request objects instead of passing multiple parameters.
  • Having multiple parameters can make it hard to maintain your service and it is also hard for your service consumers to call your service. 

6. Returns an appropriate sized subset of the data rather than returning large amount of the data in one call.
  • It can result in service timeout and also can frustrate the consumers of your service due to latency of the response. 

7. Use a meaningful, business specific name as the service name.
  • Consumers of your service should be able to easily recognize your service based on its main business functionality. 
  • Consistent naming convention helps service consumers to easily recognize your service. 
  • A consistent set of services that cleanly establishes the level of clarity between the services enables easier interoperability and reuse. 

8. If possible, always publish the service to UDDI, so the service consumers can access the service by service name.
  • If the consumers of your service are not calling your service using UDDI service name, your consumers may not able to access your service in case the host of your service or the name of your service is changed.

Tuesday, April 24, 2012

Developing a Content-Rich Media Application using Silverlight

Silverlight is a platform independent, cross browser and enterprise ready technology. Its capabilities such as Client-side processing, client-side local caching and asynchronous communication make Silverlight a good technology for multimedia and content rich websites. XAML based UI allows developers to build loosely coupled, customizable and modular applications. This web application called "My Nature Album" was developed to demonstrate desktop-like user experience and better media experience of Silverlight.
 
Features
1. High performing rich user interface for viewing images with image preview capabilities.
2. Ability to play and stop image presentation/show.
3. Easy navigation between categorized collections of images.
4. Full Screen view functionality.
5. Animation based on user actions.
 
Technologies/Tools used
Silverlight 5, .NET 4.0, LINQ to XML, Visual Studio 2010, Expression Blend 4.0 and MVVM Pattern.
 
  •     For better user experience, please view it in full-screen mode by clicking the icon on upper right corner of the application.
  •     You can play and stop presentation by toggling play/pause buttons.  

Friday, April 20, 2012

Detecting HTML5 Feature Support of your browser

Modernizr is an open-source JavaScript library that allows developers to detect whether the user's browser support a given HTML5/CSS3 feature or not.

With this knowledge, the developer can gracefully fallback to the native behavior of the browser in case a given HTML5 or CSS3 feature is not able to handle by the user's browser.


The following website demonstrates using Modernizr JavaScript Library to detect HTML5/CSS3 feature support and can be used to test how well your browser support HTML5/CSS3.
http://prasantha.com/projects/html5featuresupport/

To learn more about Modernizr, please refer to my previous post or Modernizr website.

Saturday, January 21, 2012

HTML5 - Details

The aim of the element is to provide native support for a feature common on the Web—a collapsible box that has a title, and more info or functionality hidden away.

The HTML5 details element can be used to expand the relevant addional information and hide the content when needed. <details> element is accompanied with optional <summary> element. <details> is the wrapper for all the content we want to show and hide, and <summary> contains the summary and title of the section.

Currently, this feature only available on Chrome.

<details>

<summary>My Summary</summary>

<UL>
<LI>Content 1</LI>
<LI>Content 2</LI>
<LI>Content 3</LI>
</UL>

</details>

Tuesday, January 17, 2012

WCF 4.0 new feature - Default Endpoints

WCF 3.x services required at least one endpoint or you'd get an exception.
WCF 4.0 comes with default endpoints. Windows Communication Foundation (WCF) looks at the configured mappings and decides on which binding to use for a particular based address.
If you have defined at least one endpoint, you won't get default endpoints.

WCF defines a default protocol mapping between transport protocol schemes (e.g., http, net.tcp, net.pipe, etc) and the built-in WCF bindings. The default protocol mapping is found in the .NET 4 machine.config.comments file and it looks like this:


<protocolMapping>

    <add scheme="http" binding="basicHttpBinding"/>
    <add scheme="net.tcp" binding="netTcpBinding"/>
    <add scheme="net.pipe" binding="netNamedPipeBinding"/>
    <add scheme="net.msmq" binding="netMsmqBinding"/>
</protocolMapping>

Sunday, January 15, 2012

Code Review Workflow with TFS 2012 and VS 2012

Visual Studio 2012 and Team Foundation Server 2012 introduce the feature called code review workflow and allow developers to request and perform code reviews using Team Explorer. A code review task also behaves as a work item and can be assigned to one or more developers as a review request(s).
The reviewer can accept or decline the review, and respond to any messages or queries associated with the code review, add annotations and more.

Once the code reviewer finished reviewing the code, he can assign it back to the requester. Visual Studio 2012 displays the code by using a “Diff” format, showing the original code and the changes made by the developer requesting the review. This feature enables the reviewer to quickly understand the scope of the changes and work more efficiently.

Saturday, January 14, 2012

HTML5 Feature Support Detection

None of the browsers currently fully supports HTML5. HTML5 browser support timeline for any given browser is also not clear. So, it is vital for HTML5 developers to know whether a specific HTML5 feature is supported on a given client’s browser or not.

Modernizr is a JavaScript library that can be leveraged by developers to detect whether a given HTML5 feature is supported on the client’s browser or not. So, Modernizr can be very useful in developing HTML5 applications.

These are few ways HTML5 developers can use Modernizr in their HTML5 development efforts.

1. Modernizr.[HTML5 feature name] returns true or false for a given HTML5 feature and developers can write program logics accordingly.

<!doctype html>
  <html>
   <head>
     <title>Modernizr Basics</title>
     <script src="scripts/modernizr-2.0.6.min.js"></script>

       <script>

          if (Modernizr.localstorage) {
              // Use Local Storage
          } else {
             // Do not use Local Storage
          }
         </script>

     </head>

  <body>
  </body>
</html>

2. Modernizr.load() allows developers to load different scripts based on whether a given HTML5 feature is supported in the client’s browser or not.


Modernizr.load({

     test: Modernizr.geolocation,
     yep : 'Script1.js',
     nope: 'Script2.js'
});

test: The Modernizr property you want to detect.

yep: The location of the script you want to load if the test succeeds. Use an array for multiple scripts.
nope: The location of the script you want to load if the test fails. Use an array for multiple scripts.
3. Modernizr.[HTML5 feature name]? can be used to implement fallback behavior if the browser does not support given HTML5 feature.
    var audio = new Audio();
    audio.src = Modernizr.audio.ogg ? 'background.ogg' :
    Modernizr.audio.mp3 ? 'background.mp3' :
    'background.m4a';
    audio.play();

Friday, January 13, 2012

Silverlight 5 - Double Click and N-Click Support Edit

Silverlight 5 has introduced the concept of a click count. This works for both the left and right mouse buttons. This can be accomplished by the ClickCount property of the MouseButtonEventArgs class. This property tells you how many times the user has rapidly clicked the mouse button. 

XAML

<Grid x:Name="LayoutRoot" Background="White">
<Rectangle x:Name="ClickRectangle" Height="85" Width="93"
   HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,40,0,0"
   Stroke="Black" StrokeThickness="1" Fill="#FFE82A2A"
   MouseLeftButtonDown="RectMouseLeftButtonDown" />
</Grid>


C# Source Code

private TimeSpan _clickDelay = TimeSpan.FromMilliseconds(300);
private int _clickCount = 0;
private DispatcherTimer _timer = new DispatcherTimer();

void RectMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// This code would never allow for a triple click

//if (e.ClickCount == 2)

// MessageBox.Show("Double click!");

//else if (e.ClickCount == 3)

// MessageBox.Show("Triple click!");

_clickCount = e.ClickCount;

    if (e.ClickCount >= 2 && !_timer.IsEnabled)
   {
        // wait to see if we get a triple click
       _timer.Interval = _clickDelay;
       _timer.Tick += TimerTick;
       _timer.Start();
     }
else if (e.ClickCount < 2)
    {
      _timer.Stop();
    }
}
private void TimerTick(object sender, EventArgs e)
{
     _timer.Stop();
    _timer.Tick -= TimerTick;

      if (_clickCount == 2)
      OnRectDoubleClick();
      else if (_clickCount == 3)
      OnRectTripleClick();
}

private void OnRectDoubleClick()
{
    MessageBox.Show("Double Click!");
}

private void OnRectTripleClick()
{
    MessageBox.Show("Triple Click!");
}

Saturday, December 3, 2011

HTML 5 async attribute

Async attribute can be used to load an external file and allows developers to load the file asynchronously. So, this means async attribute load the script in the background as soon as script is available without causing other page elements to delay while it loads.

<script async src="Script.js" onload="Init()"></script>

async attribute would benefit the user experience if the script is loaded as soon as possible, rather than after the page loads. So, this attribute will speed up the web by loading script asynchronously.

Saturday, November 12, 2011

ASP.NET vNEXT - Strongly Typed Data Controls

The next release of ASP.NET provides the ability to have strongly-typed data templates on data controls and introduces new property called "ModelType". This property has two expressions: Item and BindItem. And, also provides full Intellisense and compile-time checking support.

This means developers who used Eval() and Bind() helper methods to bind data into a control,

First Name: <%# Eval("FirstName") %><br />

   <asp:TextBox ID="firstName" runat="server" Text='<%# Bind("FirstName") %>' />

can use the property called "ModelType" on data controls introduced in ASP.NET vNEXT as below:

   <asp:TextBox ID="firstName" Text='<%# BindItem.FirstName %>' runat="server" />

Monday, September 19, 2011

ASP.NET MVC 4 Developer Preview for Visual Studio 2010

Microsoft has released MVC 4 Developer Preview for Visual Studio 2010 and available to download from ASP.NET MVC 4 Developer Preview. ASP.NET MVC 4 can be installed and run with ASP.NET MVC 3 side-by-side.

Software Requirements:

1. .NET 4.o
2. Visual Studio 2010 SP1 or Visual Web Developer Express 2010

New features:

1. Enhanced ASP.NET MVC 4 project template allows you to create more modernized websites. The size of website is adjusted according to screen resolution.
2. Mobile project template - Develop web applications that can run on any phone. The MVC4 mobile template is based on JQuery Mobile framework.
3. Enhanced support for asynchronous methods.