Code and Slides from Milwaukee WinRT

by Damon Payne 12. October 2011 22:57

Here are the slides and sample apps from the //Build Conference and WinRT intro

Slides

Code

 

Tags:

Technical Community | WinRT

Speaking: Build and WinRT in Milwaukee

by Damon Payne 9. October 2011 20:32

This coming Tuesday, October 11th I will be speaking at the Milwaukee .NET User's Group on the topic of the recent Microsoft //Build conference. 

Microsoft has shown us a glimpse of the Windows 8 platform and the future of application development. What does that mean for us as .NET developers: are Silverlight and WPF dead? What is WinRT? Do I have to learn HTML 5 and C++? Please join us for a discussion of these topics and a healthy amount of Windows 8 development examples.

You can find registration details here: http://www.wi-ineta.org/DesktopDefault.aspx?tabid=23

There will be a little bit of "Here look at how cool Windows 8 is" but that type of presentation is only fun in large scale keynotes in my opinion.  We'll be going over some WinRT applications and hopefully answering a lot of your questions about the future directions for development on Windows platforms.  I'll be presenting from a Windows 8 laptop and will be able to show anything you'd like to see of the OS itself or the developer preview tooling.

Tags:

Technical Community | WinRT

Still Here

by Damon Payne 5. October 2011 14:19

Yes, I took the entire month of September off of blogging.

No, I’m not sorry.  Sometimes you just need a break.

Cheers,

Damon

Tags:

In Indianapolis this Thursday!

by Damon Payne 9. August 2011 10:53

{Edit: due to personal illness this talk is cancelled/postponed.  Indy NDA will still be meeting!}

This week Thursday I'll be speaking at Indy NDA!  http://www.indynda.org/

I'll be talking about Silverlight 5 this time, and taking things in some different directions than I have in the past.

Silverlight is not dead! Contrary to what you might be hearing Microsoft is still making big investments across the XAML development stack and that includes Silverlight. Come check out a survey of what's new in Silverlight 5. Examples from real-world Silverlight 5 business applications will be included, going far beyond the usual demos. We will also discuss silverlight's place in the developer ecosystem.

I hope to see some familiar faces there.

 

 

Tags:

Silverlight | Technical Community

You'd have to be stupid to use IE

by Damon Payne 2. August 2011 13:57

I love it when news like this comes out: http://www.bbc.co.uk/news/technology-14370878

This is isntantly jumped on by the anti-Microsoft crowd to indicate you'd have to be stupid to use Internet Explorer, scientific proof that Micro$oft sucks and everything that does not come from Redmond is superior like you've been told all along.

I'm not a statistician, but let me attempt to refute this.

  1. Last I heard, Windows still has over 90% of the desktop OS market. 
  2. Windows users overwhelmingly stick with IE because they are not tech geeks and IE is already there.
  3. People who go out of their way to install Chrome/Opera/Firefox tend to be tech geeks of some sort who think those browsers are better (they may very well be better but my Mom has no reason to think so), or are doing software development themselves, or have ideological issues with Microsoft.
  4. Tech geeks tend to be far above average intelligence.

The overwhelming majority of users, who don't know and don't care, skew the results.  I don't think I'm the only one to come to this conclusion but I've seen just enough people actually take this study to seriously mean "If you don't install Chrome your very intelligence is suspect" that I needed to go on record.

Peace.

{Edit: the study was later revealed to be a hoax anyway! http://www.winrumors.com/internet-explorer-users-arent-dumb-study-was-a-hoax }

Tags:

Technical Community

2011 Microsoft MVP

by Damon Payne 5. July 2011 10:48

I have once again been awarded the Microsoft MVP Award in the Client App Dev category for 2011!  It was a pretty busy year of traveling and speaking from July 2010 to July 2011, although the blogging has suffered of late.  This will be fixed shortly.

I've got some big things cooking for this year and I'm looking forward to working with my fellow MVPs and of course Microsoft.

Tags:

Technical Community

Edgenet Product Data Live on Bing.com !

by Damon Payne 30. June 2011 20:32

Several times since last summer, I have written about my massive data collection projects at Edgenet/BigHammer.  This has been a long time in coming, but product data is now live on Microsoft Bing!  We have partnered with Microsoft Bing to get the best product data in the business to be factored into Bing Shopping search results.  The user facing portions of our data collection efforts amount to what I assume is one of the largest production Silverlight 4 applications out there.

Here are some bing shopping search results:

http://www.bing.com/shopping/radiator/specs/A06F16EAAD0436415011?q=radiator

http://www.bing.com/shopping/control-arm-bushing/p/F7AE8AE1EFFB4F7D5011?q=control+arm+bushing

http://www.bing.com/shopping/fx-extruded-aluminum-running-boards-in-chrome/specs/B05C7327DC76E4465011?q=FX+Extruded+Aluminum+Running+Boards+in+Chrome&FORM=CMSMSP

If you scroll down to each page below the images and specifications you'll see the Data from edgenet logo.

Read more at: http://bing.edgenet.com/

 

Tags:

Architecture and Design | Silverlight | Technical Community

Speaking at Milwaukee Area Silverlight SIG

by Damon Payne 5. June 2011 19:03

Long ago, when Silverlight 2 was new, we had a Silverlight User Group in Milwaukee.

Tuesday, June 7th we are re-launching the Milwaukee Silverlight Special Interested Group.  I will be presenting on the topic "What's new in Silverlight 5".  I would highly suggest attending this meeting if you are a Silverlight or Windows Phone 7 developer or at all interested in these topics.  We will be looking to talk to local developers about what Silverlight topics interest them and will also be recruiting presenters for future meetings.

A location map and registration can be found here:  http://www.wi-ineta.org/DesktopDefault.aspx?tabid=192 .  I hope to see you there!

Tags:

Silverlight | Technical Community | Windows Phone 7 Development | WindowsPhone7

Using ICustomTypeProvider in Silverlight 5

by Damon Payne 14. April 2011 13:55

Why would I want to trick Silverlight into treating Dictionary values like real Properties?
There are scenarios when complex, data-intensive applications will need to data bind to keys/value pairs or generally determine the properties of a Class at runtime.  In cases where there could be large numbers of keys or the keys could change without an application re-deploy, this is a tricky problem to solve.  I wrote about using Reflection Emit for two-way data binding to dictionaries quite a while ago.

In Silverlight 5, however, you can use ICustomTypeProvider to achieve the same goal in a clean fashion.

Data Facets

Some systems, such as Pivot Viewer, allow you to specify any number of pseudo-Properties about interesting items, which we’ll call Facets.  Using a structure like a Dictionary, we could specify any number of Facets.  Two-way data binding to these is problematic however since they aren’t real CLR properties.  In the full .NET Framework you can do tricks with ICustomTypeDescriptor, and now in Silverlight 5 we have System.Reflection.ICustomTypeProvider.
Let’s create a simple Facet class to represent data about the Facet we’d like to data bind to.

/// <summary>
/// Some facet of a dynamic type
/// </summary>
public class Facet
{
    /// <summary>
    /// Must be a valid CLR property name
    /// </summary>
    public string PropertyName { get; set; }

    public Type PropertyType { get; set; }

    //Couple of demo Facets

    public static Facet DynamicDemo0 = new Facet
    {
        PropertyName = "DynamicPropZero",
        PropertyType = typeof(string)
    };

    public static Facet DynamicDemo1 = new Facet
    {
        PropertyName = "DynamicPropOne",
        PropertyType = typeof(double)
    };
}

Next we’ll create an object with a regular CLR property and a dictionary to store key/value pairs.  These key value pairs will be made binding-friendly.

/// <summary>
/// An Class with normal properties, but also supporting dynamic properties
/// </summary>
public class FacetedObject : ICustomTypeProvider, INotifyPropertyChanged, INotifyDataErrorInfo
{
    Dictionary<string, object> _facetValues;

    public object this[string key]
    {
        get
        {
            if (!_facetValues.ContainsKey(key))
            {
                return null;
            }
            return _facetValues[key];
        }
        set
        {
            _facetValues[key] = value;
            OnPropertyChanged(key);
        }
    }

The interesting thing here is the ICustomTypeProvider interface implementation. 

ICustomTypeProvider Implementation

On any CLR object you can call GetType().  If you’ve ever done any reflection programming you’re aware of all the rich runtime metadata about your classes that System.Type can provide.  System.Type is also an abstract class, and ICustomTypeProvider requires only a single method implementation:

public Type GetCustomType()
{
    return new FacetedObjectType<FacetedObject>(_currentFacets);
}

So, we can create a class that extends System.Type and do some interesting things.  We can trick the Silverlight runtime into thinking our Facets are real CLR Properties.  While my FacetObjectType<TSource> implementation is about 300 lines long, here’s the most interesting part:

/// <summary>
/// A custom System.Type implementation that can provide different Properties at runtime. 
 All operations except those related to
/// Property logic delegated to the type of TSource
/// </summary>
/// <typeparam name="TSource"></typeparam>
public class FacetedObjectType<TSource> : System.Type
{
//snip…


    public override System.Reflection.PropertyInfo[] GetProperties(BindingFlags bindingAttr)
    {
        var properties = ProxyTargetType.GetProperties(bindingAttr);

        if (
           BindingFlags.Instance == (bindingAttr & BindingFlags.Instance)
        && BindingFlags.Public == (bindingAttr & BindingFlags.Public)
        )
        {
            var dynamicProperties = GetPublicDynamicProperties();
            var allprops = new List<PropertyInfo>();
            allprops.AddRange(properties);
            allprops.AddRange(dynamicProperties);
            return allprops.ToArray();
        }
        return properties;
    }
//snip…

So, for system types that implement ICustomTypeProvider, we can intercept important requests for reflection information and supplement that information.  In our case here, we can claim that properties exist that aren’t really on our class at compile time.  In terms of telling the runtime how to actually Get and Set these dynamic properties, we need to create a class that extends PropertyInfo.  Here’s a type called DynamicPropertyInfo, and the two most interesting methods:

public class DynamicPropertyInfo : PropertyInfo
{
    public DynamicPropertyInfo(Type propertyType, Type declaringType, string propertyName)
    {
        _propertyType = propertyType;
        _declaringType = declaringType;
        _name = propertyName;
    }

    public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder,
        object[] index, System.Globalization.CultureInfo culture)
    {
        var fo = obj as FacetedObject;
        return fo[Name];
    }

    public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder,
        object[] index, System.Globalization.CultureInfo culture)
    {
        var fo = obj as FacetedObject;
        fo[Name] = value;
    }

In here, we can just use the this[] indexer of our FacetedObject class to get and set values.

NoteI’m only showing basic custom properties here, but there’s a lot more you can do with ICustomTypeProvider.  Most of the methods in FacetObject<TSource> and DynamicPropertyInfo just delegate to the original Type.  I’d love comments/email on specific scenarios you’re interested in.

Demo App

To show how this concept works, let’s create a Silverlight 5 application with a DataGrid.  We’re going to get the datagrid to display “properties” that technically speaking are not there.  First we’ll create a couple of Facets assigned to FacetedObject by default called “DynamicPropZero” and “DynamicPropOne”.  For these two we can create DataGridColumns along with an actual compile-time Property of FacetedObject.

            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="Id" IsReadOnly="True" Binding="{Binding Id}" />
                <sdk:DataGridTemplateColumn Header="Dynamic Property 0">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding DynamicPropZero, Mode=TwoWay, 
                                NotifyOnValidationError=True,
                                ValidatesOnNotifyDataErrors=True,
                                ValidatesOnDataErrors=True,ValidatesOnExceptions=True}"/>
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate>
                </sdk:DataGridTemplateColumn>
                <sdk:DataGridTextColumn Header="Dynamic Property 1"
                                        Binding="{Binding DynamicPropOne, Mode=TwoWay}" />
            </sdk:DataGrid.Columns>

Here’s the code we’re using to create the sample data in our main ViewModel.  Note that we're going to explose the dictionary values as properties.

public class ShellViewModel : INotifyPropertyChanged
{
    public ShellViewModel()
    {
        Items = new ObservableCollection<FacetedObject>();
        var d0 = new FacetedObject();
        d0[Facet.DynamicDemo0.PropertyName] = "I'm a property!";
        d0[Facet.DynamicDemo1.PropertyName] = 42.42;

        var d1 = new FacetedObject();
        d1[Facet.DynamicDemo0.PropertyName] = "Would you like to be a property too?";
        Items.Add(d0);
        Items.Add(d1);

And as you can see, it works:

BindingApp0

Notice the buttons above the DataGrid.  These dynamic properties wouldn’t be very useful unless they are first-class citizens, and they are.  Note that FacetedObject also implements INotifyPropertyChanged and INotifyDataErrorInfo.  By clicking the buttons we fire commands that affect changes in code, and the UI reflects the changes for the dynamic properties.

BindingApp1

Now, recall at the beginning that I said this could be completely dynamic and that we could actually create both the Facet data and visuals in a data driven fashion at runtime.  Clicking on the Add Facet button demonstrates this.

BindingApp2

After clicking OK, we can do some work to add this Fact to the items on the ViewModel, and also dynamically create a new DataGridColumn to display the data.

public void AddNewFacet(string name, object defaultValue, string clrType)
{
    var typeDict = new Dictionary<string, Type>();
    typeDict["string"] = typeof(string);
    typeDict["int"] = typeof(int);
    typeDict["double"] = typeof(double);

    //1. Create a new Facet
    var newFacet = new Facet
    {
        PropertyName = name,
        PropertyType = typeDict[clrType]
    };

    //2. Tell objects to clear out cached state
    //3. Assign a default value we can see in the UI
    var vm = DataContext as ShellViewModel;
    
    foreach (var item in vm.Items)
    {
        item.AddFacet(newFacet);
        item[newFacet.PropertyName] = defaultValue;
    }

    //4. create visuals to bind to new facet
    var sb = new StringBuilder("<DataTemplate 
xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" >")
    .Append("<TextBox Text=\"{Binding  ")
    .Append(name)
    .Append(", Mode=TwoWay}\" />")
    .Append("</DataTemplate>");

    var dt = (DataTemplate)XamlReader.Load(sb.ToString());
    var column = new DataGridTemplateColumn();
    column.Header = name;
    column.CellTemplate = dt;
    FacetGrid.Columns.Add(column);
}

Our new DynamicProperty is now shown in the DataGrid and we can edit it with two-way binding support:

BindingApp3

For some, this last piece of code will look like the worst kind of voodoo, but there are cases where your requirements will dictate this level of flexibility and this combination of techniques will help you get there.

Conclusion

You can see a lot of other places you could take this.  Download the source code and you’ll see some comments.  For one example, you could easily extend this sample to add System.ComponentModel.DataAnnotations attributes to your properties to have automatic validation from the Controls that support it.  This method is much cleaner than the reflection Emit route and gets away from some of the issues that route can cause.
It’s always been easy to accomplish extreme feats of dynamism in XAML by using XamlReader but ICustomTypeProvider brings a new level of runtime fun to your data types.

Demo Solution Source:

DamonPayne.CustomFacetBinding.zip (646.97 kb)

Tags:

Architecture and Design | Silverlight

Another Journey of Learning and Teaching is Coming

by Damon Payne 1. April 2011 21:15

Back in September of 2008 during the Silverlight 2 era I wanted to do a proof of concept for a Silverlight design surface.  I called this Argentum Tela.  My goal was to take a complex project and blog about the various design decisions that were made, why they were made, and to just have fun.  The project started here on my blog and ended here on codeplex.  I still get a lot of questions about this project and I've had some people use it in commercial business apps.

I don't have all the answers, I'm a fellow traveler on this road; however I have been doing a lot of complex Silverlight applications for more than three years now and along the way I've formed some patterns and practices.  For the next couple of months I'll be sharing that knowledge with you.

Tags:

Architecture and Design | Silverlight

About the author

Damon Payne is a Microsoft MVP specializing in Smart Client solution architecture. 

INETA Community Speakers Program

Month List

Page List

flickr photostream