Friday, 12 October 2012

Entity Framework 6 Asyc- Is this the best feature yet?





Entity Framework 5 was long awaited by the developer community and not without its reasons.

EF (as the nick name goes), version 5 which is available on NuGet, introduced a host of features which immediately made it a hot cake with the Enterprise Developers looking to shed some weight off their shoulders in terms of Rapid ORM Prototyping and Application Development:

Some of the nicer ones being-

·         Enum support allows you to have enum properties in your entity classes. This new feature is available for Model, Database and Code First.

·         Table-valued functions in your database can now be used with Database First.

·         Spatial data types can now be exposed to Model using the DbGeography and DbGeometry types. Spatial data is supported in Model, Database and Code First.

What's more, EF5 automatically detects the database engine depending upon the development environment for the creation of new databases including the ability to make use of enum properties in entity classes. The framework also adds tables to the existing database if the target database doesn't contain any tables from the model [Cool!]

For Application Architects and Designers, the designer included with Visual Studio 2012 consist of new features such as DbContext code generation, multiple-diagrams per model, table-valued functions in addition to batch import of stored procedures which allows multiple stored procedures to be added during model creation. The new models created using the designer will generate a derived DbContext and POCO classes by default.

However, For enterprise developers, particularly working with performance and database intensive applications and NOSQL Databases all the time, a feature which has been long sought is the Task-based async - Allowing EF to take advantage of .NET 4.5. async support with async queries, updates, etc.

According to Microsoft, EF6 will provide support for async and can be implemented either using SaveChangesAsync() or ExecuteSqlCommandAsync() methods.


This will also enable developers to perform async operations on IQueryable (IQueryable<T>) operator and can be implemented using FindAsync() and SingleAsync() extension methods. 

Moreover, developers will be able to make use of ToListAsync() method to execute the code.


So What does this mean?

Distributed and Asynchronous programming has long been the holy grail for coders working on distributed, fault-tolerant applications that respond in real-time and never stop or halt.

With task based async now a reality with Entity Framework Users, it simply means more power to create better fault-tolerant applications, rapidly without worrying about the underlying Database schema changes.

Here is how the async version of SaveChanges looks in an ASP.NET MVC controller action:

[HttpPost]
public async Task<ActionResult> Edit(Thing thing)
{
    if(ModelState.IsValid)
    {
        _db.Entry(thing).State = EntityState.Modified;
        await _db.SaveChangesAsync();               
        return RedirectToAction("Index");
    }
    
    return View(thing);
}

The new IQueryable operators are async versions of operators that materialize a concrete result. For example, finding a single entity:

[HttpGet]
public async Task<ActionResult> Edit(int id)
{
    var model = await _db.Things.FindAsync(id);
    // or
    var model = await _db.Things.SingleAsync(t => t.Id == id);

    return View(model);
}

Also forcing execution with ToList:

public async Task<ActionResult> Index()
{
    var model = new HomeIndexViewModel();         
    model.Things = await _db.Things.ToListAsync();

    return View(model);
}

Getting an application up and running with EF 6 (including migrations) is slightly challenging, but I've found the easiest approach is to msbuild the Nuget.proj file in the NuGet directory, then adding the NuGet\bin\debug directory as a custom local NuGet repository and adding references to EF 6 via NuGet. I also had to register all the EF assemblies for verification skipping with sn -Vr.


EF 6 will be the next release after the completion of EF5 and Visual Studio 2012 release. 
Here is the download link: http://entityframework.codeplex.com/wikipage?title=Roadmap

WPF/Silverlight: Step By Step Guide to MVVM


MVVM is the short form for Model-View-ViewModel pattern widely used in WPF/Silverlight programming. This design pattern was introduced by John Gossman primarily for segregation and easy testability of View, ViewModel and Model. 





Let me first explain the three parts of MVVM

Model

Model as we all know represents the data layer. 

View

View represents the UI or the looks. 

View Model

View Model is the middle man and its responsibility is to tweek the data from model in such a way that it can be consumed by the View. For some people MVVM is a steep learning curve. Let me assure you its very easy if you keep four thing in mind. You can also call these four steps as the GURU MANTRA of MVVM



