MEF vs. Unity in composite application (Prism)

On April 27, 2011, in C#, Programming, by Akash Kava

This article describes differences between MEF and Unity which may help you in deciding which technology you must use while making composite application.

Both technologies are useful and easy to understand, and offer a rich set of features that can make integration of various software components very easy. However, both being little different in functioning they offer exact same level of features but choosing wrong one can lead to chaos.

So we will drill down to differences between their operations.

Unity

MEF

Unity creates new instance of type by default.

MEF creates singleton instance of type by default.

Unity does not require registration for classes. This means you can instantiate any other third party type.

MEF requires Export attribute to be specified on the class. MEF cannot create instance of third party type unless it defines Export.

Unity requires type registration in code for interface types.

No registration, simple Export attribute does it all.

Unity container can compose IUnityContainer property in the composed class where you can further access it easily in your own scope. This behavior is not useful for Plugin architecture as getting access to IUnityContainer may result in full access to your application.

MEF does not allow composition of CompositionContainer, which blocks access to MEF in your own scope if you do not have CompositionContainer. This is useful in Plugin architecture where third party code has limited access to your application. 

Unity offers injection method mechanism, that can define IUnityContainer parameter and get the unity container object, with which you can compose other private properties manually.

MEF can only compose public properties, this is dangerous as anyone can change public property and make application crash easily.

Inside your application’s framework code, Unity serves the best as it gives you full control over type hierarchy, lifecycle and allows you to utilize third party components easily without writing much of code. 

Inside your application, MEF will put lots of restrictions in which your framework can operate as it cannot easily compose third party components and it will force you to write numerous attributes in your code without which it will fail drastically.

Mostly, User Interface objects like your View, or UserControl or any UIElement can never be shared as no UIElement can have two parents at same time. So default behavior of Unity to create a new instance of type is very helpful.

Default behavior of MEF will create only one single instance of UI object, that will lead to trouble, not only that, if UI object is third party tool, MEF will not compose it. You can create multiple copies of exported type by specifying one more attribute called [PartCreationPolicy(Shared)], however it is very time comsuming and tedious to define this one every UI related type we create.

Unity does allow singleton objects, but for that you have to register an instance to the container.

MEF by default creates singleton object only.

Unity does not allow multiple registrations for same instance in same scope sharing same interface but different type.

MEF allows multiple singleton objects of different type sharing same interface.

Unity works best for MVVM, as composing user interface parts can be very easy with unity.

MEF does not work great with MVVM as it will create singleton objects that will behave strangely in runtime and lead to UI failure.

Unity is not good for Modularity, as composing IUnityContainer will offer more control of unity lifecycle to third party modules.

MEF is good for Modularity, as it will not allow modification of composition thus offering great deal of security between modules.

So, to develop a framework, MVVM Crud application and a UI framework, Unity is the best.

To expose some functionality of your application for third party modules to register and access limited functionality, MEF is the best.

 
 

Following is outline of how your application should be,

Unity Container must compose and manage your application’s framework, UI and MEF modules.

MEF will only expose limited functionality from Unity Container to third party modules.

No module, through MEF should have access to unity container at all.

Thank you for reading this article, please put your suggestions below in the comment. I do not intend to make any specific rules and regulations here but I am suggesting the architecture based on the differences I have outlined.

Share
Tagged with:  

UI Atoms 1.7.5 Released

On April 3, 2011, in C#, Programming, RIA, Technology, by Akash Kava

We are happy to announce new release of UI Atoms 1.7.5 with following new features.

  1. New AtomDataForm Control
  2. Tabs in AtomForm and AtomDataForm
  3. Lambda Binding Extensions

Introducing new Control AtomDataForm

AtomForm did support UI Validations, however Microsoft RIA Services Client has some inbuilt validation and support for IEditableObject. So we created a new AtomDataForm that supports RIA Services validation and IEditableObject support.

  1. AtomDataForm supports object with IEditableObject interface and fires event for BeginEdit, CancelEdit and EndEdit
  2. AtomDataForm displays items in read only mode unless Edit button is clicked
  3. After edit button is clicked, Save and Cancel button appear for you to persist changes or cancel changes
  4. AtomDataForm contains UI Element (TextBox, ComboBox etc) as children, so you can easily define child ui element in your xaml as shown in sample below
  5. AtomDataForm supports Tabbed layout, for that you can insert your items within AtomDataFormTab as shown in example below
  6. Following sample illustrates Tabs, but you can also create simple user interface without tab as well
  7. You can also use AtomDataFormGroup to group items in to a headered group
  8. Every child element of AtomDataForm can be accessed in code behind file easily because they appear as a variables when you define x:Name property
  9. AtomDataForm supports CanChangeDataContext property, which is false when the form is in edit mode
  10. You can easily reuse any third party control within AtomDataForm, AtomDataFormGroup and AtomDataFormTab
