CodeStock 2010 Sessions

Hello everyone!

I have a few sessions submitted to CodeStock 2010 this year!  These sessions are on the multi-touch and Silverlight 4 Validation topics I have been looking into recently.  If you enjoyed the blogs and want more detail and guidance on the topics please vote for my sessions!

You can find them at

http://www.codestock.org/Sessions/intro-to-touch-and-multitouch-in-wpf-and-silverlight.aspx

http://www.codestock.org/Sessions/model-validation-in-silverlight-4.aspx

Thanks again and have a good day!

No Comments

Silverlight 4 INotifyDataErrorInfo

Hello everyone!

So recently I have been looking into Silverlight 4’s new INotifyDataErrorInfo interface for a solution to validation.  I have to say that I really like how this works.

I have built a sample validation framework that models can use to build a simple and easy-to-use system for adding validation that is supported by Silverlight.

You can download the sample code here, but let’s look at a few things.

First let’s take a look at the basics of the Interface.  INotifyDataErrorInfo has three primary items:

  • event ErrorsChanged
  • IEnumerable GetErrors(string propertyName)
  • bool HasErrors

The ErrorsChanged event is the key to validation notification in this system.  When ErrorsChanged is fired, a binding that specifies ValidatesOnNotifyDataErrors=True will then call the GetErrors() method with the property name of the property for which the validation rule exists, or null if you want to specify the object as a whole.  So when you create your custom validation engine and you want to notify Silverlight that the validation state for a property (or object) has changed, you will raise this event.

One cool thing to note about the fact ErrorsChanged is an event, is that it can now support async validation rules.  Imagine in your validation system you make an async call back to the server; when it returns, you can raise this event!

private void HandleRuleResult(string propertyName, RuleKey<T> ruleKey, RuleArgs args)
        {
            if (args.IsValid)
            {
                var foundRule = (from re in ErrorMessages
                                 where re.PropertyName == propertyName
                                 && re.RuleIdentifier == ruleKey.RuleIdentifier
                                 select re).FirstOrDefault();

                if (foundRule != null)
                {
                    ErrorMessages.Remove(foundRule);
                    OnErrorsChanged(propertyName);
                }
            }
            else
            {
                var foundRule = (from re in ErrorMessages
                                 where re.PropertyName == propertyName
                                 && re.RuleIdentifier == ruleKey.RuleIdentifier
                                 select re).FirstOrDefault();

                if (foundRule == null)
                {
                    RuleError error = new RuleError() { RuleIdentifier = ruleKey.RuleIdentifier, ErrorMessage = args.Message, PropertyName = propertyName };
                    ErrorMessages.Add(error);
                    OnErrorsChanged(propertyName);
                }
            }
        }

        protected void OnErrorsChanged(string propertyName)
        {
            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

 

The method of GetErrors() is what the system uses in order retrieve the validation errors when it is notified that the validation rules have changed.  The propertyName parameter will be passed either a single property name, for which you will retrieve your rules, or null, which is your key to retrieve all rules for the entire object.  This is helpful for controls like my custom ValidationSummary control.

It is important to note here that this method needs to be able to get the validation messages after the ErrorsChanged event fires. This means in your custom system, you must have stored your broken validation rules in a way where this can be coded to retrieve before you fire the event.

public System.Collections.IEnumerable GetErrors(string propertyName)
        {
            List<string> errors = null;

            if (propertyName == null)
            {
                if (ErrorMessages.Count > 0)
                {
                    errors = new List<string>();

                    foreach (var re in ErrorMessages)
                    {
                        errors.Add(re.ErrorMessage);
                    }
                }
            }
            else
            {
                var foundRules = (from re in ErrorMessages
                                  where re.PropertyName == propertyName
                                  select re).ToList();

                if (foundRules != null && foundRules.Count > 0)
                {
                    errors = new List<string>();
                    foreach (var re in foundRules)
                        errors.Add(re.ErrorMessage);
                }
            }

            return errors;
        }

 

The last piece is the HasErrors property: this is how to notify your objects that the resulting object has errors.  Every time a rule changes you may want to raise OnPropertyChanged for this property and implement its getter in a way where it knows how to count your broken rules.

public bool HasErrors
        {
            get { return ErrorMessages.Count > 0; }
        }

 

So far what we should now realize is that the interface provides us a way to tie our own validation engine directly into Silverlight.  It does not provide a validation engine in itself, but gives you everything you need to notify Silverlight that states have changed.

The sample code posted above provides a sample implementation of how a validation rules engine might be created around this interface.  I was very inspired by CSLA’s (http://www.lhotka.net/) validation rule entry interface so I modeled it somewhat after its pattern.  We have the ability to add rules to our objects via static methods and property names.  These rules are only added once per type and stored statically.  The engine also allows for the creation of async rules and also provides a bindable collection that is populated with broken rules when they are added.

Once again if you would like to download the sample framework and code you can get it here.

I hope you enjoy it and have a good day!

3 Comments

Multi-Touch in WPF and Silverlight

Hello Everyone!

We had a great time at the Columbia Code Camp this year.  A lot of great speakers and volunteers to help with the event.  We had I think around 150 people show up which was amazing since it was snowing, raining and freezing temperatures :) .

I did my multi-touch presentation for the first time and I think it went very well.  Had some great feedback and questions afterwards.

So as promised I am posting  up the materials and a quick explanation of what is available to use for Multi-Touch in WPF and Silverlight.  In the demo code for WPF you will need to change the App.xaml to point to the different demo windows.  You can download the demo code here.

Raw Touch

In both WPF and Silverlight there is a concept called Raw Touch.  These events are close to the mouse events in that they work with a device and a point (position) on the visual.   Here are the events:

WPF

  • TouchDown – Occurs when a touch device touches the visual
  • TouchMove – Occurs when a touch device is down and starts to move across the visual
  • TouchUp – Occurs when the touch device is lifted off the visual
  • TouchEnter – Occurs when the touch device is down and while moving enters a new visual
  • TouchLeave – Occurs when the touch device is down and while moving leaves a visual

Silverlight

  • Touch.TouchFrameReported – Static Event that is fired any time a touch device activates on a visual

In WPF we can attach handlers to the above events to an individual element and they will only fire when touch is activated on that visual.  For Silverlight however we do not have this.  The TouchFrameReported event will fire no matter what visual has had touch activated.  It is constantly looking for this event on a frame draw.  Even if you touch your finger down and hold it without moving the TouchFrameReported event is still firing with a Move action.

The key to these events (even the Silverlight one) is the GetTouchPoint or GetTouchPoints methods.  With these methods you can pass in an element and get the point that you are currently touching.  What’s cool about this is that if we have 2 elements one of top of the other, but the element underneath is larger than the we actually touched, we can pass in the element underneath and get the touch point relative to that element instead of the one on top.  So we have a lot of power behind where we can get these touch points in relation to which elements we have defined.

Another key to RawTouch is the Device’s Device Id.  Each unique finger that touches the screen will get a unique device ID.  By utilizing this device ID we can accurately keep track of which finger is performing what action and act appropriately.  By doing this we can now truly write something in Multi-Touch :) .

To see more detail please look at the RawTouch and Gesture demos.  The Gesture demos show how we can write one common library in WPF and Silverlight that can recognize straight line gesture activations and abstractly report them to a handler or command.

Manipulations

One other cool thing that we do have in WPF that we don’t have in Silverlight is Manipulations.  These events take alot of the guess work out of raw touch and simplifies the data passed into the handlers.

The events to take note of are:

  • ManipulationStarting – occurs when a manipulation is triggered and about to start
  • ManipulationStarted – occurs when a manipulation has started
  • ManipulationDelta – occurs when a manipulation has changed its data based on movement
  • ManipulationInertiaStarting – occurs when inertia is about to kick in for a manipulation.

Lets say we want to handle the pinching resize functionality that seems to be common in multi-touch.  Well with RawTouch that would be very difficult as we have to calculate that 2 touch points are moving in opposite directions away from each other.  Then we have to calculate the difference between them and provide a scale vector.  This could be a real pain to do in RawTouch.

With Manipulations all of that hard work is done for us.  When the ManipulationDelta event fires the args provide a DeltaManipulation with a Scale property.  This Scale is the vector difference of our resize.  If Scale is not populated then we know we did not do a resize.  We are also provided with a Rotate that is a decimal in the degree change and a Translate which handles straight movement.  Manipulations make it very easy to get started with multi-touch.

Inertia is a cool way to provide smooth deceleration transitions from a manipulation to a stopping point.  Lets say you move a rectangle across the screen but you don’t want it to stop immediately when you lift your finger, but instead you want it to keep going and slow down to a stopping point.  Inertia is an easy way to allow this.

When the ManipulationInertiaStarting event fires it has already calculated your velocity for you!  It has determined how much distance was crossed and how fast your manipulation occured to give you this initial velocity.  From this you just provide it a deceleration rate to tell it how fast it needs to slow down.  A deceleration rate of 10 inches per second every second could look like this “10.0 * 96 / (1000 * 1000)”.  With this we can control how it slows down when continuing a manipulation.

For more detail on the code please see the demos provided.

 

Well thats the basics of what multi-touch capabilities are provided in WPF and Silverlight.  I hope you enjoyed this topic and enjoy the code!

I will be presenting on this topic in Atlanta at the Atlanta MS Pros user group on March 1st.  I hope to see you there!

1 Comment

Columbia CodeCamp 2010!

Hello Everyone!

Its been a bit since my last blog post, so I thought i would give an update as to what I have been working on.

On January 30th I will be travelling to Columbia, SC to speak at the Columbia CodeCamp!  I have been working hard on a new presentation that will cover the popular topic of Touch and Multi-Touch.

In this presentation I will be going over the different ways Touch and Multi-Touch can be handled in WPF and Silverlight.  It will show things like Raw Touch, Manipulations and Gestures in both of these technologies.  I have about 7 demo’s already coded to show the different ways of accomplishing this as well as a sample on how to build a fully abstracted gesture processor where there is a common code base for both WPF and Silverlight, and it actually works! :)

After I present this for the first time at the Columbia CodeCamp I will be shortly blogging about it and posting the source code.  After that I plan on speaking on this topic somewhere in Atlanta TBD.

If you are in the area for the code camp please drop by, its free, alot of fun and there will be lots to learn.  You can register for the code camp at http://columbiacodecamp.com.

Hope to see your there!

No Comments

WPF Tips and Tricks Part 2 – Panels

Hello Everyone!

First of all, Happy Thanksgiving!  I hope everyone is having a good time and enjoying the holidays.

So it’s been awhile since I started my WPF Tips and Tricks segment and figured it was long overdue for the second installment.  In this part we will look a little bit at Panels and what we need to think about when choosing how we will lay out our forms.

So the primary tip when regarding Panels is that Panels are the “only” visuals in WPF that actually perform any sort of measurement and arrangement calculations.  What this means is that when we create a TextBox and set its Width to 100, the TextBox does not actually draw itself on the screen; the Panel it is contained in will see that it has a TextBox as a child and that its width is 100.  The Panel will then determine where the TextBox needs to be placed inside of itself and if it has enough space to include a width value of 100 and will perform the drawing.

The next tip is thinking of performance.  Lets look at some code to put this into more perspective.

I have created this example layout in 2 different panel formats:

formlayout

Here is the XAML for the first layout that uses a total of 4 StackPanels:

<StackPanel HorizontalAlignment="Left">
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
        <TextBlock Text="Field 1: " VerticalAlignment="Center"/>
        <TextBox Width="100"/>
    </StackPanel>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
        <TextBlock Text="Field 2: " VerticalAlignment="Center"/>
        <TextBox Width="100"/>
    </StackPanel>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
        <TextBlock Text="Longer Field 3: " VerticalAlignment="Center"/>
        <TextBox Width="100"/>
    </StackPanel>
</StackPanel>

Having 4 StackPanels means we have 4 different processes to run measurement and arrangement.  The first StackPanel performs measurement and arrangement; when it gets to its first child, that StackPanel will call measurement and arrangement on its children and return up to the first StackPanel. The first StackPanel will then iterate to its second child which performs another set of measurement and arrangement calculations and so on for each StackPanel  child  – causing 4 calculations.  In more complex scenarios this will not be be very performant.

Now lets look at the second, more performant way to lay out this form:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="100"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <TextBlock Text="Field 1: "
               Grid.Column="0"
               Grid.Row="0"
               HorizontalAlignment="Right"
               VerticalAlignment="Center"/>
    <TextBox Grid.Column="1"
             Grid.Row="0"/>

    <TextBlock Text="Field 2: "
               Grid.Column="0"
               Grid.Row="1"
               HorizontalAlignment="Right"
               VerticalAlignment="Center"/>
    <TextBox Grid.Column="1"
             Grid.Row="1"/>

    <TextBlock Text="Longer Field 3: "
               Grid.Column="0"
               Grid.Row="2"
               HorizontalAlignment="Right"
               VerticalAlignment="Center"/>
    <TextBox Grid.Column="1"
             Grid.Row="2"/>
</Grid>

With this format we have a lot more XAML to write, but we get a much more performant way to lay out the exact same visual content.  We have only one panel; this panel will perform one set of measurement and arrangement calculations.

So looking at it all: the tip here is to really think about performance when dealing with Panels.  The least amount of Panels we can use (as long as we can meet the form requirements), the more performant our WPF applications will be.

I hope you enjoy this and look forward to WPF Tips and Tricks Part 3!

No Comments

Augusta CodeCamp

Hello everyone!

So last Saturday I took trip over to Augusta to speak at their first annual CodeCamp.  We had alot of fun and learned alot while there.  This was also my first CodeCamp presentation outside of my local area!

There was a cancellation of a spot right before my slotted spot so I stepped up and did an inpromptu adhoc session on Intro to WPF.  This was interesting since I had nothing prepared.  I tried to show as much code samples and different concepts in WPF and in the end it went very well.  A few people came up to thank me for the presentation because they knew it would be difficult being last minute but they learned alot.

After that session I did a revised version of my WPF Custom Controls presentation.  In this one we built the basics of a NumericUpDownTextBox from scratch to go over the concepts, then looked at a pre-built one I did that was alot more robust.  You can download the presentation materials here.

If you made it to the CodeCamp then I hope you enjoyed it!

Cheers

No Comments

CEDG

Hello Everyone!

So i traveled to Columbia, SC this past monday to talk at CEDG.  We had a good talk and a good time.  After the presentation we went to Longhorn for some more talks over some drinks.

I tweaked my previous Prism/MVVM topic for this presentation and I think overall it was a success.

You can download the presentation materials here.

If you came by I hope you enjoyed the presentation!

No Comments

Speaking at the Columbia Enterprise Developers Guild

Hello Everyone!

So I wanted to announce that next Monday on October 26th, I will be traveling to Columbia, SC to speak at the Columbia Enterprise Developers Guild.  You can visit their website here.

I will be speaking about how you enhance your WPF applications with the MVVM design pattern and Prism.

Here is the topic blurb.

“Model-View-ViewModel (MVVM) is a UI Design Pattern that fits well with WPF and Silverlight. It utilizes key components of XAML-based technologies like DataBinding and Commanding to provide a level of separation between visual representation, business functionality and business data design. In this topic we review the overall concept of MVVM and available design tools. We will demonstrate the use of Bindings to facilitate data interaction and business process execution in a way that allows us to take full advantage of designer/developer collaboration. We will also take a dive into Microsoft’s Composite Application Library (Prism 2) to see what tools it provides to facilitate many common UI design patterns and other WPF application framework concepts. This topic assumes Intermediate knowledge of WPF including a basic understanding of XAML, Templates and Binding.”

If you are in the area, please stop by as I think it will be a fun and knowledgeable session!

No Comments

Razre WPF Framework

Hello all!

I have just released the Razre WPF Framework to CodePlex.  You have visit it here.

The framework provides the following functionality.

  • A Navigation system to a MainRegion.  Can provide a dynamic, custom transition animation.
  • A DataTemplate View resolution implementation of the Model-View-ViewModel (MVVM) UI design pattern.
  • A full Layout theming mechanism to swap out the entire visual representation of a ViewModel.

Each of the systems are integrated with each other to provide a robust and performant mechanism in which to provide this functionality in a new WPF application.

The sample application needs alot of work right now from the visual standpoint, but I think the code is fairly well organized to show how this framework can be used.

I will be adding new functionality to the framework as time goes by, so look for some cool updates to it.

I hope everyone finds the framework helpful and as always, Happy Coding!

No Comments

WPF Tips and Tricks Part 1

So I was at the local Atlanta Silverlight Meetup last night and we got on the topic what you get and dont get from most training programs for WPF and Silverlight.  While there are some out there that are very good about providing the full in-depth knowledge of WPF programming there are sometimes items that are very important to know but get left out.  I refer to these as Tips and Tricks.  I talked about some of them and found out most of them had not run into these scenario’s and understanding of what WPF does.  I have found some of these out on the web already but I wanted to do a blog series of the Tips and Tricks I find to be very good to understand.

The first tip I end up giving when talking to people who are new to WPF is about a situation with Converters.  I find that when Converters are first seen they are loved and then used everywhere.  Well a Converter is not as performant as a Trigger.  A lot of the time I see converters created that could very easilly be represented as a trigger and by swapping out all of the converters with the triggers we saw a good performance increase.  So my first tip is “Try to not use converters if you dont have to, see if you can find a way to use a trigger to achieve the same result”.

Part 2 coming soon!

No Comments