1) Try to have minimum code behind. That is your View.xaml.cs is supposed to have almost no code. Not even event handlers. This does not mean absolute zero code is a must, what I mean to say is that we should have minimum code behind. An exception would cases like where the logic is pure View oriented (and is very specific to that view only) and has nothing to do with ViewModel or Model or evenother Views of same ViewModel. For example on mouse over you want to slide in the tooltip, you may opt to do it in xaml.cs (of course you could have also done it by using trigger in xaml itself, but just cooking it as an example). There is no harm in having such code behind as it does not has anything to do with ViewModel or Model. Having said this, I would like to mention a few exceptions to the above rule. a) Dependency properties will always be part of code behind, hence it does not mean that you should avoid dependency property in MVVM. b) Sometimes you have to use third party controls which are not MVVM compliant. In such cases too you end up having some code behind.
2) All Events or actions should be treated as Command. Your question would be how to do that, my control has click event behavior but no command. My answer is there are several ways to do that. All this will be explained in detail in the rest of the article.
3) ViewModel is the DataContext of View. So neither View has instance ViewModel and nor does ViewModel has instance of View. Its incorrect and ugly to type cast View.DataContext to ViewModel. This will break your true MVVM model.
4) Design ViewModel and View independent of each other. This means that you must design the view by keeping in mind that if tomorrow the view is supposed to be replaced with another view (another look and feel), it should not require the ViewModel or model to change. Hence do not code anything in ViewModel that is specific to the view and also do not code anything in the view that is specific to ViewModel.

Homework before starting MVVM

1) Learn and clear concepts on Databinding. 2) Learn how to use Dependency Properties. 3) Learn use of Converters. 4) Last but not the least INotifyPropertyChanged. Let's start of with the basics first: Data Binding: Data binding is the process that establishes a connection between the application UI and business logic. If the binding has the correct settings and the data provides the proper notifications, then, when the data changes its value, the elements that are bound to the data reflect changes automatically. Data binding can also mean that if an outer representation of the data in an element changes, then the underlying data can be automatically updated to reflect the change. For example, if the user edits the value in a TextBox element, the underlying data value is automatically updated to reflect that change.Dependency Property: Dependency properties are just like normal CLR properties, but with a X-factor. The X-factor is that these properties have inbuilt support for data binding , animation, styling ,value expressions, property validation , per-type default calues. At the end of the day we need dependency properties to be able to save state of UI Elements. It won't be incorrect to say that dependency property will always be part of View's code behind and normal (CLR) properties are more likely to be part of ViewModel or Model. Just like there is a syntax to define CLR properties ( setter, getter ), there is a syntax for dependency property as well. The syntax is: 
public class MySampleControl : Control
{
    // Step 1: Register the dependency property 
    public static readonly DependencyProperty SpecialBrushProperty =
            DependencyProperty.Register("SpecialBrush", typeof(Brush),
            typeof(MySampleControl));

    // Step 2: Provide set/get accessors for the property 
    public Brush SpecialBrush
    {
        get { return (Brush)base.GetValue(SpecialBrushProperty); }
        set { base.SetValue(SpecialBrushProperty, value); }
    }
}
Please note that there are other ways to declare setter and getter for dependency properties. Also note that there several ways and combination to register a dependency properties like registering it as attached property (which in turn makes the dependency property inheritable its value down the visual tree. Example if you change the font of the Grid control, all its children also start showing the font of the parent Grid) etc. Converters: Data Conversion or Value Conversion is generally required when your view needs that data to be slightly tweaked from what it is currently. For example, in the view you want to show traffic light kind of signals based on the state of your project. That is green if your project is from 8 to 10, yellow if its rating is 5-7 and red if it’s less. Here there is no point keeping a variable corresponding to the color in your ViewModel, looks ugly. Here the showing project rating as color is a pure View requirement. Tomorrow if this view is to be replaced with another view where you show project rating as number, your color variable will turn out to be a complete waste. So how do you do that, solution is simple use Value converters, Value converters are purely part of View, it’s the view who wants the color to be green, yellow or red and ViewModel doesn’t care about the color. A value converter must derive from IValueConverter or IMultiValueConverter(in case you have multiple values to be used as input. Like in the traffic light example, let’s suppose your green color is to be shown when project is healthy and deadline is within acceptable limit. So we have two inputs, rating and deadline). 
[ValueConversion(typeof(Project), typeof(Brush))]
public class ColorConverter : IValueConverter
{

    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        Project project = (Project)value;
        if (project.Rating >= 8)//its healthy if rating is 8 to 10
              return new SolidColorBrush(Colors.Green);
        else if (project.Rating >= 5) )//its ok if rating is 5 to 7
              return new SolidColorBrush(Colors.Yellow);
        else //less its unhealthy
              return new SolidColorBrush(Colors.Red);
    }    

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return null;
    }
}
INotifyPropertyChanged: INotifyPropertyChanged has been there since Winform arena. It’s not a new concept in WPF/Silverlight. It’s an interface that you would like to implement in your ViewModel to notify you View that something got changed. Observable Collection and Dependency Property are some which have inbuilt notification mechanism. For such properties you may not require to raise the notification through code. 
public class SomeViewModel : ViewModelBase, INotifyPropertyChanged
{
     ….
     ….
    private Module _SelectedModule;
    public Module SelectedModule
    {
            get
            {
                return _SelectedModule;
            }
            set
            {
                _SelectedModule = value;
                RaisePropertyChanged("SelectedModule");
            }
    }
    …
    …
    #region INotifyPropertyChanged 
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
    }
    #endregion 
Coming back to the real thing, lets start of with the Model: Rest of the post, I shall explain by means of the a demo application for displaying employee information: Model: As the name suggest, it holds the data's model. Some people prefer to call model as data model. All your database select queries will first populate the data model which in turn will be used by ViewModel and View. As an example, I hereby demonstrate an Employee class. This class has properties corresponding to my data fields like name, notes, age etc. 
public class Employee : IDataErrorInfo, INotifyPropertyChanged
{
    #region Constructor
    public Employee(string id = "", string name = "", uint age = 0, string notes = "")
    {
        _id = id;
        _name = name;
        _age = age;
        _notes = notes;
    }
    #endregion

    #region Properties
    private string _id = string.Empty;

    public string ID
    {
        get { return _id; }
        set
        {
            _id = value;
            RaisePropertyChanged("ID");
        }
    }

    private string _name = string.Empty;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged("Name");
        }
    }

    private uint _age = 0;

    public uint Age
    {
        get { return _age; }
        set
        {
            _age = value;
            RaisePropertyChanged("Age");
        }
    }

    private string _notes = string.Empty;

    public string Notes
    {
        get { return _notes; }
        set
        {
            _notes = value;
            RaisePropertyChanged("Notes");
        }
    }
    #endregion

    #region IDataErrorInfo
    public string Error
    {
        get
        {
            return this[string.Empty];
        }
    }

    public string this[string propertyName]
    {
        get
        {

            string result = string.Empty;
            propertyName = propertyName ?? string.Empty;

            if (propertyName == string.Empty || propertyName == "ID")
            {
                if (string.IsNullOrEmpty(this.ID))
                {
                    result = "Employee ID is invalid. ID cannot be null or blank";
                }
                else if (System.Text.RegularExpressions.Regex.IsMatch(this.ID, "[/!@#?/}[}{ ]"))
                {
                    result = "Employee ID is invalid. ID cannot have special characters";
                }
            }
            else if (propertyName == "Name")
            {
                if (string.IsNullOrEmpty(this.Name))
                {
                    result = "Name is invalid. ID cannot be null or blank";
                }
            }
            else if (propertyName == "Age")
            {
                if (Age > 150 || Age < 0)
                {
                    result = "Age is invalid. Age should be between 0 and 150";
                }
            }

            return result;
        }
    }
    #endregion

    #region INotifyPropertyChanged
    [field: NonSerialized]
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}
In have inherited my model from IDataErrorInfo and INotifyPropertyChanged, but the same is not mandatory while designing your model. the same is done for data validation implementation and not MVVM. There is not much to explain in the model, lets proceed to the next level ViewModel. ViewModel: In the beginning of this blog I had mentioned that ViewModel is nothing but DataContext of View. Since ViewModel's responsibility is to play mediator between View amd Model, it will always have an instance of Model class and to reflect change in model, it will notify View via notification (INotifyPropertyChanged etc) or databinding. All Commands of the View are processed/handled here. Keep in mind that a ViewModel may have multiple views, so never code anything which is specific to a given view here. Considering our example for Employee, in our view we have list of employees on the left side and selected employees details on right side, so our viewModel which is supposed to be DataContext of View, must provide list of employees and a property to represent selection. Hence we end up having two properties in our viewModel, Employees and SelectedEmployee. 
    public class EmployeeListViewModel : INotifyPropertyChanged
    {
        public ObservableCollection Employees { get; private set; }

        public EmployeeListViewModel()
        {
            Employees = MVVMDemo.DataHelper.EmployeeDataHelper.CookEmployeesData();
        }

        private Employee _SelectedEmployee;
        public Employee SelectedEmployee
        {
            get
            {
                return _SelectedEmployee;
            }
            set
            {
                _SelectedEmployee = value;
                RaisePropertyChanged("SelectedEmployee");
            }
        }

        #region INotifyPropertyChanged
        [field: NonSerialized]
        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
ViewView is the look and feel. View is represented by xaml and its xaml.cs files. All your animations, decorations, themes, controls etc. sit here. The view is to be coded keeping in mind that tomorrow if you want to display your data in a different way, it should not require you to touch the ViewModel or Model at all. For example if you want to display you list of employees in a datagrid or listbox or tree or even tabs, it should not be a matter of concern for you ViewModel or Model, it’s purely the job of View to change the look and feel because at the end of the day it’s the same data that has to be presented in slightly different way. In our example of Employee list, View has a ListView of left side and selected employees details are displayed on the right side. So for this we have a xaml and xaml.cs in place. But the xaml.cs hardly has anything significant; hence code for it can be ignored for now. 


Working with Entity Framework as JSON Objects


Few months back, Henrik Nielsen wrote a great post on how to return JSON from ASP.NET Web API using JSON.NET on the msdn blog.

With Entity Framework rapidly becoming a choice of ORM framework for most enterprise scale applications (I also have my reservations using NHibernate for enterprise development, but let's just focus on EF for now), I’ve run into issues with serializing Entity Framework objects to JSON  using JSON.NET, from the ApiController over WCF.

After a bit of digging and delving, I discovered that the problem in this case lies in the lazy loading with EF, which causes circular reference between the objects. 

(e.g. “Self referencing loop detected for type (…)” when using JSON.NET and "A circular reference was detected while serializing an object of type (…)” when using JavaScriptSerializer,  and so on and so forth)


The fundamental problem is the same though and here is a look at the workaround I made to get my EF objects serialized to JSON objects.

Let's try to reproduce the Self-referencing loop/error first.

We begin by defining two models:


public class Url
 {
     public int UrlId { get; set; }
     public string Address { get; set; }
     public string Description { get; set; }
     public string Uid { get; set; }
     public virtual List<Tag> Tags { get; set; }
 }
 public class Tag
 {
     public int TagId { get; set; }
     public string Name { get; set; }
 }


...and here is the DBContext:


public class UrlzipContext : DbContext
 {
    public DbSet<Url> Urls { get; set; }
    public DbSet<Tag> Tags { get; set; }
 }

Let's look at the ApiController Code:


public class ValuesController : ApiController
  {
  DbContext db = new DbContext();
  // GET /api/values
  public List<Url> Get()
  {
   var urls = db.Urls.Include("Tags").ToList();
   return urls;
  }
}


Trying to return a simple Url from the ApiController, we’d get the circular reference error as explained above ( which internally stems from the underlying serializer class being used, JSON.NET in this case )

Here is the pic depicting the error:





And this is where the solution we could use steps in.

Instead of letting the default serializer use the complete Domain Model Object, we try to pass to the serializer only a selected set of values, in the form of an object which is different from the Domain Model object.

Here is the mod applied to the LINQ query in the ApiController:
[Why are domain models exposed to views anyways?]


var urls = db.Urls.Include("Tags").Select(i => 

      new { i.Uid, i.UrlId, i.Address, i.Description, i.Tags});


Hold on... this isn't over yet :-)

The modded code won't yet compile yet as our old Get() method returns a List, whereas in here we are dealing with IQueryable of Anonymous Type.

Unfortunately there is no simple way to return IQueryable of Anonymous Type or IEnumerable of Anonymous Type from an ApiController method. 


So we’ll mod the method signature too, so that public dynamic Get() becomes


public dynamic Get()
{
 var urls = db.Urls.Include("Tags").Select(i => 
    new { i.Uid, i.UrlId, i.Address, i.Description, i.Tags});
 return urls;
}



That's about it. Now we get our EF objects serialized to JSON with JSON.NET
Finally, here is something for religious MVC followers.

If you don't like to give up on the MVC mandate of programming, then instead of using selective values or returning anonymous objects to the view, you could instead create a custom type, and effectively have a ViewModel intact.

Cheers!


Windows 8 inspired TileGrid.


This week we discuss an interesting new Metro-Style control: the Windows 8 inspired TileGrid. 

This control provides layout logic, user interaction and nice animations that mimic the look and feel of the Win8 start menu. This control is great to use as a customizable navigation hub for your application that users will be familiar with. Here are some initial screen shots of this control:





Dragging a tile onto a group separator:




To use this control start with a TileGrid tag and populate it with one or more TileGroup objects which in-turn can be populated with Tile instances. Here’s an example used to create the images above:




Here is a sample design implemented using the Tile Grid:





Windows 8: an arranged marriage of windows 7 and windows phone

Introduction:
Ever since Windows 8 was announced, it has been a hot topic of discussion primarily due of the fact that it sounded as a bold migration step from Microsoft for many technical and marketing reasons. People were not expecting company like Microsoft to put ASP.Net, WPF, Silverlight on the backseat and give way to open source technologies like HTML 5 and JavaScript. But we all must understand that to bring a revolutionary change, bold steps are a must. 

First day of marriage:
I recently downloaded Windows 8 Release Preview as I was planning develop a Metro styled application for one of my clients. Please note Metro-styled applications can only be developed on Windows 8 operating system, there is no virtual or simulator available on windows 7 or prior versions to support Metro styled application development. As expected the first impression was that it has great looks but navigation was a pain, simply because we(including myself) are so accustomed to existing style of windows. But let me tell you that once we get comfortable with the new way of navigation, it will be all fine.


Cultural shock on honeymoon:
Not all honeymoons are pleasant. At times you need to spend some time understanding each other. Since we users are so comfortable with existing layout of windows, it become a bit irritating to find out how to perform some basic tasks like :

  • How to close the application, as my metro styled application doesn't shows the close button?
    Solution: You can close your application by holding the application at the top and then dragging it towards the bottom of the screen or by pressing ALT-F4.
  • Where's the start menu?
    Solution: Your start menu is now a complete screen which becomes visible when you take your mouse to the left bottom corner of your screen. In fact all four corners of the screen now have something for you. they are now better known as hot corners.
  • Why was my application suspended when I just navigated to another application?
    Solution: My application was suspended because it was a metro-styled application. A metro-styled application is different from normal desktop application. When the window is not active, it either goes to suspended or closed state.




  • Why is my right click not working?
    Solution: Since windows 8 is designed to behave more like a smartphone or tablet than a PC, it seems to be a deliberate attempt to replace it with pinning. The items will get pinned when you right click.
  • How do I shutdown?
    Solution: Since windows 8 is designed to behave more like a smartphone or tablet than a PC, simply going to sleep when it’s not being used. If you do want to shut down, or have a need to restart, open the Charms Bar, select Settings, and then the Power button, which will reveal the Shutdown and Restart commands.
and many more... however once you ready to accept the fact windows 8 is an OS more for smartphone or tablet than a PC, you will find things coming in smooth.

Is it a love marriage or arranged marriage:
Now lets us look into the two parties that are getting married: Windows Phone and Windows 7.
A windows phone application run as if they are running on an OS that cannot do multitasking (except for music player and all). If you switch from one application to another, the first one goes to sleep. Similarly on Windows 7 or any other desktop OS, you open several application and each continue to do the task they we performing until its complete, irrespective of the fact that its on topmost window or not. you are downloading, playing game and listening to music at the same time.
Windows 8 is neither a complete smartphone OS nor a complete desktop OS. Its something which is in between of the two and slightly biased towards smartphones. Metro style based application behave the way Windows Phone applications behave and desktop applications behave the way a normal win32 application behave. So in short its an arranged marriage. It supports both Win32 applications (better known as desktop applications) and WinRT (metro styled applications). 

Desktop applications are here to stay:
Metro styled application are a good fit for small to medium sized applications that are complete in themselves. It the beginning of metro-styled applications but not the end of desktop applications. Both will continue to be there and live side by side. Big enterprise applications and distributed applications will continue to be desktop applications. Its not easy to imagine a metro styled application replacing them anytime soon. Even Visual Studio 12 RC is not metro styled application. It would make debugging an application using visual studio impossible as visual studio will go into suspended mode when debugging application gets launched.

Conclusion:
Windows 8 is bold but a necessary move by Microsoft. It might not be a hit as it neither a complete smartphone OS nor a complete desktop OS, but it is the soldier who will make the way for next generation. This will make the future of Windows 9 brighter and comfortable. We hope that Microsoft will WinRT more real-time (than runtime).