AtomDataForm Sample
  1. <ns:AtomDataForm
  2.     Grid.Column="1"
  3.     DataContext="{Binding SelectedItem,ElementName=dataGrid}" >
  4.             
  5.     <!– 1st Tab–>
  6.     <ns:AtomDataFormTab Header="Default">
  7.                 
  8.         <TextBox
  9.             ns:AtomDataForm.Label="Name:"
  10.             Text="{Binding ProductName, Mode=TwoWay}"/>
  11.                 
  12.         <ns:AtomToggleButtonBar
  13.             ns:AtomDataForm.Label="Type:"
  14.             SelectedItem="{Binding ProductType,Mode=TwoWay}">
  15.             <sys:String>Product</sys:String>
  16.             <sys:String>Service</sys:String>
  17.         </ns:AtomToggleButtonBar>
  18.                 
  19.         <TextBox
  20.             ns:AtomDataForm.Label="Folder:">
  21.             <ns:AtomDataForm.CommandBox>
  22.                 <Button Content="…"/>
  23.             </ns:AtomDataForm.CommandBox>
  24.         </TextBox>
  25.                 
  26.     </ns:AtomDataFormTab>
  27.             
  28.     <!– 2nd Tab–>
  29.     <ns:AtomDataFormTab Header="General">
  30.                 
  31.         <TextBox
  32.             ns:AtomDataForm.Label="Email:"  
  33.             Text="{Binding Email, Mode=TwoWay}"/>
  34.                 
  35.     </ns:AtomDataFormTab>
  36.             
  37.     <!– 3rd Conditional Tab–>
  38.     <!– This tab will be visible only if Product's
  39.     IsTypeService is true–>
  40.     <ns:AtomDataFormTab
  41.         Header="Service"
  42.         IsEnabled="{Binding IsTypeService}">
  43.                 
  44.         <TextBox
  45.             ns:AtomDataForm.Label="Service Details:"/>
  46.                 
  47.     </ns:AtomDataFormTab>
  48.  
  49.     <!– 4th Conditional Tab–>
  50.     <!– This tab will be visible only if Product's
  51.     IsTypeProduct is true–>
  52.     <ns:AtomDataFormTab
  53.         Header="Product"
  54.         IsEnabled="{Binding IsTypeProduct}">
  55.                 
  56.         <TextBox ns:AtomDataForm.Label="Product Details:" >
  57.             <ns:AtomDataForm.CommandBox>
  58.                 <Button Content="Search"/>
  59.             </ns:AtomDataForm.CommandBox>
  60.         </TextBox>
  61.                 
  62.     </ns:AtomDataFormTab>
  63.             
  64. </ns:AtomDataForm>

In above sample you can notice following things,

  1. Header property of AtomDataFormTab is displayed in the title section on the top
  2. AtomDataFormTab contains children and each child can have properties as below
    1. ns:AtomDataForm.Label displays label on left side
    2. ns:AtomDataForm.Description displays description on bottom
    3. ns:AtomDataForm.Title displays title on the top of control
    4. ns:AtomDataForm.CommandBox displays a UI Element on the right corner, usually a search button or expand button
  3. AtomDataFormTab supports IsEnabled binding, you can bind this property to show/hide the tab as shown in the example above
  4. Every child elemen of either AtomDataForm , AtomDataFormTab or AtomDataFormGroup supports Visibility and IsEnabled binding
    1. If Visibility is bound and it results in Collapsed then entire form item is not displayed
    2. IsEnabled binding can enable/disable the editable control

Following is screenshot of Tabbed AtomDataForm in edit mode

AtomDataForm

Introducing Lambda Binder Extensions

Writing binding expressions with conditions and converters can be very complex especially rewriting many and same logic at different classes. Now UI Atoms support, Lambda Binding Extensions which lets you do binding within the code without creating any complex IValueConverter implementation.

Bind Method Extension

Element Property Binding
  1. theForm.Bind(AtomDataForm.HeaderProperty,
  2.     () => string.Format("{0} ({1})",
  3.             productName.Text,
  4.             typeToggleButtonBar.SelectedItem
  5.         ));

This will bind theForm’s Header property to an expression that will combine properties of two different elements. And this will also automatically update when any of bound source or its property will change.

DataContext Property Binding
  1. theForm.Bind(AtomDataForm.HeaderProperty,
  2.     () => string.Format("{0} ({1})",
  3.             theForm.DataContext.Property("ProductName"),
  4.             theForm.DataContext.Property("ProductType")
  5.         ));

Assuming, we may not have property information at design time, but we know that DataContext will be set to an object containing properties, then we can write Property extension method as shown above.

