Rajnish Noonia

Author: Rajnish Noonia

  • Asp.Net MVC flavours

    The main purpose of the MVC (Model, View and Controller) architecture is to make separation of the business layer (logic) and the application layer (data)  from the presentation layer to the user. Model-View-Controller is a software pattern for achieving isolation between different application components. Its always desirable for software applications (especially web-based applications) that there must be clear separation between business logic and the user interface. A model represents the state of a particular aspect of the application. A controller handles interactions and updates the model to reflect a change in state of the application, and then passes information to the view. A view accepts necessary information from the controller and renders a user interface to display that information. Over past few years many version of ASP.Net MVC were release moving towards more and more mature framework for web development.Below is brief comparison of features release in each version

    MVC 5 – October 2013

    • Bootstrap replaced the default MVC template.
    • ASP.NET Identity for authentication and identity management.
    • Authentication Filters for authenticating user by custom or third-party authentication provider.
    • With the help of Filter overrides, we can now override filters on a method or controller.
    • Attribute Routing is now integrated into MVC 5

    MVC 4 – August 2012

    • ASP.NET Web API, a framework that simplifies the creation of HTTP services and serving a wide range of clients.
    • Follow to create your first ASP.NET Web API service
    • Adaptive rendering and other look-n-feel improvements to Default Project Templates.
    • A truly Empty Project Template.
    • MVC4 also uses Razor View Engine as a default view engine with some new features like condition attribute and ‘Tilde slash’
    • Based on jQuery Mobile, new Mobile Project Template introduced.
    • Support for adding controller to other project folders also.
    • Task Support for Asynchronous Controllers.
    • Controlling Bundling and Minification through web.config.
    • Support for OAuth and OpenID logins using DotNetOpenAuth library.
    • Support for Windows Azure SDK 1.6 and new releases.
    • MVC4 provides better support for Jquery like Jquery Mobile
    • Client side validation, Jquery validation and enhanced support for asynchronous methods
    • Supports many new features for mobile apps and also provides new mobile project template and default templates are refreshed and modernized

    MVC 3 – January 2011

    • New Project Templates having support for HTML 5 and CSS 3.
    • Improved Model validation.
    • Razor View Engine (.cshtml for c# and .vbhtml for Visual Basic) introduced apart from Web Forms view engine (.aspx)
    • Having support for Multiple View Engines i.e. Web Forms view engine, Razor or open source.
    • Controller improvements like ViewBag property and ActionResults Types etc.
    • Unobtrusive JavaScript approach, Ajax and Client side Validation, Jquery Validation and JSON binding support
    • Chart, WebGrid, Crypto,WebImage, WebMail Controls
    • Improved Dependency Injection with new IDependencyResolver.It provides powerful hooks with Dependency Injection and Global Action Filters
    • Partial page output caching.
    • TempData, ViewData ,ViewBag
    • Supports not only Master Page but also Layout Page

    MVC 2 – March 2010

    • MVC 2 uses only Web Forms view engine (.aspx) as a default View Engine.
    • (HTML Syntax) Web Forms view engine syntax: <%=Html code %>
    • TempData, ViewData
    • Jquery support is Good
    • Supports only Master Page
    • Client-side Validation and Asynchronous controllers
    • support controllers to process requests asynchronously
    • Supports validations using the RangeAttribute, RequiredAttribute, StringLengthAttribute, and RegexAttribute attributes.

    MVC 1 – March 2009

    MVC CTP – December 2007 

    * Notes

    • View Engine is responsible for rendering of the HTML code from your views to the browser.
    • In ViewData, dictionary of objects are accessible via strings as keys
    • ViewBag was added in the C# 4.0 which uses the dynamic feature that allows to add properties of an object dynamically . We can say that ViewBag = ViewData + dynamic feature around the ViewData dictionary
  • Prism Navigation – ViewModel first

    Navigating to view using prism navigation service is straight forward and there are lot of examples on web around this.With MVVM i always found ViewModel first approach as best because of lot of reasons, some of them are

    • With MVVM, ViewModels is your application
    • No threading issues as you will always create view models which can be created on any thread.
    • More responsive , you are not dealing with dispatcher context to create views and let WPF system decide when to create views.
    • No Memory leaks, The life cycle of views is controlled by WPF system in most efficient way
    • More testable application, Since you app lives in view models and they don’t have UI beasts,
    • And lot more..

    This post cover a small trick to implement the ViewModel first navigation using Prism 5.0 for WPF.

    1. What ever IoC you are using (the code is based on StructuralMap) expose the RegisterForNavigation<T> method and from module initialization, register interface of viewModels participating in navigation process. The RegisterForNavigation<T> will look like

    public static void RegisterTypeForNavigation<T>(this ConfigurationExpression reg)
    {
    reg.For<object>().Use(() => ServiceLocator.Current.GetInstance(typeof(T)))
    .Named(typeof(T).FullName);
    }
    

    And some where in module initialization you call this method

    configurationExpression
    .RegisterTypeForNavigation<ICustomerDetailViewModel>();
    

    And to navigate to this view model just use

    var parameters = new NavigationParameters { { "Activity", SelectedActivity }, { "ColumnName", columnName } };
    var uri = new Uri(typeof(ICustomerDetailViewModel).FullName, UriKind.RelativeOrAbsolute);
    regionManager.RequestNavigate(ShellRegions.Workspace, uri, parameters);
    

    And obviously some where in you data template definition there should a (DataTemplate) mapping which WPF uses to swap the view model with corresponding view (and set data context too)..

  • .Net Universe

    .NET Universe Poster

    A visual map of the entire .NET ecosystem — frameworks, tools, languages, runtimes and libraries — all in one poster. The original PDF version is no longer available for direct download but the poster content is captured above.

  • Attached Behaviors Memory Leaks

    “Behavior is the base class for providing attachable state and commands to an object. The types the Behavior can be attached to can be controlled by the generic parameter. Override OnAttached() and OnDetaching() methods to hook and unhook any necessary handlers from the AssociatedObject.”
    If you using of the behaviors or trigger actions and these subscribe internally on events you’re in trouble. The memory used by them is never released. And could held lot of objects including views in memory causing memory leaks.

    “When you subscribe to an event the event source ends up with a hard reference to the event handler. This creates a situation where the event handler cannot be cleaned up as long as the event source exists.”
    So to unhook events you probably write code in OnDetaching methods however a behavior might not detach when you expect it to and vice versa, leaving added event handler on the control to survive GC. OnDetaching is only called when you explicitly remove behaviour.
    The solution:
    The OnAttached is called when XAML parser parses XAML and creates instance of behaviour and adds this to BehaviorCollection of target control which is exposed as DependencyAttached property. However when view is disposed, the collection (Behavior collection) was disposed of, it will never trigger OnDetaching method. If the behaviour is not properly cleanup it will not be collected by GC and will also hold BehaviorCollection and other behaviors in that collection. The behaviours are designed to extend AssociatedObject, as long as you are subscribing to AssociatedObject events its fine as the AssociatedObject (publisher) will die and your behaviour will be collected by garbage collector.

    Use BehaviorBase (see code below) to avoid memory leak from behaviours. The same technique can also be used for triggers.
    Drive all your behaviors from BehaviorBase class and override OnSetup and OnCleanup methods. OnSetup is triggered when behaviour explicitly is attached to already loaded object at runtime or when object is loaded.
    BehaviorBase

     
    public abstract class BehaviorBase<T> : Behavior<T> where T : FrameworkElement
    {
    private bool _isSetup = true;
    private bool _isHookedUp;
    private WeakReference _weakTarget;
    
    protected virtual void OnSetup() {}
    protected virtual void OnCleanup() {}
    protected override void OnChanged()
    {
           var target = AssociatedObject;
           if (target != null)
           {
                  HookupBehavior(target);
           }
           else
           {
                  UnHookupBehavior();
           }
    }
    
    private void OnTarget_Loaded(object sender, RoutedEventArgs e) { SetupBehavior(); }
    
    private void OnTarget_Unloaded(object sender, RoutedEventArgs e) { CleanupBehavior(); }
    
    private void HookupBehavior(T target)
    {
           if (_isHookedUp) return;
           _weakTarget = new WeakReference(target);
           _isHookedUp = true;
           target.Unloaded += OnTarget_Unloaded;
           target.Loaded += OnTarget_Loaded;
           SetupBehavior();
    }
    
    private void UnHookupBehavior()
    {
           if (!_isHookedUp) return;
           _isHookedUp = false;
           var target = AssociatedObject ?? (T)_weakTarget.Target;
           if (target != null)
           {
                  target.Unloaded -= OnTarget_Unloaded;
                  target.Loaded -= OnTarget_Loaded;
           }
           CleanupBehavior();
    }
    
    private void SetupBehavior()
    {
           if (_isSetup) return;
           _isSetup = true;
           OnSetup();
     }
    
    private void CleanupBehavior()
    {
           if (!_isSetup) return;
           _isSetup = false;
           OnCleanup();
    }
    }