In this post I’ll show you how to configure your Visual Studio 2010 to step into the source code of .NET Framework 4.0 in 9 easy steps.

  1. Download the 167Mb installer that contains the logic and data required to install Reference Source, .Net 4.0. On the download page table, its named “.Net”, Version: 4.
  2. Execute the installer “Net_4.msi” that you have downloaded in the previous step.
  3. Install it onto a path of your choice. Example “C:\Development\Framework 4 Source
  4. Launch Visual Studio 2010. From the Tools menu, choose Options and open the Debugging node.
  5. Select General, then do the following:
    • Uncheck “Enable Just My Code (Managed only)”
    • Check “Enable source server support”
    • Uncheck “Require source files to exactly match the original version”
    • Optional: Uncheck “Step over properties and operators (Managed only)”
  6. Select Symbols under Debugging.
  7. In the Symbol File Locations box, add the downloaded symbols location: “C:\Development\Framework 4 Source\Symbols
  8. Enter in text box under ‘Cache symbols in this directory’: “C:\Development\Framework 4 Source\Symbols\Cache
  9. That’s it, you can now Step Into .NET source code. Happy sessions!

Technorati Tags: , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

This reference tutorial will help you grasp the power of WinDebug debugging tool and quickly start using it in your daily development tasks. So, before we start, let me explain what WinDbg is.

WinDbg is a multipurpose debugger for Microsoft Windows, distributed on the web by Microsoft. It can be used to debug user mode applications, drivers, and the operating system itself in kernel mode. It is a GUI application, but has little in common with the more well-known, but less powerful, Visual Studio Debugger. WinDbg can be used for debugging kernel-mode memory dumps, created after what is commonly called the Blue Screen of Death which occurs when a bug check is issued. It can also be used to debug user-mode crash dumps. This is known as Post-mortem debugging.

WinDbg also has the ability to automatically load debugging symbol files (e.g., PDB files – Program DataBase file with debug information) from a server by matching various criteria (e.g., timestamp, CRC, single or multiprocessor version). This is a very helpful and time saving alternative to creating a symbol tree for a debugging target environment. If a private symbol server is configured, the symbols can be correlated with the source code for the binary. This eases the burden of debugging problems that have various versions of binaries installed on the debugging target by eliminating the need for finding and installing specific symbols version on the debug host. Microsoft has a public symbol server that has most of the public symbols for Windows 2000 and later versions of Windows (including service packs).

I’ve used WinDbg mostly in .NET applications, and that’s what I’ll be sharing this time around. To keep things simple and fast, because if you need WinDbg you are probably dealing with some memory issues and time is precious, I’ll put put it in steps:

1) You can start by downloading debugging tools from the Microsoft Windows SDK for Windows 7 and .NET Framework 4. You may also opt to download the ISO version. Take into consideration the target instruction set, either x84 or x64, depending on your application requirements.

2) Run WinDbg.exe executable. Search for WinDbg in "C:\Program Files (x86)\Debugging Tools for Windows (x86)" or “…WinDDK\7600.16385.1\Debuggers\windbg.exe” if you have the Windows Driver Development Kit.

3) Load mscorlib by writing:

        > sxe ld:mscorlib
        > g
       
        NOTE: Press enter after each line. "g" continues debuger execution.

4) Load the SOS Debugging Extension (SOS.dll). This allows debugging of managed programs in the WinDbg.exe debugger and in Visual Studio by providing information about the internal common language runtime (CLR) environment. First command in example loads SOS for debugging framework 2.0. The second is used for Framework 4.0.

        > .loadby sos mscorwks
        > .loadby sos clr (Framework 4.0)
        > g

5) Quick usage scenario #1: View memory consumption for all objects of a given type

        > !DumpHeap -type MyAppRootNamespace.ViewModels.ClientProfileViewModel

6) Quick usage scenario #2: View the managed call stack

        > !CLRStack

7) Quick usage scenario #3: View which object(s) are holding a reference to a specified address

        > !gcroot 29682dc0

 

Here’s a little script you can use to detect Framework 4 and load it in WinDbg.
   
    > !for_each_module .if(($sicmp( "@#ModuleName" , "mscorwks") = 0) ) {bp mscorwks!WKS::GCHeap::SuspendEE ".if (dwo(mscorwks!WKS::GCHeap::GcCondemnedGeneration)==2) {.echo start of gen 2}"} .elsif ($sicmp( "@#ModuleName" , "clr") = 0) {bp clr!WKS::GCHeap::SuspendEE ".if (dwo(clr!WKS::GCHeap::GcCondemnedGeneration)==2) {.echo start of gen 2}"}

 

Also, a full list of WinDbg commands, organized by category: http://windbg.info/doc/1-common-cmds.html.

And a PDF for you to print and keep it around your workspace.

 

Happy sessions.

Technorati Tags: , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

PowerSQL dumping tool available

0

I made available a small utility that allows you to script SQL Server data onto sql/txt files. It’s an old tool I used on several real world scenarios and it worked pretty well. It saved me a lot of time on many ocasions.

Although it isn’t finished, I thought of posting it so that you can save some time as well. Feel free to comment and don’t forget: use it at your own discretion.

Some of the features included are:

  • SQL Server 2000 and 2005 support (2008 version’s new datatypes are yet to be added)
  • Lists database tables, stored procedures and views
  • Shows table schema info
  • Dumps SQL Server table data onto configurable sql/txt files
  • Set file size limit
  • File per table option
  • Maximum file size setting allows you to generate several, smaller, files
  • View and Stored Procedure viewer and editor

From the PowerSQL homepage: “Keep in mind that this is a small utility I’ve made for my daily usage, and It’s still buggy, so use it at your discretion. I’ve used it successfully for several times in big production databases, but there’s allways room for error. Leave some feedback if you encounter urgent bugs, I’ll try to fix them. In the meantime I’ll try to get the time to make it a v1…”

Check out PowerSQL Homepage  to download, and don’t forget to leave some feedback.

Technorati Tags: ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

New Visual Studio 2010 Feature: Pin To Source

0

A cool feature in Visual Studio 2010 is Pin To Source. This command is available in the Visual Studio code editor context menu and allows you to create a kind of little “Post-It!” on your code showing variable values and expressions that you want to watch during a debugging session. Its very handy:

Just right click on the variable you wish to watch (or create your own expression) and select Pin To Source. And Voilá! A tip shows up with the current inspected value. When you aren’t debugging it all becomes grayed out, just like the Watch window.

I’m having a blast with this tiny feature. But use it wisely and if you see yourself creating huge “post-it” farms, you’ll maybe want to consider calling it a day!

EDIT: Visual Studio 2010 RC has some issues with this feature though. Pinned variables/expressions get a marking on the left bar of the code editor (where debug markers stay) with a pin icon. In design time you can see their latest values and you also have the options to clear them and arrange them. When doing the later, VS 2010 crashes in all its glory… Another one to get in the bug fixing line to the final release.

Technorati Tags:

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Listing an Element’s Attached Properties

1

I was recently confronted with a scenario in witch a xaml element needed to be dynamically replaced and nested in a container control. There’s nothing unusual about this except for the fact that when this happens the element being replaced might have attached dependency properties set on it. Needless to say that in this scenario such operation might have significant impact. Imagine if your element is inside a Canvas panel and has some of its attached properties set, like Canvas.Top or Canvas.Left.

My first approach was to go through reflection on the parent and get all DependencyProperties, then invoke GetValue() on the element for each one. It worked but it got me thinking that there had to be a cleaner way, since Attached Property values collection is internal and not directly accessible. Then I got to know a primitive called MarkupWriter. In fact, I’ve crossed with it before on a previous project but never got to actually use it. This time around I’ll make it official, so I’m sharing a little snippet that checks an element for Attached Properties, followed by an example:

public static IDictionary GetAttachedProperties(DependencyObject element)
{
    var attachedPropertyList = new Dictionary();
    var markupObject = MarkupWriter.GetMarkupObjectFor(element);

    foreach (var prop in markupObject.Properties)
    {
        if (prop.IsAttached)
            attachedPropertyList.Add(prop.DependencyProperty, prop.Value);
    }
    return attachedPropertyList;
}

Here’s a simple usage example:

var border = new Border()
             {
                 Width = 200, Height = 200,
                 BorderBrush = Brushes.Blue,
                 BorderThickness = new Thickness(1)
             };

border.SetValue(Canvas.TopProperty, 10d);
border.SetValue(Canvas.LeftProperty, 50d);

var list = GetAttachedProperties(border);

// Beware that ForEach is a Unity enumerable extension.
list.ForEach(prop => Console.WriteLine("Attached property Name: {0}", prop)); 

/*
Outputs:
Attached property Name: [Left, 50]
Attached property Name: [Top, 10]
*/

 Hope it helps.

Technorati Tags: ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

WPF Input Validation Part 3: Markup Extensions

2

In the previous article we took a step further on input validation over WPF controls by means of an attached property. The attached property’s owner would then have the required programming to add validation logic to the control’s target dependency property binding.

Keeping optimization in mind we can go, once again, a step further on this and reduce the code required by implementing our own Binding object, with it’s own validation mechanism, that could be configured by the developer in design time. An example of this methodology would be going from this:

<TextBox x:Name="ValidatedTextBox" Width="200"
    Rules:MandatoryRule.TargetProperty="{x:Static TextBox.TextProperty}"
    Style="{DynamicResource EditableTextBox}" Text="{Binding MyProperty}" />

To this:

<TextBox x:Name="ValidatedTextBox" Width="200"
    Style="{DynamicResource EditableTextBox}"
    Text="{validation:ValidationBinding MandatoryInputRule, MyProperty}" />

So what’s the trick when we wish to replace the good old Binding class by a custom one? The Binding class, like many others also familiar to you like StaticResource, DynamicResource, RelativeSource or Templatebinding, is a MarkupExtension. You can detect MarkupExtensions in XAML by the curly braces. They are the actual indicator of a markup to the XAML parser. So the idea here is to create a new binding-like MarkupExtension and extend it to accommodate binding functionality with built in validation.

Before we dig into the code, I believe a brief explanation on MarkupExtensions is needed.

MarkupExtensions are a XAML concept and can be described as a behavior that the XAML parser acquires when going through the XAML to discard the general treatment of attribute values as either a literal string or a directly string-convertible value and, instead, “pass the ball” to a handling class perform its own logic in the visual tree buildup. In attribute syntax, curly braces ({ and }) indicate a markup extension usage. Its a good alternative when the requirement is more ambitious a type converters implementation on types or properties.

So why a MarkupExtension and not just use nested property element syntax? – you ask. Well, for two reasons. It reduces the amount of code required to perform the task, and also because when using property element syntax, a new instance is created, while a markup extension usage can potentially return an existing instance, and thus can be more versatile or might incur less object overhead. But there’s a disadvantage though, and that’s collections. You can’t define collection elements in attribute syntax, unlike property element syntax. Take the x:Array MarkupExtension for instance:

<x:Array Type="sys:String">
    <sys:String>dot</sys:String>
    <sys:String>Net</sys:String>
    <sys:String>Brainwork</sys:String>
    <sys:String>Rocks!</sys:String>
</x:Array>

Each markup extension identifies itself to a XAML parser by means of a class that derives from MarkupExtension, and provides an implementation of the ProvideValue method. This method defines what object is returned once the markup extension is evaluated. The returned object is typically instantiated or set by using the various string tokens passed to the markup extension.

Finally, with this in mind, lets dig into the code. The following ValidationBinding class is a MarkupExtension that aggregates a validation mechanism and allows its definition in the attribute syntax binding declaration.

[MarkupExtensionReturnType(typeof (object))]
[Localizability(LocalizationCategory.None, Modifiability = Modifiability.Unmodifiable,
    Readability = Readability.Unreadable)]
public class ValidationBinding : MarkupExtension
{
    #region Private Fields

    // Rule collection
    private readonly List rules = new List();

    // Our binding object, pre-initialized with PropertyChanged trigger.
    private Binding binding = new Binding {UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged};

    private ValidationRule rule;

    // Convert string to rule instance.
    private readonly StringToValidationRuleConverter ruleConverter = new StringToValidationRuleConverter();

    #endregion

    #region Public properties

    [DefaultValue(null)]
    public object AsyncState
    {
        get { return binding.AsyncState; }
        set { binding.AsyncState = value; }
    }

    [Browsable(false)]
    public Binding Binding
    {
        get { return binding; }
        set { binding = value; }
    }

    // ...

    [DefaultValue(null)]
    public string XPath
    {
        get { return binding.XPath; }
        set { binding.XPath = value; }
    }

    [DefaultValue(null)]
    public Collection ValidationRules
    {
        get { return binding.ValidationRules; }
    }

    [DefaultValue(null)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [TypeConverter(typeof (StringToValidationRuleConverter))]
    [ConstructorArgument("ruleName")]
    public ValidationRule Rule
    {
        get { return rule; }
        set
        {
            rule = value;
            rules.Add(rule);
        }
    }

    #endregion

    #region Constructor

    public ValidationBinding()
    {
    }

    public ValidationBinding(string ruleName)
    {
        AddRule(ruleName);
    }

    public ValidationBinding(string ruleName, string path)
        : this(ruleName)
    {
        Path = new PropertyPath(path);
    }

    public ValidationBinding(string ruleName1, string ruleName2, string path)
        : this(ruleName1, path)
    {
        AddRule(ruleName2);
    }

    public ValidationBinding(string ruleName1, string ruleName2, string ruleName3, string path)
        : this(ruleName1, ruleName2, path)
    {
        AddRule(ruleName3);
    }

    #endregion

    #region Implementation

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (serviceProvider == null)
            return this;

        var provideValueTarget = serviceProvider.GetService(typeof (IProvideValueTarget)) as IProvideValueTarget;

        DependencyObject targetDependencyObject;
        DependencyProperty targetDependencyProperty;

        CheckCanReceiveMarkupExtension(this, provideValueTarget, out targetDependencyObject,
                                       out targetDependencyProperty);

        if (targetDependencyObject == null || targetDependencyProperty == null)
        {
            return this;
        }

        // Fetch metadata - unused, just for your reference
        var metadata =
            targetDependencyProperty.GetMetadata(targetDependencyObject.DependencyObjectType) as
            FrameworkPropertyMetadata;

        if ((metadata != null && !metadata.IsDataBindingAllowed) || targetDependencyProperty.ReadOnly)
            throw new ArgumentException("");

        // Two-way binding requires a path
        if (
            (binding.Mode == BindingMode.TwoWay || binding.Mode == BindingMode.Default) &&
            binding.XPath == null &&
            (binding.Path == null || String.IsNullOrEmpty(binding.Path.Path))
            )
            throw new InvalidOperationException("Two way binding has no Path.");

        if (rules.Count > 0)
            foreach (var r in rules)
                binding.ValidationRules.Add(r);

        return binding.ProvideValue(serviceProvider);
    }

    ///
    /// This static method validates the holder of the current extension, where it is being defined. It detects the various scenarios
    /// where a MarkupExtension is allowed to be set and tests their candidacy for the assignment.
    ///
    public static void CheckCanReceiveMarkupExtension(MarkupExtension markupExtension,
                                                      IProvideValueTarget provideValueTarget,
                                                      out DependencyObject targetDependencyObject,
                                                      out DependencyProperty targetDependencyProperty)
    {
        targetDependencyObject = null;
        targetDependencyProperty = null;

        if (provideValueTarget == null)
            return;

        var targetObject = provideValueTarget.TargetObject;

        if (targetObject == null)
            return;

        var targetType = targetObject.GetType();
        var targetProperty = provideValueTarget.TargetProperty;

        if (targetProperty != null)
        {
            targetDependencyProperty = targetProperty as DependencyProperty;
            if (targetDependencyProperty != null)
            {
                targetDependencyObject = targetObject as DependencyObject;
                Debug.Assert(targetDependencyObject != null,
                             "DependencyProperties can only be set on DependencyObjects");
            }
            else
            {
                // For the implementation at hand we should do this, because nothing else matters.
                // throw new XamlParseException("Type not assignable.");

                // Moving on with all possible cases...
                var targetMember = targetProperty as MemberInfo;
                if (targetMember != null)
                {
                    // If targetMember is a MemberInfo, then its the CLR Property case.
                    // Setters, Triggers, DataTriggers & Conditions are the special cases of
                    // CLR properties in which DynamicResource and Bindings are allowed.
                    // Since StyleHelper.ProcessSharedPropertyValue prevents calls to ProvideValue
                    // in such cases, there is no need for special code to handle them here. 

                    Debug.Assert(targetMember is PropertyInfo || targetMember is MethodInfo,
                                 "TargetMember is either a CLR property or an attached static setter method");

                    Type memberType;

                    var propertyInfo = targetMember as PropertyInfo;
                    if (propertyInfo != null)
                        memberType = propertyInfo.PropertyType;
                    else
                    {
                        var methodInfo = (MethodInfo) targetMember;
                        var parameterInfos = methodInfo.GetParameters();
                        Debug.Assert(parameterInfos.Length == 2,
                                     "The signature of a static settor must contain two parameters");
                        memberType = parameterInfos[1].ParameterType;
                    }

                    // Check if the MarkupExtensionType is assignable to the given MemberType
                    // This checking allows properties like DataTrigger.Binding, Condition.Binding
                    // HierarchicalDataTemplate.ItemsSource, GridViewColumn.DisplayMemberBinding
                    if (!typeof (MarkupExtension).IsAssignableFrom(memberType) ||
                        !memberType.IsAssignableFrom(markupExtension.GetType()))
                    {
                        throw new XamlParseException("Type not assignable.");
                    }
                }
                else
                {
                    throw new XamlParseException("Type not assignable.");
                }
            }
        }
        else
        {
            throw new XamlParseException("Type not assignable.");
        }
    }

    private void AddRule(string ruleName)
    {
        var validationRule =
            new StringToValidationRuleConverter().ConvertFrom(null, null, ruleName) as ValidationRule;

        if (validationRule != null)
            rules.Add(validationRule);
    }

    #endregion
}

The above code is purposely expanded to better understanding. You can refactor on your implementation afterwards.

Lets start by explaining the two attributes defined for the class. MarkupExtensionReturnType specifies type information for the type returned in the ProvideValue method. We’ve specified object for this example. Localizability specifies the localization attributes for the class. This has to to with the Localization features in WPF. Checkout the LocBaml tool for more info on this. For now the class is being defined as not modifiable by localizers and also not readable.

Next come some private field declarations. The rules list will hold every ValidationRule objects defined in the class declaration in XAML. There’s also a Binding object, which is the foundation of the ValidationBinding class. Everything the extension does is meant with the purpose of configuring and defining this binding instance. That’s why the extension exposes a set of properties that are typical of the binding class, to allow the extension to expose binding behavior to the outside. You are already familiar with all of those, except for the last one, which is:

[DefaultValue(null)]
[EditorBrowsable(EditorBrowsableState.Always)]
[TypeConverter(typeof (StringToValidationRuleConverter))]
[ConstructorArgument("ruleName")]
public ValidationRule Rule
{
    get { return rule; }
    set
    {
        rule = value;
        rules.Add(rule);
    }
}

This property serves the purpose of direct rule definition in the attribute. Like so:

Text="{val:ValidationBinding Rule=MyCustomRule, Path=MyProperty}"

 There are a couple of attributes defined on this class member:

- DefaultValueAtribute: The default attribute the property will have once the class is initialized. This is typically used by designers to reset the member’s value, or even code generators, to determine whether code should be generated for the member or other reflection tasks.

- EditorBrowsableAttribute tells the designer to display this property. This type can be used in a visual designer or text editor to determine what properties or methods are visible to the user when in design mode. The IntelliSense engine in Visual Studio is an example of such usage, because it uses this attribute to determine whether or not to show a property or method.

- TypeConverterAttribute specified the value converter to use when the user specifies the property in attribute syntax. This is typically a string converter.

- ConstructorArgumentAttribute specifies that this property is set by a constructor parameter with the given name. In the ValidationBinding class example, the first parameter in two overloads is “ruleName” and it sets the Rule property afterwards.

That said, It’s time to explain the purpose of the several constructor overloads. In case you don’t know, when dealing with attribute syntax attributes a lot is considered and assumed by the XAML processor. Consider the following example:

Since we are assigning values to properties (hence the “equals” = sign), the XAML parser will assume commas as delimiters for each property set operation. On the other hand, if no assignments are made the processor assumes commas are constructor parameter delimiters:

The text property of this TextBox control is being set to a Binding MarkupExtension object, with the target property as its parameter. Underneath, a one parameter constructor is being called to process the given property name.

So in the ValidationBinding class we define several constructor overloads in order to be able to define more than one ValidationBinding at a time. This is only required for the sake of attribute syntax comfort. It wouldn’t be necessary if you consider property element syntax in your implementation, but then that would be more troublesome wouldn’t it? ;)

Then there’s the ProvideValue method implementation that is responsible for making all the pieces come together. It starts by getting a reference to a IProvideValueTarget object through the IServiceProvider argument provided. It then calls the CheckCanReceiveMarkupExtension method to analyze this extension’s owner characteristics and see if it meets the requirements of our MarkupExtension to be able to execute its purpose, which is data binding validation. Several scenarios are considered and evaluated for this, but the present case targets only DependencyProperties. You should take into account all possible MarkupExtension usages in XAML when validating your own logic. That way you can filter all the scenarios where your code might be used and react accordingly.

To wrap things up, validations are added to the binding object, and the object that is to be set on the property the extension is applied on, is returned. The AddRule method actually adds validation rules to the binding instance. It does so by converting the rule name to the actual object, through reflection.

private void AddRule(string ruleName)
{
    var validationRule = ruleConverter.ConvertFrom(null, null, ruleName) as ValidationRule;

    if (validationRule != null)
        rules.Add(validationRule);
}

 When initialized, the converter checks for all ValidationRules in the executing assembly and collects them in order to hold all possible types and to be able to initialize them on demand, or shall I say, when a compatible rule name is passed onto the ConvertFrom method:

#region #using Directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows.Controls;

#endregion

namespace ValidationSample4
{
    public class StringToValidationRuleConverter : TypeConverter
    {
        private static readonly Dictionary Rules;

        static StringToValidationRuleConverter()
        {
            Rules = new Dictionary();

            var assembly = Assembly.GetExecutingAssembly();
            foreach (var type in assembly.GetTypes().Where(type => type.IsSubclassOf(typeof (ValidationRule))))
                Rules.Add(type.Name, type);
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof (string) || base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof (string))
                return true;

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string text = value as string;

            if (text != null)
            {
                try
                {
                    if (Rules.Any(type => type.Key == text))
                    {
                        var instance = Activator.CreateInstance(Rules);
                        return instance;
                     }
                 }
                 catch (Exception e)
                 {
                     throw new Exception(String.Format("Cannot convert '{0}' ({1}) because {2}", value, value.GetType(), e.Message), e);
                 }
             }
              return base.ConvertFrom(context, culture, value);
        }

         public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
         {
             if (destinationType == null)
                 throw new ArgumentNullException("destinationType");
              var rule = value as ValidationRule;
              if (rule != null && CanConvertTo(context, destinationType))
                 return rule.GetType().Name;
              return base.ConvertTo(context, culture, value, destinationType);
         }
     }
 }

 I guess that wraps it up. But there’s nothing better than give it a go yourself. Take a good look at the example, mess around with it, and feel free to comment this implementation. I’ll continue to evolve this mechanism in following articles.

Here’s the sample with all the code:

Wpf Input Validation (WpfInputValidation.rar)

Includes:

- ValidationSample1 (Base implementation)

- ValidationSample2 (Attached property)

- ValidationSample3 (Attached property – no need for UpdatePropertyTrigger)

- ValidationSample4 (Markup Extension)

In case you missed them, here are the previous articles:

1) Wpf Input Validation Part I – Validation Rules

2) Wpf Input Validation Part II – Attached Properties

Technorati Tags: ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

WPF Input Validation Part 2: Attached property approach

3

 In the previous article I’ve shown how to apply Validation Rules to controls in order to prevent/access user input. In the process, user was warned through a visual change in the target control. It’s the simplistic and direct way of doing validation and works perfectly from the UX point of view. However, from the developer point of view, a better implementation is required to ease the quantity of code needed and to isolate concerns.

The idea is to apply validation rules by means of an attached property, in which the owner would have the reference to the control and its target Dependency Property, and the required logic to add the rule object implicitly.

We’ll assume the WPF window of the previous example and proceed from there. The biggest difference rests is the XAML. The TextBox no longer has a validation rule and, instead, an attached property was added. We’ll discuss it afterwards.

<Window x:Class="ValidationSample2.ValidationWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Rules="clr-namespace:ValidationSample2"
    Title="ValidationWindow" Height="200" Width="300">
    <Window.Resources>
        <Style x:Key="EditableTextBox" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
            <Setter Property="Background" Value="#DDFFDD" />
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <Border BorderBrush="Red" BorderThickness="2">
                            <AdornedElementPlaceholder />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="Background" Value="#FFDDDD"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid VerticalAlignment="Center" HorizontalAlignment="Center">
        <StackPanel Name="ValidationPanel" >
            <Label>Validated Text Box:</Label>
            <!-- UpdateSourceTrigger is needed in order to raise property change event on input
            and not on focus, which is the default behavior -->
            <TextBox x:Name="ValidatedTextBox" Width="200"
                     Rules:MandatoryRule.TargetProperty="{x:Static TextBox.TextProperty}"
                     Style="{DynamicResource EditableTextBox}" Text="{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}" />
        </StackPanel>
    </Grid>
</Window>

As you can see, things got much simpler. A single property set is all there is in order to set my mandatory input rule. So how do we do this? It’s pretty simple, actually. I’ve created a static class called MandatoryInput and, as you can see in XAML, I’ve defined the TargetProperty attached property and I’m registering on the static constructor. The essence of this implementation happens when this property’s value changes. Check out the full blown implementation that follows:

#region #using Directives

using System;
using System.Windows;
using System.Windows.Controls;

#endregion

namespace ValidationSample2
{
    public static class MandatoryRule
    {
        #region Dependency Properties

        public static readonly DependencyProperty TargetProperty;

        #region Get/Sets

        public static DependencyProperty GetTargetProperty(UIElement target)
        {
            return target.GetValue(TargetProperty) as DependencyProperty;
        }

        public static void SetTargetProperty(UIElement target, DependencyProperty value)
        {
            target.SetValue(TargetProperty, value);
        }

        #endregion

        #endregion

        #region Constructor

        static MandatoryRule()
        {
            TargetProperty = DependencyProperty.RegisterAttached("Target",
                                                                 typeof (DependencyProperty), typeof (MandatoryRule),
                                                                 new UIPropertyMetadata(null, OnTargetPropertyChanged));
        }

        #endregion

        #region Event handlers

        private static void OnTargetPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            if (!(obj is UIElement))
                throw new InvalidOperationException("Object must be a UI element.");

            SetValidationRule(obj, args.NewValue as DependencyProperty);
        }

        #endregion

        #region Methods

        private static void SetValidationRule(DependencyObject obj, DependencyProperty property)
        {
            if (property == null)
                throw new InvalidOperationException("No Validation DependencyProperty attached.");

            GetRule(obj, property);
        }

        private static void GetRule(DependencyObject obj, DependencyProperty property)
        {
            var control = obj as Control;

            if (!control.IsInitialized)
            {
                RoutedEventHandler callback = null;
                callback = delegate
                               {
                                   control.Loaded -= callback;
                                   SetValidationRule(obj, property);
                               };
                control.Loaded += callback;
                return;
            }

            var expression = control.GetBindingExpression(property);
            if (expression == null)
                throw new InvalidOperationException(
                    "The control's validation property must be bound for the Validator to validate it.");

            var binding = expression.ParentBinding;
            if (binding == null)
                throw new ApplicationException("Property binding expression has no parent binding.");

            ValidationRule mandatoryRule = null;
            foreach (var rule in binding.ValidationRules)
            {
                if (rule is MandatoryInputRule)
                {
                    if (mandatoryRule == null)
                        mandatoryRule = rule as MandatoryInputRule;
                    else
                        throw new InvalidOperationException(
                            "There's more than one MandatoryInputRule in the Binding's ValidationRules.");
                }
            }

            if (mandatoryRule == null)
            {
                mandatoryRule = new MandatoryInputRule();
                binding.ValidationRules.Add(mandatoryRule);
            }
        }

        #endregion
    }
}

As an attached property, I had to create the usual Get[PropertyName] and Set[PropertyName] methods so that these could actually set the values in the control. The idea is for this property to hold the target control’s dependency property we are going to interact with, and upon property change notification, execute our logic.

However, this notification actually  comes in two distinct phases. The first one happens when the XAML is processed by the XAML parser and the last is when it’s actually initialized. As you can see in the code, the GetRule() method is called on such occasions, however, binding data will only be available when the affected control is initialized, so it is crucial to do our work only when. So, on the first phase, since the control isn’t yet initialized, we just set an event handler to execute when control is Loaded. This event handler will call the same SetValidationRule() method who attached it in the first place, but in that point in time, it will proceed all the way to the binding manipulation.