BindVisibility Method Extension

Visibility converters are very frequent so we created a BindVisibility extension method that will let you specify a boolean expression that will be converted to Visibility on the fly.

BindVisibility Extension
  1. productTab.BindVisibility(
  2.     () =>
  3.         typeToggleButtonBar.SelectedIndex == 0);

These extensions can be used anywhere in any third party controls as well.

Download Now

Click here to download your free demo copy of NeuroSpeech UI Atoms 1.7.5

Share
Tagged with:  

Lambda Binder for WPF and Silverlight

On March 20, 2011, in C#, Technology, by Akash Kava

LambdaBinder class helps in creating complex binding expressions without having to create IValueConverter and IMultiValueConverter, it lets you write inline expresions with advanced binding scenarios.

Lets say, you have two TextBox for first and last name and you want a Title to be displayed as addition of both.

So lets say, you can write it as follow,

Adding Two Properties
title.Bind(TextBlock.TextProperty,
    () => firstName.Text + " " + lastName.Text);

Formatting Properties
title.Bind(TextBlock.TextProperty,
    () => string.Format("{0} {1}",
        firstName.Text, lastName.Text));

You can pass on the Linq expression to Bind extension method of LamdaBinder and that will convert and set binding so that anytime if firstName or lastName is modified, the title will be updated automatically.

Assuming I want some hypothetical visibility logic, for example, only if the firstName is entered, lastName should be visible.

Conditional Visibility Binding
lastName.Bind(TextBox.VisibilityProperty,
    () => firstName.Text.Length > 0 ? Visibility.Visible :
        Visibility.Collapsed);

You can also use this to avoid writing IValueConverters and do inline binding in code very easily.

Lambda Binder
public static class LambdaBinder
{

    public static void Bind(
        this DependencyObject dest,
        DependencyProperty destProperty,
        Expression<Func<object>> func)
    {
        MultiBinding b = new MultiBinding();
        b.Converter = new MultiDelegateConverter(func.Compile());
        LambdaBindingBuilder bb = new LambdaBindingBuilder(b);
        bb.Visit(func.Body);
        BindingOperations.SetBinding(dest, destProperty, b);
    }

}

public class LambdaBindingBuilder : ExpressionVisitor
{
    private MultiBinding multiBinding;

    private string lastPath = null;

    public LambdaBindingBuilder(MultiBinding mb)
    {
        this.multiBinding = mb;
    }

    protected override System.Linq.Expressions.Expression VisitMember(MemberExpression node)
    {
        PropertyInfo p = node.Member as PropertyInfo;
        if (p != null) {
            if (string.IsNullOrWhiteSpace(lastPath))
            {
                lastPath = p.Name;
            }
            else {
                lastPath = p.Name + "." + lastPath;
            }
        }
        FieldInfo f = node.Member as FieldInfo;
        if (f != null) {
            Binding b = new Binding(lastPath);
            b.Source = System.Linq.Expressions.Expression.Lambda<Func<object>>(node).Compile()();
            multiBinding.Bindings.Add(b);
            lastPath = null;
        }
        return base.VisitMember(node);
    }

    protected override System.Linq.Expressions.Expression VisitConstant(ConstantExpression node)
    {
        if (!string.IsNullOrWhiteSpace(lastPath)) {
            Binding b = new Binding(lastPath);
            b.Source = node.Value;
            multiBinding.Bindings.Add(b);
            lastPath = null;
        }
        return base.VisitConstant(node);
    }
}

public class MultiDelegateConverter : IMultiValueConverter
{
    private Func<object> func;

    public MultiDelegateConverter(Func<object> func)
    {
        this.func = func;
    }

    public object Convert(object[] values,
        Type targetType,
        object parameter,
        System.Globalization.CultureInfo culture)
    {
        return func();
    }

