Tuesday, March 23, 2010

Improving performance of DataBinding, patience is gold

I came across a performance problem lately. I have a WPF Smart Client application connected to a Dynamics CRM back end. At some point in my application I have add a lot of lines in a data table held by an ObservableCollection class. The problem was each time I add a line into the collection a CollectionChanged event was raised and that triggered the update of some other fields, approximately 10 in my case.
So when was doing batch update the screen freezes for way too much time. I found out the problem was the cascading effect of recalculating all the dependent fields every time I add a ne line in the collection, thanks to the new Visual Studio 2010 performance analysis tools.
In this scenario, I’m only interested to get the totals right when I do the last insert, all other intermediate values are useless. I didn’t want to play with the data binding itself. I could have unbound the total calculation and have it rebinded at the end but I didn’t. Instead I chose to delay the calculation with some kind of sliding expiration timer. Such a timer, set with a timeout of 10 ms, would be reset every time a new add would be made, so if I add a bunch of line in batch odds that the delay between two line add be less than 10 ms is good. In fact it is so good that because it’s almost always true the calculation happens only once at the end.
So there is this magic DelayRun class with its DelayController:
using System;
using System.Collections.Generic;
using System.Threading;

namespace Infrastructure
{
    public interface IDelayRun
    {
        void Reset();
        void Start(int ms);
        event EventHandler<DelayRunEventArgs> EventCompleted;
    }

    public class DelayRun<T> : IDisposable, IDelayRun
    {
        private static readonly ManualResetEvent _resetEvent = new ManualResetEvent(true);
        private readonly Action<T> _action;
        private readonly T _target;
        private int _delay;
        private volatile Timer _timer;

        private DelayRun(T target, Action<T> action)
        {
            _action = action;
            _target = target;
        }

        #region IDelayRun Members

        public void Start(int ms)
        {
            if (ms == 0)
                throw new ArgumentOutOfRangeException("ms", ms, "ms should be grater than 0.");

            if (_delay != 0)
                throw new InvalidOperationException("Can't start, already started.");

            _delay = ms;
            _timer = new Timer(Execute, this, _delay, Timeout.Infinite);
        }

        public void Reset()
        {
            lock (_timer)
            {
                if (_timer == null)
                    throw new InvalidOperationException("Can't reset the timer, already completed.");

                _timer.Change(_delay, Timeout.Infinite);
            }
        }

        #endregion

        public static DelayRun<T> CreateNew(T target, Action<T> action)
        {
            return new DelayRun<T>(target, action);
        }

        public static DelayRun<T> StartNew(T target, Action<T> action, int ms)
        {
            DelayRun<T> delayRun = CreateNew(target, action);
            delayRun.Start(ms);
            return delayRun;
        }

        public void Execute(object state)
        {
            _resetEvent.WaitOne();
            lock (_timer)
            {
                _timer.Change(Timeout.Infinite, Timeout.Infinite);
            }

            _action.Invoke(_target);
            _resetEvent.Set();
        }

        #region Event Handling

        public event EventHandler<DelayRunEventArgs> EventCompleted;

        public void InvokeEventCompleted(DelayRunEventArgs e)
        {
            EventHandler<DelayRunEventArgs> handler = EventCompleted;
            if (handler != null) handler(this, e);
        }

        #endregion

        #region IDisposable

        public void Dispose()
        {
            lock (_timer)
            {
                if (_timer != null)
                    _timer.Dispose();
            }
        }

        #endregion
    }

    public class DelayRunEventArgs : EventArgs
    {
        public DelayRunEventArgs(IDelayRun delayAction)
        {
            DelayAction = delayAction;
        }

        public IDelayRun DelayAction { get; set; }
    }

    public static class DelayController
    {
        private static readonly IDictionary<string, IDelayRun> _actions = new Dictionary<string, IDelayRun>();

        public static void Add<T>(string key, T target, Action<T> action, int ms)
        {
            if (_actions.ContainsKey(key))
                _actions[key].Reset();
            else
            {
                DelayRun<T> delayRun = DelayRun<T>.CreateNew(target, _ => {});
                _actions[key] = delayRun;
                string localKey = key;
                delayRun.EventCompleted += (sender, args) =>
                {
                    _actions.Remove(localKey);
                    action.BeginInvoke(target, ar => ar.AsyncWaitHandle.WaitOne(), delayRun);
                };
                delayRun.Start(ms);
            }
        }
    }
}
To use this class all you need to do is call the DelayController. The DelayController will handle the creation and the reset process of the DelayRun class. It can handle many delay class at once if they have different key value. Each time the controller Add method is called it either create a new instance of a DelayRun Class of reset the running one.
Here is how you can call it:
DelayController.Add("ValuesOnCollectionChanged", this, m => Recalc(m), 10);
This call will delay the Recalc method call for 10 ms. In the mean time if your program add other values to recalc you can recall this line and the delay will be reset for another 10 ms and so on.
Tell me if this can be helpful in your own projects.

Monday, March 22, 2010

Canadian Developer Connection : Windows Phone 7 Session Videos and Slides, Organized and Explained

Windows Phone 7 @ MIX10: Reports on the new hotness from MIX10 in Las Vegas

The Videos are Up!

It’s only been a couple of days since MIX10 wrapped up, but as promised, we recorded videos of all the sessions and they’re now available online. It doesn’t matter if you missed a session or missed the entire conference, you can now catch (or re-catch) them all. The videos are all “two-shots”; that is, they feature two views: one of the speaker, shown in a window on the left, and one of the current slide, shown in a view on the right. They’re all in Windows Video (WMV) format, and for many of the presentations, the speakers have also made the slides available in PowerPoint (PPTX) format.

The Windows Phone Videos

I’m biased – I’m one of the evangelists designated as a “Windows Phone 7 Champ” – so naturally I consider the Windows Phone 7 Series announcements made at MIX10 to be the most important ones of the conference. (Don’t worry, I’ll talk about the other things I saw at MIX in a later article.)

I’m a believer in “The Power of the Obvious”. Sometimes, there’s great power and utility in taking information that’s already out there and rearranging it in a way that makes it even more useful. That’s why I decided to take the listing of all the MIX10 session videos, pick out the ones applicable to Windows Phone 7 development and rearrange them into the three lists below:

I’ve listed each session with:

  • Its code and title – not the title that appears in the program, but the title that the presenters actually used (some were changed at the last minute)
  • A brief description of the session
  • A “You should watch it if” list to give you an idea of whether the presentation is relevant to you
  • Links to the video of the presentation, and if available, the slides

All told, there’s more than 18 hours’ worth of Windows Phone video.

Canadian Developer Connection : Windows Phone 7 Session Videos and Slides, Organized and Explained

Thursday, March 18, 2010

How to use strongly-typed name with INotifyPropertyChanged

You may already have read my posts about how to use INotifyPropertyChanged in a type-safe way (here and here), but sometime you don’t want to modify all your classes to use this method. All you want is avoid the use of a magic string to define the property. Your code will be refactoring proof.

For example let say you have this property:

public string FirstName
{
    get { return _firstName; }
    set 
    {
        if (_firstName == value)
            return;
        _firstName = value;
        RaisePropertyChanged("FirstName");
    }
}

Some refactoring tool, like Resharper, will be able to change the “FirstName” string but not Visual Studio itself. The solution? Replace this string with a strong type value. How? Let’s assume we can do this:

public string FirstName
{
    get { return _firstName; }
    set 
    {
        if (_firstName == value)
            return;
        _firstName = value;
        RaisePropertyChanged(this.NameOf(p => p.FirstName));
    }
}

Notice that you must specify the “this” keyword to make it work. That is exactly What this extension method let you do:

public static class ObjectExtensions
{
    public static string NameOf<T>(this T target, Expression<Func<T, object>> propertyExpression)
    {
        MemberExpression body = null;
        if (propertyExpression.Body is UnaryExpression)
        {
            var unary = propertyExpression.Body as UnaryExpression;
            if (unary.Operand is MemberExpression)
                body = unary.Operand as MemberExpression;
        }
        else if (propertyExpression.Body is MemberExpression)
        {
            body = propertyExpression.Body as MemberExpression;
        }
        if (body == null)
            throw new ArgumentException("'propertyExpression' should be a member expression");

        // Extract the right part (after "=>")
        var vmExpression = body.Expression as ConstantExpression;

        // Extract the name of the property to raise a change on
        return body.Member.Name;
    }
}

You can even use it in your property changed handler:

private void OnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
    if (args.PropertyName == this.NameOf(p => p.FirstName))
    {
        // ...
    }
}

Enjoy!

Monday, February 15, 2010

Patch for VS 2010 RC Intellisense Crash Issue Now Available - ScottGu's Blog

Crash Symptom

If you are encountering frequent VS 2010 crashes when you are typing in the editor while Intellisense is popping up and/or being dismissed then you are running into this issue.

Patch Now Available

This morning we made available a VS 2010 RC patch which fixes this issue. You can download and run it here.

Please apply it if you are encountering any crashes with the VS 2010 RC, or if you have a tablet, multi-touch, screen-reader or external devices attached (including Wacom tablets, phones/ipods, and others that connect via USB).

Please make sure to submit any issues you encounter with the VS 2010 RC to us via the connect.microsoft.com web-site. Once you’ve entered the issue there please send me email (scottgu@microsoft.com) with a pointer to the issue and I’ll make sure the appropriate team follows up quickly.

Hope this helps,

Scott

[Via Patch for VS 2010 RC Intellisense Crash Issue Now Available - ScottGu's Blog]

Friday, February 12, 2010

Parallel Programming with .NET : FAQ :: Which .NET language is best for parallelism?

The new parallelization support in the .NET Framework 4 is implemented purely in libraries and the runtime and does not require special compiler support. Therefore, it is available to all compliant .NET languages. This includes all of the managed languages that ship as part of Visual Studio 2010 (Visual C#, Visual Basic, Visual F#, and C++/CLI) as well as other Microsoft-provided languages (e.g. IronPython) and 3rd-party developed languages. In fact, our samples available athttp://code.msdn.microsoft.com/ParExtSamples include examples in multiple languages.

However, some of the APIs in .NET 4 have been designed with certain language capabilities in mind. For example, C#, Visual Basic, and F# all support lambda expressions and closures, which enable easily defining the bodies for Tasks and parallel loops. Query comprehensions in C# and Visual Basic, and sequences in F#, can help to write cleaner, more elegant PLINQ queries. F#’s support for asynchronous workflows and its provision of immutability of data by default are geared towards making it easier to write highly concurrent applications.

In summary, you can introduce parallelism in your application using any .NET language. Which one is best still depends on your scenario.

From:

Parallel Programming with .NET : FAQ :: Which .NET language is best for parallelism?

Thursday, December 24, 2009

Microsoft TechEd North America 2010 - Home

Give the gift of technical education, and save US$300 on the full Tech·Ed conference fee.
Microsoft TechEd North America 2010 - Home

Wednesday, November 25, 2009

Now Available: patterns & practices Application Architecture Book

via J.D. Meier's Blog de J.D. Meier le 05/11/09

AAG2FrontCover-Small The Microsoft Application Architecture Guide, 2nd edition, is now available on Amazon and should be available on the shelf at your local bookstores soon.  The PDF was downloaded ~180,000 times.  This is the Microsoft platform playbook for application architecture.  You can think of it as a set of blueprints, and as your personal mentor for building common types of applications on the Microsoft platform:  mobile, RIA, services, and Web applications.

The backbone of the guide is an information model for the application architecture space.  It's a durable and evolvable map to give you a firm foundation of principles, patterns, and practices that you can overlay the latest technologies.  It's your "tome of know-how."  While it's not a step-by-step for building specific applications, it is a pragmatic guide for designing your architecture, with quality attributes, key software principles, common patterns, and architectural styles in mind.  It's holistic and focused on the key engineering decisions where you face your highest risks and most important choices.

Key Features of the Book
The book has several compelling features for slicing and dicing the application architecture body of knowledge:    

  • Canonical Frame.  This describes at a meta-level, the tiers and layers that an architect should consider. Each tier/layer will be described in terms of its focus, function, capabilities, common design patterns and technologies.
  • Application Types.  These are canonical application archetypes to illustrate common application types: Mobile, Rich Client, RIA, Services, and Web applications.  Each archetype is described in terms of the target scenarios, technologies, patterns and infrastructure it contains. Each archetype is mapped to the canonical app frame. They are illustrative of common application types and not comprehensive or definitive.
  • Quality attributes.  This is a set of qualities and capabilities that shape your application architecture: performance, security, scalability, manageability, deployment, communication, etc.
  • Cross-cutting concerns.  This is a common set of categories for hot spots for key engineering decisions: Authentication, Authorization, Caching, Communication, Configuration Management, Exception Management, Logging and Instrumentation, State Management, and Validation.
  • Step-by-Step Design Approach.
  • Principles, patterns, and practices.   Using the application types, canonical frame, and cross-cutting concerns as backdrops, the guide provides an overlay of relevant principles, patterns, and practices.
  • Technologies and capabilities.  The guide provides an overview and description of the Microsoft custom application development platform and the main technologies and capabilities within it.

Contents at a Glance
The full Microsoft Application Architecture Guide is available for free on MSDN in HTML.  This is the contents of the guide at a glance:

Chapters

Appendices

The Team
Here is the team that brought you the guide:

  • Core Dev Team: J.D. Meier, Alex Homer, David Hill, Jason Taylor, Prashant Bansode, Lonnie Wall, Rob Boucher Jr, Akshay Bogawat
  • Test Team - Rohit Sharma, Praveen Rangarajan, Kashinath TR, Vijaya Jankiraman
  • Edit Team - Dennis Rea
  • External Contributors/Reviewers - Adwait Ullal; Andy Eunson; Brian Sletten; Christian Weyer; David Guimbellot; David Ing; David Weller; Derek Greer; Eduardo Jezierski; Evan Hoff; Gajapathi Kannan; Jeremy D. Miller; John Kordyback; Keith Pleas; Kent Corley; Mark Baker; Paul Ballard; Peter Oehlert; Norman Headlam; Ryan Plant; Sam Gentile; Sidney G Pinney; Ted Neward; Udi Dahan
  • Microsoft Contributors / Reviewers - Ade Miller; Amit Chopra; Anna Liu; Anoop Gupta; Bob Brumfield; Brad Abrams; Brian Cawelti; Bhushan Nene; Burley Kawasaki; Carl Perry; Chris Keyser; Chris Tavares; Clint Edmonson; Dan Reagan; David Hill; Denny Dayton; Diego Dagum; Dmitri Martynov; Dmitri Ossipov; Don Smith; Dragos Manolescu; Elisa Flasko; Eric Fleck; Erwin van der Valk; Faisal Mohamood; Francis Cheung; Gary Lewis; Glenn Block; Gregory Leake; Ian Ellison-Taylor; Ilia Fortunov; J.R. Arredondo; John deVadoss; Joseph Hofstader; Koby Avital; Loke Uei Tan; Luke Nyswonger; Manish Prabhu; Meghan Perez; Mehran Nikoo; Michael Puleio; Mike Francis; Mike Walker; Mubarak Elamin; Nick Malik; Nobuyuki Akama; Ofer Ashkenazi; Pablo Castro; Pat Helland; Phil Haack; Rabi Satter; Reed Robison; Rob Tiffany; Ryno Rijnsburger; Scott Hanselman; Seema Ramchandani; Serena Yeoh; Simon Calvert; Srinath Vasireddy; Tom Hollander; Wojtek Kozaczynski

Application Architecture Knowledge Base
The guide was developed in conjunction with our Application Architecture Guide v2.0 Knowledge Base Project. The knowledge base project was used to inform and steer the guide during its development. The Application Architecture Knowledge Base includes a large amount of material that expands on specific topics in the main guide. It also includes draft material from the main guide that is targeted and packaged for more specific audiences, such as the Pocket Guide series.

Key Links at a Glance
Here are the key links at a glance:

Thursday, October 15, 2009

10/GUI: Fascinating Multitouch User Interface Design

If you want to see what the next generation of UI might look like, take a look at this concept.

Link: 10/GUI via Gizmodo