So the trick here is to fetch the BindingExpression on the target DependencyProperty of the affected control. Keep in mind that a BindingExpression is an underlying object that knows the connection between the binding source and the binding target. On the other hand, a Binding is merely a higher level object in the binding mechanism that contains all the information about the binding source and the nature of the binding, and can be shared across several BindingExpression objects.

Moving on, with our BindingExpression, we then get the Binding object and add our validation rule to it, validating duplicates in the process. And that’s all there is to it.

I know this already leverages the implementation and code required, and most people would be comfortable with this, but we still must set UpdateSourceTrigger on the Binding object, otherwise input validation only occurs when the textbox loses focus. Since others, and myself would have a “mission incomplete” kind of feeling, we’ll move on.

At this moment, you may be thinking in changing the value of UpdateSourceTrigger in the GetRule() method, where the binding object is exposed:

(...)
var binding = expression.ParentBinding;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
(...)

 You could indeed to it, and the app would compile just fine. But at runtime you would get the following exception: “Binding cannot be changed after it has been used”. If you think about it, it makes sense, because when a binding is set, the event wiring is created in order for change notifications to go from source to target and vice-versa. So this means that a new binding object must be created, and then set on the target DependencyProperty. The following variant of the GetRule() method exposes this like of thinking:

static void GetRule(DependencyObject obj, DependencyProperty property)
{
    var control = obj as Control;

    if (!control.IsInitialized)
    {
        RoutedEventHandler callback = null;
        callback = delegate
                       {
                           control.Loaded -= callback;
                           SetValidationRule(obj, property);
                       };
        control.Loaded += callback;
        return;
    }

    var expression = control.GetBindingExpression(property);
    if (expression == null)
        throw new InvalidOperationException("The control's validation property must be bound for the Validator to validate it.");

    var binding = expression.ParentBinding;
    if (binding == null)
        throw new ApplicationException("Property binding expression has no parent binding.");

    /*
     * The TextBox.Text property has a default UpdateSourceTrigger value of LostFocus.
     * This means that the text you type into the TextBox does not update the source
     * until the TextBox loses focus. This causes a runtime exception 'Binding cannot
     * be changed after it has been used'. So we must reset the binding.
    */

    if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default)
    {
        var bind = new Binding() {
                                     Mode = binding.Mode,
                                     UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                                     Path = binding.Path,
                                     BindsDirectlyToSource = binding.BindsDirectlyToSource,
                                     Converter = binding.Converter,
                                     ConverterCulture = binding.ConverterCulture,
                                     ConverterParameter = binding.ConverterParameter,
                                     FallbackValue = binding.FallbackValue,
                                     IsAsync = binding.IsAsync,
                                     NotifyOnSourceUpdated = binding.NotifyOnSourceUpdated,
                                     NotifyOnTargetUpdated = binding.NotifyOnTargetUpdated,
                                     NotifyOnValidationError = binding.NotifyOnValidationError,
                                     StringFormat = binding.StringFormat,
                                     TargetNullValue = binding.TargetNullValue,
                                     UpdateSourceExceptionFilter = binding.UpdateSourceExceptionFilter,
                                     ValidatesOnDataErrors = binding.ValidatesOnDataErrors,
                                     ValidatesOnExceptions = binding.ValidatesOnExceptions,
                                     XPath = binding.XPath
                                 };

        if (binding.ElementName == null && binding.RelativeSource == null)
            bind.Source = control.DataContext;
        else if (binding.Source == null && binding.RelativeSource == null)
            bind.ElementName = binding.ElementName;
        else
            bind.RelativeSource = binding.RelativeSource;

        binding = bind;
    }

    ValidationRule mandatoryRule = null;
    foreach (ValidationRule rule in binding.ValidationRules)
    {
        if (rule is MandatoryInputRule)
        {
            if (mandatoryRule == null)
                mandatoryRule = rule as MandatoryInputRule;
            else
                throw new InvalidOperationException("There's more than one MandatoryInputRule in the Binding's ValidationRules.");
        }
    }

    if (mandatoryRule == null)
    {
        mandatoryRule = new MandatoryInputRule();
        binding.ValidationRules.Add(mandatoryRule);
    }

    BindingOperations.ClearBinding(obj, property);
    BindingOperations.SetBinding(obj, TextBox.TextProperty, binding);
}

I’ve purposefully cloned a binding object and set its properties for better understanding and so that all the previous settings could be persisted, except for the origin of all this, the UpdateSourceTrigger property.

In the next article we’ll come out with an even better approach using a Markup Extension. It’s nothing new, but makes life a bit easier for the developer, and more clean and extensible from an architectural point of view.

In case you missed them, here is the previous article:

Wpf Input Validation Part I – Validation Rules

Technorati Tags: , , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

WPF Input Validation Part 1: Tutorial and examples

5

I’ve recently set up a sample of a validation mechanism for WPF text input controls on the UI that I thought it would be of general interest due to the “Gokuu approach”* I’ve done with it, otherwise it just wouldn’t make my day :) The requirement is to create a UI control behavior that visually signals validation errors over user input, so when the user submits empty or invalid data on a mandatory field, the input control changes it’s appearance or some kind of action takes place, like a validation message box. Then, it should prevent data submission when a button is clicked or the Enter key is pressed, for instance.

I’m talking about WPF Validation Rules. Validation Rules are objects that apply validation over a data Binding operation, and they are added to the Binding.ValidationRules Collection. They can be created by deriving from the ValidationRule class and overriding its Validate method that should hold the validation logic. Then, normally, you would add the rule to the collection in your xaml code, through property element syntax, or in code.

Although not a part of this article, there’s another validation mechanism built into WPF. You can also test one’s input through an ExceptionValidationRule, which invalidates a value if there are exceptions during source updates of the binding source property. You can even provide custom logic to specify how the binding engine handles these exceptions by using a UpdateSourceExceptionFilterCallback.

These series of articles will focus on creating and applying custom validation rules the most effective way. I’ll discuss this in an incremental way, building up a structured thinking till an acceptable solution is reached.

Moving on… We should then start with a simple WPF application, with it’s main window as our demo canvas. Lets a text control to fetch some user input to validate, say, a TextBox control, and make it data bound to a property that lives on the Window control itself. We’ll set it as it’s own DataContext for that.

<Window x:Class="ValidationSample1.ValidationWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Rules="clr-namespace:ValidationSample1"
    Title="ValidationWindow" Height="200" Width="300">
    <Window.Resources>

    </Window.Resources>
    <Grid VerticalAlignment="Center" HorizontalAlignment="Center">
        <StackPanel Name="ValidationPanel" >
            <Label>Validated Text Box:</Label>
            <TextBox x:Name="ValidatedTextBox"
                     Width="200"/>
            </TextBox>
        </StackPanel>
    </Grid>
</Window>
#region #using Directives

using System.ComponentModel;
using System.Windows;

#endregion

namespace ValidationSample1
{
    /// <summary>
    /// Interaction logic for ValidationWindow.xaml
    /// </summary>
    public partial class ValidationWindow : Window, INotifyPropertyChanged
    {
        public string myProperty;

        public string MyProperty
        {
            get { return myProperty; }
            set
            {
                if (value == myProperty)
                    return;

                myProperty = value;
                OnNotifyPropertyChanged("myProperty");
            }
        }

        public ValidationWindow()
        {
            InitializeComponent();

            DataContext = this;
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnNotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
    }
}

 Now we need to make sure the user doesn’t submit empty data and visually indicate him that same requirement. For that, we’re going to create a custom ValidationRule to prevent the user from submitting empty text. Like I said, this is done by extending the System.Windows.Controls.ValidationRule class:

#region #using Directives

using System.Globalization;
using System.Windows.Controls;

#endregion

namespace ValidationSample1
{
    public class MandatoryInputRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value != null)
            {
                string input = value as string;

                if (input.Length > 0)
                    return new ValidationResult(true, null);
            }

            return new ValidationResult(false, "Validation error. Field input required.");
        }
    }
}

The next step is to connect the Validation Rule to the binding target. To do so, you can go either the XAML way or in code. I’ll show you the first approach.

<TextBox x:Name="ValidatedTextBox"
         Width="200">
    <TextBox.Text>
        <!--  Textbox notifies changes when Text is changed, and not focus. -->
        <Binding Path="MyProperty" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <!--  Validation rule set to run when binding target is updated. -->
                <Rules:MandatoryInputRule ValidatesOnTargetUpdated="True" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

Notice that our binding object sets the UpdateSourceTrigger property to PropertyChanged. This is needed because TextBox updates it’s source when it loses Focus and as such, the default value of UpdateSourceTrigger for the TextBox is LostFocus. In this example, this isn’t enough. We need to analyze the data as user writes. So the ideal update behavior is to trigger when data, or property changes, hence the UpdateSourceTrigger.PropertyChanged value in the preceding example.

For now, our binding is empty value-aware due to the validation rule we applied. But wait! If we run the app, nothing happens. It still doesn’t manifest visually when user submits no text. We must specify a style behavior for when validations errors occur, the user gets warned through visual changes in the control. So we’ll add a style to the Window Resources collection and set it on the TextBox. The XAML would go like this:

<Window x:Class="ValidationSample1.ValidationWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Rules="clr-namespace:ValidationSample1"
    Title="ValidationWindow" Height="200" Width="300">
    <Window.Resources>
        <Style x:Key="EditableTextBox" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
            <Setter Property="Background" Value="#DDFFDD" />
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <Border BorderBrush="Red" BorderThickness="2">
                            <AdornedElementPlaceholder />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="Background" Value="#FFDDDD"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid VerticalAlignment="Center" HorizontalAlignment="Center">
        <StackPanel Name="ValidationPanel" >
            <Label>Validated Text Box:</Label>
            <TextBox x:Name="ValidatedTextBox"
                     Width="200"
                     Style="{DynamicResource EditableTextBox}">
                <TextBox.Text>
                    <!--  Textbox notifies changes when Text is changed, and not focus. -->
                    <Binding Path="MyProperty" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <!--  Validation rule set to run when binding target is updated. -->
                            <Rules:MandatoryInputRule ValidatesOnTargetUpdated="True" />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
        </StackPanel>
    </Grid>
</Window>

Now, the user sees a red border when no text is submitted. So the task is complete, but I can’t stop wondering the amount of code needed to add validation to a single control. Imagine an entire form…

The next article will present a new approach to this implementation and will require much less code.

* “Goku approach” is an analogy that means one’s accomplished the basic and most objective functional requirement, but then he can’t stop feeling an urge to improve the implementation whether performance, architectural or usability-wise. So that’s when code tends to get upgraded to the next level, shall we say a super level or “super-sayin”, like in the Dragon Ball anime. And after that, the same urge may arise again, and again, giving way to the typical Goku-powerup pattern that the main character faces along the series when needs to evolve to face his enemies :)

Technorati Tags: , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Object, var, dynamic and the DLR Showdown

1

There’s a time when new feature or frameworks arise and you get to know them and immediately grasp that new and useful way of doing things, but there are also times when clarity only comes after a bit of blurriness. From what I’ve read, the new Dynamic type in c# 4.0 is currently one of such cases, when compared to var. I read many developers say “What’s the point?” or “Why do I need this?”. Well, I believe it’s a matter of architectural needs, mixed with coding style. To break this discussion into pieces, and because I feel the force is strong with this one ;-) I found myself with the task of enlightening things up a bit.

In fact, this article hopes to settle the dust on this. I’ve seen a number of articles and posts on the web comparing and debating advantages and disadvantages, but I didn’t find them clear or eligible for training purposes. And even after knowing what each one really represent and allow, their usage and necessity is somewhat cloudy. Specially when it comes to dynamic.

So, to get the discussion started, I believe that we first must make sure we understand the basics of each one of these types, and build our structured thinking from there. You all know the System.Object type. Or its alias, object. Everything in the .Net Framework is an object, right? You can even refer to any type as object, by boxing it like this:

//Boxing
object var1 = 23;

// This will produce a compiler error
object sum = 3 + var1;

Since we specified 23 as var1’s value, it will be inferred and internally assumed as System.Int32. However, adding 3 var1 produces an “Operator ‘+’ cannot be applied to operands of type ‘int’ and ‘object’” compiler error.

This is where var comes in handy. If, instead of object we use the var type, the compiler will infer the underlying type and take it into consideration along the method scope. I say method scope because the var type can only be declared inside a method. So, the following would work:

var var2 = 23;

object sum2 = 3 + var2;

You can see the differences when boxing an Int32 value, but the same kind of difference arises when unboxing. Assigning var1 to an int variable produces a compiler error “Cannot implicitly convert type ‘object’ to ‘int’”, suggesting a cast, while assigning var2 compiles successfully:

// Produces compiler error
int var3 = var1;

// Compiles successfully
int var4 = var2;

var is still statically typed though. The only difference is, for instance, that you don’t need to repeat the type upon initialization:

// Type is specified only once
var x = new Collection();

It’s a nice bonus, but not it’s main purpose. The true purpose behind var is so that we can declare a strongly typed variable without needing to know the name of the variable’s type. This is crucial in order to enable C# 3.0’s anonymous types. You wouldn’t be able to declare a variable of an anonymous type if you always had to include the type name as part of the variable declaration. That’s the main reason var has been added to the language.

In some cases, when software architecture enables you to do so, you also have the advantage of changing return types without producing compilation errors.

Consider the following two classes. Event though they are similar in functionality, they are, nevertheless, different types and so, bound to the usual rules:

public class Human
{
    public int Age { get; set; }

    public string Name { get; set; }
}

public class Dog
{
    public int Age { get; set; }

    public string Name { get; set; }

    public string Breed { get; set; }
}

 

Now, imagine the following method from any given business layer, that returns a new instance of type Human:

public Human GetInstance()
{
     return new Human();
}

And a consumption example:

var o = GetInstance();

o.Name = "Alex";
o.Age = 23;

If, in the future, someone changes GetIntance()’s return type to Dog, you won’t need to change the previous code, because the same rules apply to the new type, since var’s type is implicit. Weird architectural approach, but an advantage to consider nevertheless.

And then there’s the dynamic type. dynamic is a static type, but an object of type dynamic bypasses static type checking. It’s like a type closing the door to the compiler when he knocks asking who’s in. And, as such, you don’t get the usual intellisence information. You’ll simply get the following:

 At compile time, an element that is typed as dynamic is assumed to support any operation. He simply doesn’t know what it is, nor where it comes from. You are in control :)

dynamic var1 = 23;

// Sum operation resolves successfully.
object sum1 = 3 + var1;

// This also works
int var2 = var1;

As you see in the previous snippet, it behaves just like var, but without intellisence. “No intellisence? Why bother then??” – you ask. We’ll get to that shortly. For now, consider the following extended Human class:

public class Human
{
    public int Age { get; set; }

    public string Name { get; set; }

    public void Punch(int intensity)
    {
        Console.WriteLine(string.Format("Punched with {0} strength.", intensity));
    }
}

A typical consumption example would be:

Human h = new Human();
h.Punch(100);

But if we used dynamic, we could do this:

dynamic h = new Human();
h.Punch(100, "Right in the face!");

Even though there’s no corresponding method signature in the Human class, the dynamic type made the compiler became passive, and he didn’t analyze the underlying/resolving type. So the snipped compiles just fine, but resulting in a runtime error later on.

The dynamic type has a broader usage than var. It can be used as a property, field, indexer, parameter, return value, local variable, or type constraint; it can be the target of an explicit conversion and it can be the right side assignment of both is or as operators or typeof argument. The following example demonstrates some of these arguments:

public MainWindow()
{
    InitializeComponent();

    // Prints ".net Brainwork rocks!" to the output window
    Console.WriteLine(ExampleMethod(23));
}

public dynamic ExampleMethod(dynamic number)
{
    dynamic dyn;

    int num = number;
    dyn = (dynamic)num;

    string str = ".net Brainwork rocks!";
    dyn = (dynamic)str;

    return dyn;
}

So what the dynamic type really does is telling the compiler to skip operation analysis and validation at design time, and instead, it resolves the types and operations at runtime. It accomplishes this through a new engine called Dynamic Language Runtime. The dynamic language runtime (DLR) is a new .Net Framework 4.0 runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. IronRuby and IronPython are two examples of languages developed by using the DLR.

Dynamic languages can identify the type of an object at run time, whereas in statically typed languages such as C# you must specify object types at design time.

The purpose of the DLR is to enable a system of dynamic languages to run on the .NET Framework and give them .NET interoperability. The DLR introduces dynamic objects to C# and Visual Basic in Visual Studio 2010 to support dynamic behavior in these languages and enable their interoperation with dynamic languages.

So, all in all, dynamic has an entirely new operation going on. It’s not just a matter of making it easier for developers to produce code or improve its quality, but it’s a new system for dynamic type handling, that improves how the language interacts with external data objects or services, whose types are only known at runtime like COM.

References:

Dynamic Language Runtime Overview – MSDN

Technorati Tags: , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

MEF and Prism on .NET Framework 4.0

0

David Hill from the patterns & practices team posted a very interesting article concerning MEF and Prism. It talks about the benefits your applications get from using these extensibility technologies, but also clears some misunderstandings regarding their purpose. I’ve been faced with this question several times and the online community reflects this same common overlap. While MEF is purely an extensibility API, Prism is a development pattern that allows you to organize and manage your WPF/Silverlight project through modularity and thus isolate requirement and functionality concerns in development teams.

They’re both part of .NET Framework 4.0 and a MUST if you are developing big applications and/or needing your software to be extensible.

Check out the article here.

Technorati Tags: , , , ,

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Page 1 of 41234Next »

Note: Silverlight, C#, in fact any .NET web development projects is best used with windows hosting than Linux based hosting.