    public object[] ConvertBack(object value,
        Type[] targetTypes,
        object parameter,
        System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

 

LambdaBinder is part of UI Atoms suite. At NeuroSpeech, we do research on UI and we are coming up with more interesting featues in UI Atoms.

Please Click Here to download latest update of UI Atoms with AtomForm including Tabs in the form.

Share
Tagged with:  

Entity Framework and RIA Services do not allow Entities to be added/removed from cross containers. In order to move Entity from one DomainContext/ObjectContext to another DomainContext/ObjectContext, we need to recursively detach the object graph and attach it to other DomainContext/ObjectContext.

Object Graph

Single entity can be easily detached and attached from EntitySet where it belongs, but the problem comes when navigation properties of entity are not empty. Entity object along with navigation properties is called Object Graph because if you notice, navigation property’s navigation property will contain reference to same entity and that will result in endless recursive code for Detach/Attach.

An entity with the same identity already exists in the EntitySet

When you try to detach entity from old DomainContext/ObjectContext and attach it to DomainContext/ObjectContext, it may give you an error that entity with same identity already exists and it will throw an exception. In this case we will just simply reuse the existing entity instead of attaching the entity we have.

Entity cannot be attached to this EntityContainer because it is already attached to another EntityContainer

In case of ObjectGraph, your root level entity is already detached, but navigation properties are not detached, and while you try to attach your root level entity, it will throw same error for entities that exist in navigation properties.  Because detach method does not recursively detach every entity from navigation properties.

Attach/Detach Extension Methods

Finally after brainstorming little, I made following class that will allow you to recursively detach/attach object graphs from DomainContext. You can replace DomainContext to ObjectContext to use it inside Entity Framework.

DomainContext Extensions
  1. /// <summary>
  2. /// DomainContext Extensions
  3. /// </summary>
  4. public static class DomainContextExtensions {
  5.  
  6.     /// <summary>
  7.     /// Recursively Attaches entity loaded from Other DomainContext to
  8.     /// current specified DomainContext
  9.     /// </summary>
  10.     /// <param name="context">DomainContext where entity will be attached</param>
  11.     /// <param name="entity">Entity loaded from other DomainContext</param>
  12.     /// <returns></returns>
  13.     public static Entity Attach(this DomainContext context, Entity entity)
  14.     {
  15.         if (entity == null || entity.EntityState != EntityState.Detached)
  16.             return entity;
  17.  
  18.         Entity newEntity = entity;
  19.  
  20.         Entity[] list = new Entity[] { entity };
  21.         foreach (Entity c in context.EntityContainer.LoadEntities(list,
  22.             LoadBehavior.MergeIntoCurrent))
  23.         {
  24.             newEntity = c;
  25.             break;
  26.         }
  27.  
  28.         // recursively attach all entities..
  29.         Type entityType = typeof(Entity);
  30.  
  31.         // get all navigation properties…
  32.         Type type = entity.GetType();
  33.         foreach (var item in type.GetProperties())
  34.         {
  35.             if (entityType.IsAssignableFrom(item.PropertyType))
  36.             {
  37.                 Entity navEntity = Attach(context, item.GetValue(entity, null)
  38.                     as Entity);
  39.                 item.SetValue(newEntity,navEntity, null);
  40.                 continue;
  41.             }
  42.             if (item.PropertyType.Name.StartsWith("EntityCollection"))
  43.             {
  44.                 IEnumerable coll = item.GetValue(entity, null) as IEnumerable;
  45.                 List<Entity> newList = new List<Entity>();
  46.                 foreach (Entity child in coll)
  47.                 {
  48.                     newList.Add(Attach(context, child));
  49.                 }
  50.                 dynamic dcoll = item.GetValue(newEntity,null);
  51.                 foreach (dynamic child in newList)
  52.                 {
  53.                     dcoll.Add(child);
  54.                 }
  55.             }
  56.         }
  57.         return newEntity;
  58.     }
  59.  
  60.     /// <summary>
  61.     /// Recursively detaches entities from DomainContext, this
  62.     /// method detaches every navigation properties
  63.     /// of current Entity as well.
  64.     /// </summary>
  65.     /// <param name="context"></param>
  66.     /// <param name="entity"></param>
  67.     public static void Detach(this DomainContext context, Entity entity)
  68.     {
  69.         if (entity == null || entity.EntityState == EntityState.Detached)
  70.             return;
  71.         EntitySet nes = context.EntityContainer.GetEntitySet(entity.GetType());
  72.         nes.Detach(entity);
  73.  
  74.         Type entityType = typeof(Entity);
  75.  
  76.         // get all navigation properties…
  77.         Type type = entity.GetType();
  78.         foreach (var item in type.GetProperties())
  79.         {
  80.             if (entityType.IsAssignableFrom(item.PropertyType))
  81.             {
  82.                 Detach(context,item.GetValue(entity, null) as Entity);
  83.                 continue;
  84.             }
  85.             if (item.PropertyType.Name.StartsWith("EntityCollection"))
  86.             {
  87.                 IEnumerable coll = item.GetValue(entity, null) as IEnumerable;
  88.                 foreach (Entity child in coll)
  89.                 {
  90.                     Detach(context,child);
  91.                 }
  92.             }
  93.         }
  94.     }
  95.  
  96. }

Share
Tagged with:  

UI Atoms 1.5.8 Released

On January 11, 2011, in Programming, by Akash Kava

We are happy to announce new release of UI Atoms 1.5.8 with following new features.

UI Atoms for WPF 4.0

In this release of UI Atoms, we have a new library of dlls specially designed for WPF 4.0, which now includes support for Visual State Managers and renders everything in WPF 4.0 presentation. You can find Bin.Net4 folder inside WPF, that contains libraries only for WPF 4.0 version.

AtomForm Label Alignment for Silverlight and WPF

Silverlight-Form-Label-Alignment

AtomForm now provides following two properties,

  • LabelHorizontalAlignment property that can align the label horizontally in the form item.
  • LabelVerticalAlignment property that can align the label vertically in the form item.

Label Can now contain string or UI Element object

Rich Label Format
  1. <ns:AtomTextBox HorizontalAlignment="Stretch"
  2.                 Text="{Binding Path=ProjectName, Mode=TwoWay}" Width="Auto" >
  3.     <ns:AtomForm.Label>
  4.         <StackPanel Orientation="Horizontal">
  5.             <TextBlock>Name:</TextBlock>
  6.             <Image Source="/PrismTest;component/Images/Logo.png" Width="16" Height="16" />
  7.         </StackPanel>
  8.     </ns:AtomForm.Label>
  9. </ns:AtomTextBox>

Rich-Label-Silverlight-WPF-Form

 

Advanced Quick Form Designer

Typing Tags with all Bindings could be quite time consuming, where it involves moving items up and down, deleting and adding new Form Items. Advanced Quick Form Designer resolves all this problems by giving you state of art designer, which provides one quick grid to enter all necessary information. However the form designer works well even for existing forms, and you can generate entire new form by selecting some Type as well.

Advanced-Silverlight-WPF-Form-Designer

As you see, type of control can be changed that will represent the form item and corresponding binding property can be changed as well. Just with simple one click, you can move items up and down or delete them. You can add a new control that is defaulted to AtomTextBox at the top, you can change default control to add multiple one after another very easily. Also you can click “Generate From Type” to select any Business Object Type and generate a brand new form.

Generate-Form-From-Type-Silverlight-WPF

Selecting type will automatically generate form with its bindings.

Share
Tagged with:  

UI Atoms version 1.2.22 resolves Cascaded ComboBoxes issue in MVVM pattern. Advanced AtomForm is now capable of handling cascaded ComboBoxes with MVVM and it also integrates well with third party controls.

Recently we identified few issues with MVVM implementation in Silverlight regarding ComboBoxes. ComboBox looses its “SelectedValue” binding once the ItemsSource of ComboBox changes. This needed some workaround as well as Modifying DataForm is very painful as you may need very complex form designs in regular business applications.

1. Create Models

Lets assume we need to edit a Customer’s Country and City, as we change the Country the list of cities should change it. Problem with existing ComboBox and DataForm is, as soon as list of cities changes, ComboBox’s SelectedValue binding vanishes. So lets create Customer Model first.

 

MVVM-View-Models

Each of properties in CustomerViewModel raises PropertyChanged event for corresponding properties when modified.

When selected customer changes, SelectedCountry also changes and which changes Cities property, so in drop down we can display the list of cities of selected country.

Important:

Your SelectedCountry property, where you need Change of Selection event must not raise PropertyChanged event in “set” method as shown below…, however you may turn it off or on based on your UI behavior. WPF has no problem but Silverlight has issues and it works better if PropertyChanged event is not raised.

Selected Country Property
        public Country SelectedCountry
        {
            get
            {
                return _SelectedCountry;
            }
            set
            {
                _SelectedCountry = value;
                //if (PropertyChanged != null)
                //    PropertyChanged(this, new PropertyChangedEventArgs("SelectedCountry"));
                if (_SelectedCountry != null)
                {
                    Cities = _SelectedCountry.Cities;
                }
            }
        }

2. Create Master View

Master View control declares grid with two columns, left side displaying list of customers and on right side displaying details of the selected customer.

MainPage Master View Control
<UserControl x:Class="PrismTest.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ns="http://uiatoms.neurospeech.com/silverlight"
    xmlns:local="clr-namespace:PrismTest"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <local:ViewModelLocator x:Key="locator"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="400" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <ListBox
            DisplayMemberPath="Name"
            x:Name="list"
            SelectedItem="{Binding ViewModel.SelectedCustomer,Source={StaticResource locator}, Mode=TwoWay}"
            ItemsSource="{Binding ViewModel.Customers,Source={StaticResource locator}}" />
        <local:CustomerView
            Grid.Column="1" />
        <ns:AtomTraceView
            Grid.Row="1" Grid.ColumnSpan="2"/>
    </Grid>
</UserControl>

Lets analyze Bindings,

  1. ListBox’s ItemsSource is bound to ViewModel.Customers which returns list of available customers.
  2. ListBox’s SelectedItem is bound (two way) to ViewModel.SelectedCustomer.
Customer View Control
<UserControl x:Class="PrismTest.CustomerView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ns="http://uiatoms.neurospeech.com/silverlight"
    xmlns:local="clr-namespace:PrismTest"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <local:ViewModelLocator x:Key="locator"/>
    </UserControl.Resources>
    <ns:AtomForm DataContext="{Binding ViewModel.SelectedCustomer,Source={StaticResource locator}}">
        <ns:AtomTextBox Text="{Binding Name, Mode=TwoWay}"
                        ns:AtomForm.Label="Name:" />
        <ns:AtomComboBox ns:AtomForm.Label="Country:"
                         SelectedValuePath="CountryID"
                         DisplayMemberPath="Name"
                         ItemsSource="{Binding ViewModel.Countries,Source={StaticResource locator}}"
                         SelectedItem="{Binding ViewModel.SelectedCountry,Source={StaticResource locator}, Mode=TwoWay}"
                         SelectedValue="{Binding CountryID, Mode=TwoWay}"
                         />
        <ns:AtomComboBox ns:AtomForm.Label="City:"                          
                         SelectedValuePath="CityID"
                         DisplayMemberPath="Name"
                         ItemsSource="{Binding ViewModel.Cities,Source={StaticResource locator}}"
                         SelectedValue="{Binding CityID, Mode=TwoWay}"
                         />
    </ns:AtomForm>    
</UserControl>

Lets analyze the bindings,

  1. AtomForm’s DataContext is bound to SelectedCustomer of ViewModel, which comes from SelectedItem of Parent Control
  2. AtomTextBox’s  Text is bound to Name (of AtomForm’s DataContext’s binding) with Mode=TwoWay
  3. AtomComboBox
    1. ItemsSource is bound to ViewModel.Countries which returns list of countries.
    2. SelectedValue is bound to CountryID (of AtomForm’s DataContext’s binding) with Mode=TwoWay
    3. SelectedItem is bound to ViewModel.SelectedCountry, which triggers change of SelectedCountry property on ViewModel which changes list of cities.
  4. AtomComboBox (this is the one that’s tricky, normal ComboBox does not work here)
    1. ItemsSource is bound to ViewModel.Cities which returns list of cities of SelectedCountry.
    2. SelectedValue is bound to CityID (of AtomForm’s DataContext’s binding) with Mode=TwoWay

 

3. Cascaded ComboBox

You can see that the cascaded ComboBox work well with AtomForm and AtomComboBox and its easy to design AtomForm with MVVM with so much less code then that of DataForm and ComboBoxes.

Form

Please download the latest version of UI Atoms 2010 suite to try MVVM + AtomForm + Cascaded ComboBoxes.

Share
Tagged with:  

NeuroSpeech releases XamlGenerator 1.0

On September 28, 2010, in Programming, Technology, by Akash Kava

XamlGenerator is Code Behind source code Generator for Xaml.

Xaml Code Behind Generator makes it easier to generate Code Behind designer code from XAML, where code can be used at places where Xaml Services are not accessible.
Features

  1. Using XAML 2009 in Silverlight and WPF
  2. Reusing Xaml Business Pages in Silverlight and WPF
  3. Support for User Controls derived from any Control
  4. Using Complied code instead of BAML
  5. Improving speed of XAML runtime
  6. Using XAML to generate code to be used in ASP.NET, Server Core etc, where XAML Services are not available
  7. Generated code is pure .NET 2.0 compliant, and you can target xaml objects to run in earlier .NET version too.
  8. You can also create Xaml for WinForms and use it for your .NET 2.0 projects, however please notice, the features of WPF will not be available, it can only create object hierarchies based on XAML, but it can not give you binding etc features.
  9. x:Name support for Resources, very useful for MVVM Pattern
  10. Support for Custom Extension with Custom Code Generator

Xaml Code Generator

.Net 4 introduces Xaml Services that can load Xaml Object Trees and it provides great deal in terms of intellisense and code behind facilities, however this can only be used where Xaml Services are installed. Also it is quite painful to debug and hide the generated baml resources, that actually is quite easy to disassemble and view the source.
Xaml Code Generator can easily solve these problems by creating source code equivalent to loading object via Xaml Services. Instead, once generated, the performance of source code is quite faster then baml and xaml. Since ASP.NET and WinForms, code behind files did serve great support to link the UI and Code. However in WPF and Silverlight does not support simple references to code behind objects except events. There are work arounds, but we decided to create Xaml Code Generator that will solve lot of problems.

Benefits to WPF and Silverlight

  1. Xaml pages can now use x:Reference markup extension
  2. Xaml pages can support generic type parameters
  3. Xaml page can now derive from any control/panel
  4. Xaml can easily reference any expression that involves code behind operation including "this" keyword
  5. By using custom Xaml markup extensions, you can reuse Xaml between WPF and Silverlight

Known limitations with Xaml Code Generated files

  1. Control Templates and Styles must use respective WPF/Silverlight markup only
  2. No code behind files can be generated for Control Templates and Styles
  3. Xaml pages can not be used with Navigation Urls
  4. Instead code generated files are simply source code equivalent of Xaml, and they should be treated as .Net CLR Objects instead of Xaml Pages and there exists no equivalent baml resources

So how to use benefits of Code Generator as well as XAML

We recommend following pattern to make use of best of both the worlds

  1. Create Main Application Window/Page as regular Xaml
  2. Instead of User Controls, use Xaml derived from Equivalent controls, such as StackPanel, Grid etc, and use them in Main Window/Pages
  3. In this pattern, generated CLR objects of xaml will perform exactly same

Why Generate source code from XAML?

Xaml and Xaml Services are great, they give a huge benefit in terms of runtime model loading and behaviour. For larger systems, and for complex enterprise applications Xaml is perfect. But we still have lot of code in .NET 2.0 and applications that are still heavily dependent on the components that do not support Xaml Services.
Plus, shift of paradigm from code behind to view model is quite painful. Infact ability to use more code behind features is quite needed for current generation.
Debugging Xaml is quite painful still, we still have lot of logic that lies in functional code and there is little more time still before we reach to completely modelled code.
Here are few benefits outlined of generated code,

  1. View Model can be replaced by Code behind, as we can easily reference xc:This and xc:Ref extensions
  2. Debugging c# code can be easier which involves more complex UI designs
  3. Xaml Generated can generate anything, even non UI code
  4. You can even use Xaml Generator in your DSL tool

For more details, please visit, http://xamlgenerator.codeplex.com/

Share
Tagged with:  

This tutorial outlines how to customize UI Atoms’ AtomForm appearance and layout simply by customizing its ItemContainerStyle.

AtomForm is derived from ItemsControl, and ItemsControl declares ItemContainerStyle which can customize the template of individual items that are being displayed. UI Atoms give you complete freedom of how to change your look and feel very easily by just adding a simple template in your resource dictionary.

 

Create New Item Container Style

To do this, open your xaml page in the Expression Blend and right click on the AtomForm. And choose Edit Additional Templates, and Select Edit Generated Item Container (ItemContainerStyle) and then click on “Edit a copy…”

SelectItemContainerStyle

Then choose a location to keep your style in,

ChooseStyle

Once the style editor is open, right click on “Style” and click on “Edit Template” and then click on “Edit Current”

ChooseCurrent

Now you will see the Item Container Style’s current Form Item template. Where you can change the colors and layout, for example, we have modified the Vertical Layout of “PART_Label” field as Top in this figure below.

ChangeLayout

Share
Tagged with:  

RIA – Why? Which One? How?

On December 13, 2008, in RIA, by Akash Kava

RIA (Rich Internet Application) means faster means to develop light applications to fit in your business presentation and few quick interactive applications. With RIA you can not make a money tree and you can not become rich.

Target Applications:

  1. Frontend Applications
  2. Small Quick Demo Applications
  3. Graphical Analysis of MIS
  4. Marketing Presentations
  5. Quick Forms/Data Entry for Mass Audience
  6. Polls, Social Interaction Applications
  7. Thin Client Applications

With RIA you can generally make a thin client applications, which surely needs to interact with high poerful web server or any other form of server over internet. RIA replaces frontend for modern internet applications from traditional HTML/JS form processing websites.

WHY RIA?

Traditional web portal applications (ASP.NET/EJB..) takes too much of time to process every single request, as it does not use full potential of client side computer. Every decision of which button to be displayed, state of an application and user’s choices and preferences, everything is maintained on server and applications utilizes too much of bandwidth as well.

Thats why, RIA is simple step to differentiate user interface and business logic completely with implementations of standards like SOAP web services and REST apis.

All RIAs are compiled at development site, that means the final RIA is in form of an application, which will execute accurately as designed. However in traditional HTML+JS, if any part of HTML is not rendered properly or its coded wrongly, there is no way to detect until it is delivered to browser and some error has been encountered. Pre compilation on RIA, reduces time required to develop web application drastically.

WHICH RIA?

Flex Silverlight JavaFX XUL
Vendor Adobe Microsoft Sun Microsystems Mozilla
Open Source Yes
(I am talking about FLEX not Flash)
No Yes Yes
Support

Community Support is very bad when you need quick solution in an emergency.

Paid Support & Community Paid Support & Community Community Support Community Support
Dependency Flash Player Silverlight Player Java Runtime + JavaFX Runtime XUL Runtime
Availability

According to various statistics, the by default availability of dependent software on PCs.

95% 10% 0%

Although few PCs and all MACs have Java Runtime, they still need something additional.

30% as FireFox supports XUL Apps
Size of Runtime 1MB 4.5MB 30MB 4MB
Native Device Access Camera, Mic and Speakers Speakers Speakers None in Web App,

May be few in Desktop App

Audio Video Support Widely used FLV and MP3 format, stable and its there since 2001 WMV/WMA/WMA Pro No No
Converters for the Supported Video FFMPEG and many other commercial vendors available Paid Encoders No No
Documentation SDK Documentation and Samples MSDN but still very premature, (Reason, the learning curve is little higher) JavaDocs but JavaFX is still new Apache Documentation, very scattered, difficult to learn.
Syntax XML + Action Script XML + C# / JS / VB.NET Totally New Syntax XML + JS
Language Feature Strictly Typed with “Object” being dynamic type Strictly Typed,

Dynamic type to come in C# 4.0

Strictly Typed Dynamic Typed
Binding Expressions

Flex introduced wonderful concept of auto updating expressions when properties or variables changes.

Very Accurate Accurate but lengthy code Available Better then JavaFX and Silverlight
Two Way Databinding
Not Available, Coming up in Flex 4 Available - Available
Binding Declaration Simple Attribute Extra Code in each bindable property Extra code in each bindable property Simple Attribute
Reflection Available Available Available Available
Code Size Very Concise Even simpler things like validator etc takes 6 lines, too big code size to maintain Size is small, but very disorganized, difficult to read Concise enough
Platform Availability Windows, Mac, Linux Windows Only Windows, Mac, Linux Windows, Mac, Linux
Stability Very Stable Pre Beta Pre Beta Stable Enough
Control Library Rich set of Controls available, plus lots of free stuff available as well Very basic controls, you have to spend money on other ISVs to get good controls Good set of Controls Almost everything is free, lacks good documentation though
Coders Availability

For project managers, how difficult it will be to find coders who will code.

Easily Available as existing Flash, HTML, JS, ActionScript can code. C# and Microsoft Technology programmers can code. Java Programmers can code, but due to new syntax, its still difficult to get hands on it. Very difficult as it requires too extra knowledge of mozilla architecture and various standards, which is not taught anywhere.
Commercial Training

Starting project is very easy, but ongoing maintanence and meeting deadlines requires excellent knowledge of technology, which you should not rely on community blogs, because time required to search any solution is costly.

Excellent Excellent Training available Where?
Threading Support No Limited No Limited
Themes/Skinning Yes Yes, but size of code is very big No Yes
WebService Integration Yes Yes Yes but very frustrating Yes
Upload/Download The Best Feature in Flex Yes Yes Yes
Installable on Desktop Yes No Yes Yes
Database Support (in desktop app only) Sqlite Not Applicable JavaDB

Too heavy and too slow

Sqlite
Auto Update on Desktop App Yes No No Yes
Present Since 2001 2007 2007 2001
IDE

Plugins are available under eclipse and netbeans etc type of editor, but problem is they are so premature, they dont support refractoring, analysis, debugging and lots of other facilities.

Flex Builder Visual Studio Plugin Plugin
IDE Cost
IDE Refractoring Yes Yes No No
IDE Source Versioning CVS

Good for Multiusers

Source Safe (Single Developer only)/ TSS (too costly) Plugin Plugin
Drag and Drop Editor Yes Limited, because to script you need Visual Studio and to design you need Blend (Other paid software) No No
Code Intellisense (Auto Complete) Yes Yes
Project Management Yes Yes
Library Management

Creating and importing shared code in the form of libraries.

Yes Yes
Component Development Very Simple Quite Complex as it is divided in User/Custom controls categories. Available Simple
The Result
Leader of RIA Flex Follower The Last Linux Love

Important Note:

Silverlight claims to be platform independent, but reality is, Microsoft no longer provides any more upgrades of Silverlight version for any other operating system other then Windows. And Linux was already not officially supported by Microsoft.

Advantages of RIA

  1. Reduce Development time
    As compared with traditional web application, since RIAs are pre compiled, errors due to syntax, wrong spellings can be detected earlier at time of desiging.
  2. Load First, Run Throughout
    RIAs load entire application (Except XUL) in the beginning, instead of HTML+JS, which loads as things proceed. This means, either application will load completely and work accurately even with slower bandwidth connection, or if some part didnt load, it will straightway display an error. So it works like transaction, either all or nothing. HTML+JS can behave unexpectedly in case of missing components.
  3. Seperate Design and Development Processes
    Flex and Sliverlight offers complete seperation of Development and Designing keeping integration simple, other platforms (earlier web ones) require too much time integrating designs and process.
  4. Utilize Client Computing
    Almost every computer has high powerful graphics capabilities, HTML/JS doesnt offer any great benefit over it. RIAs can completely explore native graphics capabilities and you get wide range of user interface functionality.
Share
Tagged with: