DCSIMG
Pavel's Blog
Sign in | Join | Help

Pavel's Blog

Pavel is a software guy that is interested in almost everything
software related... way too much for too little time

My Wish List for Windows “Blue”

Published at May 17 2013, 05:48 PM by pavely

Many rumors are flying around at this time about the upcoming release of Windows 8.1 (code named “Blue”, which represents a wave of product updates, including Windows Phone and others). I thought I‘d state my hopes for this release, not just in terms of user features, but also from a developer’s perspective. As a developer, I spend most of my time on my trusty laptop, not some tablet based device. Naturally, the desktop world is my friend.

  1. The Windows 8 Start screen is close to perfect for tablet devices, but for the desktop – it’s practically useless. With many programs installed, it’s difficult to find anything in there. I use the excellent search facility of Windows 8 – just press the Windows key and start typing (although I wish all the search results would show  - not separated to Apps, Settings and Files). This brings me to the first request – the Start button. Yes, it’s been rehashed quite a bit, but the organization of folders and shortcuts is invaluable and should be back at least on non-tablet devices, but preferably in Windows 8 Pro versions as well, as these devices are often used for development. And no, third party tools and extensions are not an acceptable solution.
  2. Allow running Windows Store apps in a Window, not just full screen – this is also a popular request – and why not? In a tablet world this may be too much – but the desktop? Let me run what I want in whatever size I see fit. There’s really no reason not to allow this. If not that, at least allow more than one app to run concurrently in full screen in different monitors. A pretty typical development setting includes 2 or 3 monitors – I wish we had the freedom to use these as we see fit.
  3. On the actual development front we have WinRT, which is a new platform based on the familiar COM foundation that has various “projections” to languages, such as C++, C# and JavaScript. However, this is only available (at least on the UI side) to Store apps. But why should that be? In the .NET world, there is WPF – arguably the most powerful UI platform on Windows. C++ developers had to use old libraries such as MFC to do their UI – but this model is still limited to the HWND-based Win32 behavior and restrictions. WPF gets rid of HWNDs, which is a major part of its power and flexibility. Now similar power exists for C++ developers but only under WinRT. Why should that be? Let’s have the power of no HWNDs in native code, too. All the required platform components are already there – Direct2D (which is really how XAML is rendered in WinRT), Direct Composition, the Windows Imaging Component (WIC), the Windows Animation Manager, Windows Media Foundation and more – it’s just a matter of allowing XAML usage in desktop apps, not just Store apps.
    I’ve had customers that have been using MFC for years and exposed to WPF ask me more than once – why is there no WPF-like library in native code? Indeed, why? I remember in the beta days of WPF (then called “Avalon”), I searched the MSDN docs relentlessly, trying to find the native library that Avalon wraps. I was eventually astonished to find that there is none. WPF is a managed only library. But now, after all the WinRT work as been done, what’s stopping it from migrating to the desktop apps world? Nothing, in my humble opinion, and I wish that would happen. With the new C++11 features, a powerful native UI framework is sorely missing.
  4. WinRT is based on ideas starting from WPF, but it’s a lot less powerful. It’s about as powerful as Silverlight 3. Yes, 3; not even 4, not to mention 5. I understand there was a lot of work involved in getting WinRT out there, so not all features could be implemented. I hope more features appear in Windows 8.1, comparable at least to Silverlight 5. I don’t expect the entire WPF library to be implemented, and in fact, some things are better off not being there, but I think it should get close. It’s frustrating working with WPF and then going over to WinRT only to find a lot of things missing.
  5. Open up Windows Phone some more – Windows Phone 8 is certainly more “open” that Windows Phone 7.x. But it’s still pretty closed. One argument for that is the assurance that apps could not exploit the user’s information or device for malicious purposes. Sure, there is that risk. But that what capabilities are for. There is a capability for location awareness, for instance, so the user must consent to the app being installed on his phone (from the Store) based on the app’s advertised capabilities and requirements. I say – add more capabilities, but allow more freedom for phone usage.
  6. While we’re on the phone’s subject – let’s have a window or an app that summarizes the things that have changed while the phone was unattended. Missed calls, messages, tweets, Voip calls, whatever – all in one easy to find list – not scattered around among the various apps as it is today.
    There are other small features I can think of regarding the phone, but this one stands out; I won’t discuss the rest here.

There are more things I wish for the Windows OS – but I think that’s enough for the upcoming release. We’ll have to wait and see how much of it (if any) comes true.

XAML as DSL

Published at May 05 2013, 04:14 PM by pavely

About 3 years ago, when .NET 4 and Visual Studio 2010 were just released, I’ve blogged (part 1, part 2) about the changes that took XAML from its WPF inception to the System.Xaml namespace and System.Xaml.Dll assembly, to be available more generally, not just for WPF. I’ve shown that XAML is just a declarative way of creating objects, setting their properties – sometimes in interesting ways. I did promise at the end of that second post that I’d show how to use attached properties, but never did have the time to deliver. 3 years later, it’s high time I make good on that promise.

The idea of a Domain Specific Language (DSL) is not new. Probably the most well known DSL is SQL – a language for working with databases. A DSL is typically constrained to a specific domain or a specific task (hence the name). A DSL may be a completely new language (such as SQL), and this is termed “external DSL”, and it can be constructed using a specific language semantics, such as C#, by leveraging certain language features that make up the “new” language. in C#, extension methods and “fluent interfaces” are most often used for that task.

What about XAML? The declarative nature of XAML makes it a good candidate to be a DSL. It has simple and strict rules, but it allows extensions, with type converters, markup extensions and attached properties.

An example

Suppose we want to create a text adventure game (“interactive fiction”) language (yes, I know I have a fetish for text adventures…). We could use XAML to describe not just the world that comprises the game, but also the actions that need to take place in certain scenarios.

The first step is to create an object model suitable to describe a text adventure. Here are a few simple classes to get us started:

[Serializable]
[DictionaryKeyProperty("Name")]
[DebuggerDisplay("{Name}")]
public abstract class Entity {
    Dictionary<string, object> _properties;
 
    public string Name { get; set; }
    public IDictionary<string, object> Properties {
        get {
            return _properties ?? (_properties = new Dictionary<string, object>(4, StringComparer.CurrentCultureIgnoreCase));
        }
    }
}
public enum RelativeLocation {
    In, On, Under, Behind
}
 
[Serializable]
[DebuggerDisplay("{Name} ({GetType().Name}) {RelativeLocation} {Location}")]
public abstract class Thing : Entity {
    public Thing() {
        Article = "a";
        Count = 1;
    }
 
    public string Location { get; set; }
    public RelativeLocation RelativeLocation { get; set; }
 
    [TypeConverter(typeof(StringListConverter))]
    public string[] Nouns { get; set; }
 
    [TypeConverter(typeof(StringListConverter))]
    public string[] Adjectives { get; set; }
 
    public string Article { get; set; }
    public bool IsTransparent { get; set; }
    public int Weight { get; set; }
    public int Size { get; set; }
    public string ShortDesc { get; set; }
    public string LongDesc { get; set; }
}
[Serializable]
public class Item : Thing {
    public Item() {
        CanTake = true;
    }
 
    public bool IsOpen { get; set; }
    public bool CanOpen { get; set; }
    public bool IsContainer { get; set; }
    public bool IsLocked { get; set; }
    public string Key { get; set; }
    public bool CanLock { get; set; }
    public bool CanTake { get; set; }
}

A few interesting things here:

  • 1. The DictionaryKeyProperty attribute indicates which property should be considered a key, should such an object be placed in a dictionary. This will allow us to avoid using the more awkward and generic x:Key XAML attribute.
  • 2. The TypeConverter attribute indicates how a string is to be converted to a more complex type, such as the Nouns property:
  • [TypeConverter(typeof(StringListConverter))]
    public string[] Nouns { get; set; }

This particular converter turns a string into an array of strings. Here’s the implementation:

public class StringListConverter : TypeConverter {
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
        var target = context as IProvideValueTarget;
        Type type = null;
        if(target != null) {
            type = (target.TargetProperty as PropertyInfo).PropertyType;
        }
        string svalue = (string)value;
        var words = svalue.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries);
        return type == typeof(string[]) ? (object)words : words.ToList();
    }
 
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
        return sourceType == typeof(string);
    }
}

The code can actually convert to an array of strings or a list of strings (it looks for a comma as a separator to split the words). Converters is one of those things that make XAML friendly, readable and easy to use.

Let’s take a look at something more interesting: markup extensions. Suppose we want to be able to place items in rooms or other containers. For example, a ring may be in the bedroom, or on the table, or in a box. We want to be able to “say” that as easily as possible (we are striving for a DSL). Here’s some XAML that accomplishes this:

<Item Name="ring" Location="{In box}" 
        Nouns="ring" Adjectives="small,diamond" Article="a">
</Item>
<Item Name="box" Location="kitchen" Nouns="box" IsOpen="true">
 
</Item>
<Room Name="kitchen" Attributes="Cold,Dark" ShortDesc="A small kitchen">
</Room>

Note the {In box} location of the ring. To make that work, there must be a class named In or InExtension that accepts a string as a constructor argument. In fact, we can create a bunch of those like so:

public abstract class RelativeLocationExtension : MarkupExtension {
    public RelativeLocation RelativeLocation { get; private set; }
    public string Name { get; private set; }
 
    protected RelativeLocationExtension(RelativeLocation rl, string name) {
        RelativeLocation = rl;
        Name = name;
    }
 
    public override object ProvideValue(IServiceProvider sp) {
        var target = sp.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
        if(target != null) {
            if(target.TargetObject.GetType().IsSubclassOf(typeof(Thing))) {
                target.TargetObject.GetType().GetProperty("RelativeLocation").SetValue(target.TargetObject, RelativeLocation);
            }
            else
                throw new ArgumentException("object must be a thing for a location");
        }
        return Name;
    }
}
 
public class OnExtension : RelativeLocationExtension {
    public OnExtension(string name) : base(RelativeLocation.On, name) {
    }
}
 
public class InExtension : RelativeLocationExtension {
    public InExtension(string name)
        : base(RelativeLocation.In, name) {
    }
}
 
public class UnderExtension : RelativeLocationExtension {
    public UnderExtension(string name) : base(RelativeLocation.Under, name) {
    }
}

Any markup extension must implement the ProvideValue method. The provided IServiceProvider can be used to get the context in which the markup extension is used. The IProvideValueTarget interface is the most common and useful to use. It lets the code know on which object and which property is set with the markup extension. Markup extensions provide a powerful extensibility mechanism that’s still easy to use by our DSL.

Attached properties

WPF invented attached properties, now used in other XAML based technologies. Attached properties are defined by one type but can be set on any object. They are “attached” to objects, providing the idea of context properties. By the way, they don’t have to be dependency properties (as in WPF/Silverlight) in any way. Their implementation is irrelevant to the XAML parser.

In fact, to parse attached properties, the XAML parser requires the defining class to have a static GetXxx and/or SetXxx for the attached property Xxx. In the implementation, we need to store/retrieve the value of the property from some attached property store – conceptually similar to the way WPF manages an attached property – by using some global static variable.

Technically, that store needs to implement the IAttachedPropertyStore interface. Although it’s not difficult to implement (most use a dictionary), .NET provides a default implementation accessible with the convenient AttachablePropertyServices static class. Here’s an example of creating an attached property named Commands.Script (in this case read only):

public static class Commands {
    public static IList<ScriptCommand> GetScript(Entity entity) {
        IList<ScriptCommand> value;
        AttachablePropertyServices.TryGetProperty<IList<ScriptCommand>>(entity, new AttachableMemberIdentifier(
            typeof(Commands), "Script"), out value);
        if(value == null) {
            value = new List<ScriptCommand>();
            AttachablePropertyServices.SetProperty(entity, new AttachableMemberIdentifier(
                typeof(Commands), "Script"), value);
        }
        return value;
    }
}

Now we can use the property like so (for a Room in this example):

<Room Name="kitchen" Attributes="Cold,Dark" ShortDesc="A small kitchen">
  <Commands.Script>
    <ScriptCommand Verb="smell">
      <Print Text="You smell hot peppers eveywhere." />
    </ScriptCommand>
    <ScriptCommand Verb="listen">
      <Print>You hear nothing special.</Print>
    </ScriptCommand>
  </Commands.Script>
</Room>

ScriptCommand and Print are some other classes that are part of the object model for the game.

From XAML to Objects

Here’s some part of a complete XAML we may wish to parse:

<GameFile xmlns="http://xamlventure/2013" >
  <GameFile.Resources>
    <Variable Name="light carried" Value="True" />
    <CanMoveToCondition Direction="North" Name="canMoveNorth" />
  </GameFile.Resources>
    <Item Name="ring" Location="{In box}" 
            Nouns="ring" Adjectives="small,diamond" Article="a">
    <Commands.Script>
      <ScriptCommand Verb="take" DirectObject="ring">
        <Print Text="Your hand is stopped by an invisible shield around the ring." 
            Condition="{Property Glowing, Object=ring, Value=True}" Continue="false"/>
        <Print>The ring shines momentarily as you grab it in your hand.</Print>
        <PausePrint />
      </ScriptCommand>
    </Commands.Script>
    </Item>
  <Item Name="box" Location="kitchen" Nouns="box" IsOpen="true">
    
  </Item>
  <Room Name="kitchen" Attributes="Cold,Dark" ShortDesc="A small kitchen">
    <Commands.Script>
      <ScriptCommand Verb="smell">
        <Print Text="You smell hot peppers eveywhere." />
      </ScriptCommand>
      <ScriptCommand Verb="listen">
        <Print>You hear nothing special.</Print>
      </ScriptCommand>
    </Commands.Script>
  </Room>

The XAML uses other classes not described above, with some other markup extensions, such as {Property} and {Condition}.

Note the XML namespace at the top of the file. This defines the relationship between XAML types and .NET types. The .NET types may be spread across multiple .NET namespaces, but the XML namespace maps to all of those. This is done using the following attributes:

[assembly: XmlnsDefinition("http://xamlventure/2013", "XamlVenture.ObjectModel")]
[assembly: XmlnsDefinition("http://xamlventure/2013", "XamlVenture.ObjectModel.MarkupExtensions")]
[assembly: XmlnsDefinition("http://xamlventure/2013", "XamlVenture.ObjectModel.Actions")]
[assembly: XmlnsDefinition("http://xamlventure/2013", "XamlVenture.ObjectModel.Conditions")]

This is easier than the alternative XAML namespace mapping (this is the way WPF/Silverlight works to get the correct mappings).

The next step is to turn the XAML into the GameFile root object with everything inside. The simplest way to do this is with the XamlServices class:

var root = (GameFile)XamlServices.Load(path);

This returns the root GameFile object and everything else inside it. GameFile is defined like so (partial):

[Serializable]
[ContentProperty("Entities")]
public sealed class GameFile {
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    Dictionary<string, Entity> _entities = new Dictionary<string, Entity>(32, StringComparer.CurrentCultureIgnoreCase);
 
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    Dictionary<string, Verb> _verbs = new Dictionary<string, Verb>(8, StringComparer.CurrentCultureIgnoreCase);
 
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    Dictionary<string, Resource> _resources;
 
    public IDictionary<string, Entity> Entities {
        get { return _entities; }
    }
 
    public IDictionary<string, Verb> Verbs {
        get { return _verbs; }
    }
 
    public IDictionary<string, Resource> Resources {
        get {
             if(_resources == null)
                _resources = new Dictionary<string, Resource>(4, StringComparer.InvariantCultureIgnoreCase);
            return _resources; 
        }
    }
 
    public Game Game { get; set; }
}

The ContentProperty attribute is another common helper that sets the “default” property for the particular type.

If more control is required during parsing, such as running some extra initialization after or during certain object creation, a more elaborate parsing loop can be created:

using(var reader = new XamlXmlReader(path)) {
    using(var writer = new XamlObjectWriter(new XamlSchemaContext())) {
        while(reader.Read()) {
            switch(reader.NodeType) {
                case XamlNodeType.StartObject:
                    writer.WriteNode(reader);
                    break;
 
                case XamlNodeType.StartMember:
                    goto default;
 
                case XamlNodeType.EndObject:
                    writer.WriteNode(reader);
                    AnalyzeObject(writer.Result);
                    break;
 
                default:
                    writer.WriteNode(reader);
                    break;
            }
        }
    }
}

After each XAML token is read, the code can do something with it. The most useful node type is EndObject, indicating a complete object has been written. This is a perfect opportunity to do something with that object, such as create extra objects based on its state, set some other properties or anything else that’s required. (the AnalyzeObject dummy method above indicates such operations).

After the parsing is complete, the resulting object model can be transformed to another form or another object model if needed; or it can just be used as is in the target application.

Conclusion

XAML is an effective DSL; being XAML – and XML – makes it easy to work with – as a developer and as a user, as there are many ways to simplify XML input.

Windows Phone 8 Dev Camp

Published at Apr 22 2013, 03:13 PM by pavely

A few hours ago, Ariel Ben Horesh and myself presented two sessions for Windows Phone 8 development at Microsoft offices in Ra’anana (Israel). Thank you all for attending! It was fun – it was the second time I presented with someone else (Ariel) at the same time… we had no time to rehearse, but it was great!

The code we showed can be found on github at https://github.com/arielbh/RightMyGuide.

The slides links are below.

Enjoy!

BTW, the IMDB service I created to run on Azure will not be up forever… I will probably shut it down (it’s in on private Azure account) in a week or two…

Part 1

Part 2

Task and TaskCompletionSource

Published at Apr 12 2013, 10:38 AM by pavely

The Task and Task<T> classes have been around since in .NET 4, and are fairly well known. In .NET 4, the typical usage of a Task is to run some code on a separate thread (by default using the thread pool), as a better alternative to the raw thread pool. Task has a multitude of constructors, but all of them expect a delegate that is the code to be run when the task is executed. Task provides methods such as Wait, so that code can continue when a Task finishes, and powerful continuation model with ContinueWith, that provides easy way of chaining tasks (can also be configured to run when the task completes successfully, fails or canceled and any combination of these).

But a Task is a logical entity, encapsulating something that may take time – not necessarily CPU time. It can represent an I/O operation, for instance. In this case, how can we create the task to return to some interested party? Providing an empty delegate would simply complete the task immediately; how do we create and connect a task to another operation?

This is where TaskCompletionSource<> comes in. It provides a way to construct a task that does not in itself run any code, but is used as a notification mechanism for completion of some operation. Task actually has a constructor that does not require a delegate – it’s just internal, so unusable by our code. TaskCompletionSource<>, on the other hand, can invoke that constructor.

One useful scenario for TaskCompletionSource<> is turning the Event Asynchronous Pattern (EAP) into the Task Asynchronous Pattern (TAP), usable with the C# 5.0 async/await keywords. Here’s an example for Windows Phone: suppose we want to search for contacts based on some criteria; we can use the Microsoft.Phone.UserData.Contacts class by calling the SearchAsync method. This method starts a search, which is reported back with an event handler for the SearchCompleted event:

private void OnSearch(object sender, RoutedEventArgs e) {
    var contacts = new Contacts();
    contacts.SearchCompleted += (s, args) => {
        _contactList.ItemsSource = args.Results;
    };
    contacts.SearchAsync(_search.Text, FilterKind.DisplayName, null);
}

This looks simple enough. The event handler for some Search button is invoked, which sets up a search using the Contacts class. It works with the EAP – first, we subscribe to the event and then initiate the asynchronous call. Thanks to the lambda expression we stay in the same method (conceptually) and can access the results, passing them to some ListBox for display.

Suppose we wanted to take that functionality to a separate method that may have the following prototype:

IEnumerable<Contact> SearchContacts(string text);

That’s a problem – we can’t really return the result from that method because the search is asynchronous and we do not want to block. The solution is to return a Task, representing the long operation. Naturally, it can also be “awaited” on:

Task<IEnumerable<Contact>> SearchContacts(string text);

But how would that be implemented? How would we turn the EAP into a returning a Task? That’s where TaskCompletionSource<> comes in. Here’s the implementation (method renamed to SearchContactsAsync):

Task<IEnumerable<Contact>> SearchContactsAsync(string text) {
    var tcs = new TaskCompletionSource<IEnumerable<Contact>>();
    var contacts = new Contacts();
    contacts.SearchCompleted += (s, args) => {
        tcs.SetResult(args.Results);
    };
    contacts.SearchAsync(text, FilterKind.DisplayName, null);
    return tcs.Task;
}

We create a TaskCompletionSource of the returned type (IEnumerable<Contact>) and it has a Task property (of type Task<IEnumerable<Contact>> that we return. This task is not yet complete – this is the job of the TaskCompletionSource<>.SetResult method, which we call upon the SearchCompleted event firing.

This is how the Search button handler uses the new method:

private async void OnSearch(object sender, RoutedEventArgs e) {
    _contactList.ItemsSource = await SearchContactsAsync(_search.Text);
}

For extra elegance, we can add that kind of method as an extension method to the Contacts class:

public static class Extensions {
    public static Task<IEnumerable<Contact>> SearchContactsAsync(this Contacts contacts, string text) {
        var tcs = new TaskCompletionSource<IEnumerable<Contact>>();
        contacts.SearchCompleted += (s, args) => {
            tcs.SetResult(args.Results);
        };
        contacts.SearchAsync(text, FilterKind.DisplayName, null);
        return tcs.Task;
    }
}

And use it like so:

private async void OnSearch(object sender, RoutedEventArgs e) {
    var contacts = new Contacts();
    _contactList.ItemsSource = await contacts.SearchContactsAsync(_search.Text);
}

In conclusion, TaskCompletionSource can be used to build and manage a Task that represents an operation without the Task needing to execute any code. Since a task can fail, TaskCompletionSource<> has a SetException method that causes the Task to fault. Similarly, a SetCanceled method causes the Task to be reported as cancelled.

Webcasts on Windows Phone 8 development

Published at Mar 27 2013, 09:51 AM by pavely

Recently, I’ve done two sessions on Windows Phone 8 development, that are available on YouTube. If you’re new to Windows Phone, these sessions may help you to get started. The session are in English and are comprised mostly of coding examples. A third session is planned to happen about 2 weeks from now.

First session:

Second session:

Enjoy!

Windows Phone Tip: Beware of PhoneApplicationService.State

Published at Mar 18 2013, 05:58 AM by pavely

A Windows Phone 8 app may be in one of several states:

In the running state, it’s the foreground app and the user is working with the app. So far good.

If the user taps the Start hardware button, he’s taken to the Home screen (naturally), and our app becomes dormant. In this state, all its memory is intact, but all threads are suspended so that app cannot consume any CPU time. Entering this state causes the PhoneApplicationService.Deactivated event to be fired. The app should save its state because the app may later become tombstoned.

Tombstonening means the app loses all its memory (because memory is tight, some applications were started), but navigation state is still preserved and everything in the PhoneApplicationService.State dictionary. This seemingly simple dictionary can be used to save key/value pairs of some relevant data that may allow the app to restore its state when activated again after tombstonening.

The one thing we need to watch for is that the objects saved in the PhoneApplicationService.State dictionary must be serializable.

“Serializable” in Windows Phone 8 parlance means that the object’s type must be one of two things:

  1. Have the [DataContract] attribute placed on the type and [DataMember] attributes on properties that need saving. This may also require using other attributes, such as [KnownType] to make sure all possible types can be handled by the serializer. Or
  2. Make sure the type has a public default constructor. All public properties will be saved (and must conform to one of these two rules, recursively).

The serializer used is DataContractSerializer. If any of the types is not serializable in the above sense (recursively if using complex objects), going into dormant state causes a SerializationException to occur. This occurs even if there is no handling for the Deactivated event.

The PhoneApplicationService.State property is sometimes used to pass information between unrelated entities, such as ViewModels inside the app. because that dictionary is easily accessible by using PhoneApplicationService.Current.State property; this should be discouraged for such tasks as information passing because that information may not be serializable and in any case probably not what you want to save anyway.

By the way, the well-known System.Serializable attribute from the full .NET framework is unavailable in Windows Phone, and cannot be used.

This State dictionary is not enough for state management. An app in dormancy or tombstonening may be killed by the OS (only 5 tombstoned apps are allowed) because memory may be tight. In this case the State is not saved anywhere. The app must also save state to isolated storage, so the data is available even if the app is killed.

How to save data to isolated storage? One way to go about it is to use the same DataContractSerializer on our own types, but do the saving manually:

public class AppData {
    public int Number { get; set; }
    public string Value { get; set; }
}
var storage = IsolatedStorageFile.GetUserStoreForApplication();
using(var stm = storage.CreateFile("MyData")) {
    var dcs = new DataContractSerializer(typeof(AppData));
    dcs.WriteObject(stm, data);
}

Naturally, we can use other objects for saving, such a StreamWriter; this provides flexibility. Loading the data is similar with code such as the following:

var storage = IsolatedStorageFile.GetUserStoreForApplication();
using(var stm = storage.OpenFile("MyData", FileMode.Open)) {
    var dcs = new DataContractSerializer(typeof(AppData));
    var obj = dcs.ReadObject(stm) as AppData;
    // use obj
}

A simple alternative that is similar to PhoneApplicationService.State is available through IsolatedStorageSettings.ApplicationSettings dictionary. This works very similarly, but stores data in isolated storage which is not erased if the app is killed. The question may be why not always use just isloated storage? Isolated storage is slower, so should be used for the important data that needs to be preserved between application runs.

My New Book Project

Published at Mar 05 2013, 05:57 AM by pavely

Those of you who follow my blog may have noticed a slowdown in posts. The main reason for this is that I am working on a new book, titled “Windows 8 C++ App Development” to published by Packt Publishing in about 2 months time.

image

The book has now an official URL in Pack’s web site (no Amazon link yet, but soon…).

The book is aimed towards C++ developers that want to use the power and flexibility of C++ to write Windows 8 Store Apps, while leveraging XAML as the UI technology. It includes a good coverage of C++/CX and most features of Store apps.

For those interested, these are the chapters:

  1. Introduction to Windows 8 Store Apps
  2. COM and C++ for Windows Store Apps
  3. Building UI with XAML
  4. Layout, elements & controls
  5. Data binding
  6. Components, templates and custom controls
  7. Applications, tiles, tasks and notifications
  8. Contracts and extensions
  9. Packaging and the Windows Store

I’m now in the rewrite/fixes stage. Once that’s done, I’ll be returning to “normal” post pace.

XAML Tip: Graphics with ItemsControl

Published at Feb 23 2013, 12:04 AM by pavely

Sometimes in a WPF or Windows Store or Windows Phone application we need to draw some things based on some collection of data items. Suppose we have the following simple data item:

class CarData {
    public double Distance { get; set; }
    public string Image { get; set; }
}

Suppose we have a collection of CarData objects, and the requirement was to show a set of images along a line with a particular distance, like in the following screenshot:

image

The distance from the left is determined by the Distance property, and the image is determined by the Image property. How would we achieve that?

One obvious option is to use a loop that iterates through the CarData collection, and adding (e.g.) Image elements to a Canvas (by calling the Children.Add method), while setting the Canvas.Left attached property to a value based on the Distance property.

Although this technically works, it’s inelegant to say the least. If a new CarData object is added or removed, we’d have to rerun the loop to regenerate the images or manually add/remove the appropriate image. Dealing directly with the UI instead of just with the data object is just looking for trouble.

The obvious solution to the problem is data binding; it’s classic – bind the data objects to some UI using appropriate binding expressions, and just deal with the data objects; forget about the UI; let the data bindings managed everything automatically.

But how can we bind the collection of CarData objects to a Canvas’ Children? We can’t – the Children property is not bindable.

The solution is to use an ItemsControl control (or one of its derivatives) and bind its ItemsSource property to the collection. The problem with ItemsControl (and its derivatives) is that they display items in a vertical StackPanel (or VirtualizingStackPanel, but that’s unimportant for this discussion). How can we change that? Easy – use the ItemsPanel property:

<ListBox ItemsSource="{Binding}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding Image}" Stretch="None" 
                Canvas.Left="{Binding Distance}" Canvas.Top="100" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

We change the ItemsPanel to a Canvas and provide a DataTemplate (in the ItemTemplate property) that consists of an Image moved to the correct distance with the Canvas.Left attached property bound to the CarData.Distance property. Running this produces the following:

image

It’s certainly disappointing; it seems the Canvas.Left property had no effect. Can you spot the problem?

The problem is a subtle one: Every item in a ListBox is hosted in a ListBoxItem control. This means changing the Image’s Canvas.Left property has no effect, because the Image is not in any Canvas; the ListBoxItem is.

Fixing this is just a matter of applying an ItemContainerStyle that has the required properties; the Image element has no use for them:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Canvas.Left" Value="{Binding Distance}" />
        <Setter Property="Canvas.Top" Value="100" />
    </Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
    <DataTemplate>
        <Image Source="{Binding Image}" Stretch="None" />
    </DataTemplate>
</ListBox.ItemTemplate>

The Canvas.Left property is applied on the container item – a ListBoxItem in this case.

This little trick can help to produce interesting results in an ItemsControl-derived control without the expected “list” look.

C# Extension Methods and Fluent Interfaces

Published at Feb 07 2013, 03:42 AM by pavely

The idea of fluent interfaces is not new, and has many forms. The basic idea is to use a single statement to encompass a series of operations that are natural, or at least simple, to use. There are very few fluent interfaces in .NET – the most well known, which has some fluent interface semantics, is the System.Text.StringBuilder class. Here’s a simple example:

public static string BuildInfo(Process process) {
    return new StringBuilder("Process ")
        .AppendLine(process.ProcessName)
        .Append("Started at ").AppendLine(process.StartTime.ToLongTimeString())
        .Append("Running with ").Append(process.Threads.Count).AppendLine(" threads.")
        .ToString();
}

This “chaining” is made possible by the fact that the Append and AppendLine methods of StringBuilder return the same StringBuilder instance (this).

StringBuilder is a simple example, let’s try to create something of our own. Here’s a simple Customer class with a fluent interface:

class Customer {
    List<Item> _items = new List<Item>();
 
    public string Name { get; private set; }
    public string AccountManager { get; set; }
 
    public Customer(string name) {
        Name = name;
    }
 
    public Customer WithAccountManager(string name) {
        AccountManager = name;
        return this;
    }
 
    public Customer AddItems(params Item[] items) {
        _items.AddRange(items);
        return this;
    }
}

Properties are not suited for a fluent interface because property setters cannot return anything, so chaining is impossible. This means we have to turn properties into methods for “fluency”. With the above example, we can write code like the following (Item is a some class with a constructor accepting a string):

 

var customer1 = new Customer("Bart Simpson")
    .WithAccountManager("Bernz")
    .AddItems(new Item("ball"), new Item("cactus"));

This is all good and well. Now let’s add a Customer-derived type like so:

class CorporateCustomer : Customer {
    public bool PremierSupport { get; set; }
 
    public CorporateCustomer(string name)
        : base(name) {
    }
 
    public CorporateCustomer WithPremierSupport(bool isPremier = true) {
        PremierSupport = isPremier;
        return this;
    }
}

Now let’s try to create a CorporateCustomer and initialize with the fluent interface:

var customer2 = new CorporateCustomer("Homer Simpson")
    .WithAccountManager("Bernz")
    .WithPremierSupport();

Unfortunately, the code fails to compile. Can you spot the problem?

The problem is that WithAccountManager returns a Customer and not a CorporateCustomer, so the compiler rejects the call to WithPremierSupport. How can we solve that?

We can try to make the WithAccountManager method generic, like so:

public TCustomer WithAccountManager<TCustomer>(string name) where TCustomer : Customer {
    AccountManager = name;
    return this as TCustomer;
}

In this case, the customer-creating code still does not compile. Can you spot the problem now, dear reader?

The problem is more subtle; in fact, the code that creates a plain Customer fails to compile as well. The problem is that the compiler cannot infer the generic argument automatically, because the input arguments to WithAccountManager have nothing to do with customer, and the return type can be anything that derives from customer – the compiler can’t simply select one – it does not understand the intent of the method – returning this as the “real” type of the object.

How can we solve that? One obvious way is to specify the generic arguments like so:

var customer1 = new Customer("Bart Simpson")
    .WithAccountManager<Customer>("Bernz")
    .AddItems(new Item("ball"), new Item("cactus"));
 
var customer2 = new CorporateCustomer("Homer Simpson")
    .WithAccountManager<CorporateCustomer>("Bernz")
    .WithPremierSupport();

This works, but using it is very tedious. We just want to get rid of the explicit generic argument and still return the correct type. The solution? Extension methods:

static class CustomerExtensions {
    public static TCustomer WithAccountManager<TCustomer>(this TCustomer customer, string name) 
        where TCustomer : Customer {
        customer.AccountManager = name;
        return customer;
    }
}

With this in place (and the original WithAccountManager method removed), we can simply write:

var customer1 = new Customer("Bart Simpson")
    .WithAccountManager("Bernz")
    .AddItems(new Item("ball"), new Item("cactus"));
 
var customer2 = new CorporateCustomer("Homer Simpson")
    .WithAccountManager("Bernz")
    .WithPremierSupport();

This works because the compiler can deduce the correct type because of the first argument to the extension method; and this will continue to work correctly even if new classes deriving from Customer or CorporateCustomer are created.

Don’t you just love extension methods?

C# 5.0: await and Reentrancy

Published at Jan 28 2013, 04:45 AM by pavely

The relatively new async/await keywords in C# 5.0 are truly great. I’ve been using them for a while now, and I always contrast these to the way things can be done in C++11; and even with the help of PPL tasks – it stands out as clearly victorious, with its ease of use and lack of verbosity.

In fact, it’s so easy to use that I find myself creating new methods that are mostly “Async”, even if the benefit may not be that great – just because it’s easy to do.

For example, suppose there is a method that does some work named Save:

public void Save(Data data, string path) {
    var formatter = new BinaryFormatter();
    using(var fs = new FileStream(path, FileMode.OpenOrCreate))
        formatter.Serialize(fs, this);
}

This is a clearly a synchronous method that serializes some data object to a file. Even if I expect the data to be fairly small, I may want to create an asynchronous version instead:

public async Task SaveAsync(Data data, string path) {
    await Task.Run(() => {
        var formatter = new BinaryFormatter();
        using(var fs = new FileStream(path, FileMode.OpenOrCreate))
            formatter.Serialize(fs, this);
    });
}

To make the change to an asynchronous method, we need a couple of things:

  • 1. The method should return Task or Task<T> (depends on whether the method has some result or not).
  • 2. Mark the method as async. That’s not strictly required in our case – we can simply return the Task from Task.Run. Adding async requires the use of await somewhere within the code – in this case since this is just one operation, we await the Task completion. None we don’t return anything. The compiler does the right thing and completes the Task that’s returned.

The client now simply awaits the end of the operation:

public async void SaveData(string path) {
    await SaveAsync(_data, path);
}
  • The point of await is letting the thread return until the awaited Task is complete. What happens to that thread? If it’s in some server application, the operation was probably initiated by some thread from the Thread Pool, so that thread can return to the pool and serve some other client, thus not wasting threads. In a UI client scenario, the thread returns to its all-important message pumping activity.
  • Suppose the SaveData method was initiated by a button click. In this case while the thread returns the user can click the button again, causing reentrancy to the SaveData method and the initiation of the save operation again. This can cause problems – in the above code the file may be already exclusively open, so a second attempt will throw an exception.
  • This means we need to think about all possible scenarios while operations are awaited. At a minimum, we would disable the button that initiated the operation until it’s done:
  • public async void SaveData(string path) {
        _button.IsEnabled = false;
        await SaveAsync(_data, path);
        _button.IsEnabled = true;
    }

This is certainly better, but we may need to concern ourselves with other operations. Suppose some other button on the UI changes the data object that is being persisted. What then? We may want to disable that button as well, and maybe other controls for the same reason. In XAML based technologies (WPF/Silverlight/Windows 8 Store) we can leverage data bindings to make this simpler and manageable. For example, suppose there is some ViewModel that manages the current view. We can set some property that indicates “busyness”:

public async void SaveData(string path) {
    _vm.IsBusy = true;
    await SaveAsync(_data, path);
    _vm.IsBusy = false;
}

And a typical control can be bound to the property like so:

IsEnabled="{Binding IsBusy, Converter={StaticResource notConverter}}"

This assumes the converter negates the property’s value (we can setup a IsNotBusy property to remove the need for a converter).

[Of course, we can use a Command for the button, and make it available only when non-busy]

Sometimes, we may want to invoke an asynchronous method synchronously. Since we get back a Task, we can simply call Wait on that:

SaveAsync(_data, path).Wait();

This blocks the thread, making the call effectively synchronous. If the operation returns a result, the code would change to:

var result = SaveAsync(_data, path).Result;
Reading the Task<T>.Result property cause a call to Wait() before the result can be retrieved.

 

Conclusion

async/await is a great tool for not letting threads sleep unnecessarily; we just need to remember that although the code may look synchronous, it’s actually not. This can cause reentrancy (and other similar) issues that we must deal with.

Making HTTP calls in WinRT with C++

Published at Jan 14 2013, 04:36 AM by pavely

When working with Windows Store applications (“metro”), it’s sometimes necessary to make HTTP calls. one classic example is to register for push notifications. After obtaining a unique channel URI, the app needs to send that URI to its application server, as that particular URI is the one to use by the application server to execute a push notification against the Windows Notification Service (WNS).

Getting the channel URI is fairly simple, with a call to the static PushNotificationChannelManager::CreatePushNotificationChannelForApplicationAsync method. Now comes the tricky part: how to send the resulting URI to the application server?

In .NET, things are relatively easy. Just use the HttpClient class (introduced in .NET 4.5) for sending HTTP requests. It provides an easy to use asynchronous model that can be leveraged in C# using the await keyword, but it’s part of .NET, not WinRT. What about C++ or C++/CX?

Let’s take a concrete example: suppose we have a WCF service that is hosted in our application server, that exposes a method to register for push notifications:

[DataContract(Namespace="")]
public class ClientInfo {
    [DataMember]
    public string Uri { get; set; }
    [DataMember]
    public string ClientID { get; set; }
}
 
[ServiceContract]
public interface IMovieService {
    [OperationContract, WebInvoke(UriTemplate="register")]
    void RegisterForPushNotification(ClientInfo info);
}

To make things easier, we’ll expose the service in a RESTful way. This will make creating the actual HTTP messages a lot easier. Actually, with .NET it’s not such a big deal to work with SOAP based services. Just use the “Add Service Reference…” option in Visual Studio, and an appropriate client proxy is generated for you. Unfortunately, this is unavailable for C++, so the first step is to make the required messages simpler by using REST.

Just for the sake of completeness, WCF REST support requires using the WebHttpBinding and the WebHttp behavior. The simplest way to get these is by using the WebServiceHost class. For WCF services that are hosted in IIS, the factory should be replaced with WebServiceHostFactory to get IIS to use the correct host:

<%@ ServiceHost Language="C#" Debug="true" Service="MoviesWorld.MovieService" 
CodeBehind="MovieService.svc.cs" 
Factory= "System.ServiceModel.Activation.WebServiceHostFactory" %>

Now that the server is set up, how would we call it from a C++ Windows Store application?

The Windows Runtime, unfortunately, does not provide a class that is capable of sending HTTP requests (similar to .NET HttpCient) The official recommendation is to use the classic XMLHttpRequest COM object (exposed through appropriate COM interfaces), but this is not easy to do, especially in an asynchronous way – a COM object must be written to implement a callback interface, and other such unpleasant details.

Fortunately, one of the Windows 8 samples provided by Microsoft has a nice helper class named HttpRequest (a regular C++ class, not a WinRT class) that wraps all that unpleasantness for us. We can use this class to send GET and POST HTTP requests. For example, to register the client app for push notifications, we can use the following code:

create_task(PushNotificationChannelManager::CreatePushNotificationChannelForApplicationAsync()).then(
    [this](PushNotificationChannel^ channel) {
    HttpRequest request;
    wstring body = wstring(L"<ClientInfo><ClientID>123</ClientID><Uri>") + channel->Uri->Data() + L"</Uri></ClientInfo>";
 
    return request.PostAsync(ref new Uri("http://MyServerURL/MovieService.svc/register"), L"text/xml", body);
}).then([](wstring response) {
});

First, we get a unique channel URI from the Windows Notification Service (WNS), and that channel URI (along with come client ID) should be sent to the application server. concurrency::create_task is used to create a task representing the asynchronous call, with the then clause handling completion (that’s the best we currently can do with C++/CX; compare this to using the C# await keyword - C++ still has a way to go). Then we build a plain XML string with the channel URI (and some dummy client ID) and call HttpRequest::PostAsync to make the HTTP request (I actually modified HttpRequest slightly to allow PostAsync to accept a content type (text/xml in this case), as well as the message body).

That’s it. Not as easy as C#, but not too difficult either.

Hopefully, future versions of WinRT will provide classes within WinRT that are easy to use for HTTP calls, as these are fairy common these days.

Windows Runtime with C++/C#: Anatomy of a WinRT Class

Published at Dec 30 2012, 09:47 AM by pavely

The Windows Runtime (WinRT) is based on COM (I referred to it in the past as a “better COM”), which means every method and property must be part of an interface. Also, COM does not support static members (only instance members) and does not easily support parameterized constructors. Inheritance is again an issue in classic COM – the closest thing is COM aggregation, and that’s not really inheritance in the usual sense of the word.

Using C++/CX or a .NET language allows creating WinRT types that support methods, properties, constructors and static members, and even events (another feature that is not directly supported by COM). We can even have inheritance, although currently it’s limited to the Windows::UI::Xaml::DependencyObject class (or any of its derivatives).

How does all this works in WinRT?

Let’s create a WinRT class, first in C++/CX and then in C# and take a look at the metadata for hints on the actual implementation. Here’s a Book class written in C++/CX that uses some WinRT features (to create this yourself, create a Windows Runtime Component project in Visual Studio 2012 under the C++/Windows Store node):

public ref class Book sealed {
public:
    Book(Platform::String^ name, int pageCount);
    Book(Platform::String^ name);
    virtual ~Book();
 
    property Platform::String^ Name;
    property Platform::String^ Author;
    property int PageCount;
 
    Platform::String^ ReadPage(int number);
 
    static property int BookCount {
        int get() { return _bookCount; }
    }
 
 
private:
    static int _bookCount;
};

There are two constructors, a method, three properties, a static read only property and a destructor. How does that translate to WinRT?

Let’s open the resulting WINMD file in ILDASM:

SNAGHTML53239df

We may expect to find just a Book class, but we find much more. Opening the Book class reveals the following:

SNAGHTML5342102

The metadata seams mostly what we expect: the ReadPage method, the two constructors and the properties, with their get/set methods. The odd thing is the Close method that’s in there – our original Book class has no such method. This method is part of the WIndows::Foundation::IClosable interface that’s implemented by our Book class. Where did that come from? You guessed it – that’s the result of the destructor.

The other interface implemented by Book is __IBookPublicNonVirtuals – this is “the” interface from which the instance methods and properties originate:

SNAGHTML56b91c0

What about the constructors? These are part of the __IBookFactory interface:

SNAGHTML56c6f71

There are two CreateInstance methods here, one for each defined constructor. Notice that Book does not implement that interface. Instead, it’s implemented by the activation factory (class factory) of the Book. We can get a hint of this by looking at the attributes defined by Book, specifically, the Windows::Foundation::Metadata::Activatable attribute:

.custom instance void [Windows]Windows.Foundation.Metadata.ActivatableAttribute::.ctor(class [mscorlib]System.Type,
                                 uint32) = ( 01 00 19 42 6F 6F 6B 4C 69 62 43 50 50 2E 5F 5F   // ...BookLibCPP.__
                                 49 42 6F 6F 6B 46 61 63 74 6F 72 79 01 00 00 00  // IBookFactory....
                                 00 00 )

Where is the activation factory? It’s implemented by the C++/CX compiler – this is one of the things that makes C++/CX easier to use than straight COM.

The last piece of the puzzle is the static members. These are defined by the __IBookStatics interface:

SNAGHTML57def1b

We can see the BookCount read only property (the only defined static member in the Book class).

Again, Book does not implement that interface; instead, it’s implemented by the activation factory (yes, again). This is how Microsoft solved the problem of static members; the activation factory is a natural singleton, which is perfect for storing static members.

WinRT Component in C#

Let’s try the same experiment with C#. We’ll create a Windows Runtime Component project with C# and create a similar Book class like so:

public Book(string name, int pageCount) {
    Name = name;
    PageCount = pageCount;
    BookCount++;
}
 
public Book(string name)
    : this(name, 0) {
}
 
~Book() {
    BookCount--;
}
 
public string Name { get; set; }
public string Author { get; set; }
public int PageCount { get; set; }
public static int BookCount { get; private set; }
 
public string ReadPage(int page) {
    return "sample page";
}
 
public void Dispose() {
    GC.SuppressFinalize(this);
    BookCount--;
}
    }

The implementation itself is unimportant; what is important is the resulting metadata, which makes visible the consumable parts of the Book class from any WinRT projection. Here’s the WINMD file open in ILDASM:

SNAGHTML582f3fb

Note the similarities to the C++/CX metadata. Here’s the equivalence (C# on the left)

Book              -----> Book

IBookClass    -----> __IBookPublicNonVirtuals

IBookFactory -----> __IBookFactory

IBookStatic   ------> __IBookStatic

The only new class is <CLR>Book, which is the actual .NET type that wraps the WinRT type.

The interface names of course are unimportant, as their identified via their interface IDs (which are GUIDs).

One thing to note that the IDisposable .NET interface is mapped to the IClosable WinRT interface.

Conclusion

So there you have it; WinRT under the covers. I haven’t shown events nor inheritance, but I’ll leave that as an exercise to the interested reader.

With the language projections, WinRT is a better COM.

Preview of Blend 5 available

Published at Dec 25 2012, 03:41 AM by pavely

When Visual Studio 2012 came out, one thing was sorely missing. An Expression Blend tool that can handle WPF 4.5 applications. Blend for Visual Studio that is currently available only supports Windows 8 Store Apps, but not WPF (or Silverlight).

A few days ago, Microsoft released a preview of Blend 5 (with Sketchflow), that’s able to work with WPF and Silverlight, along with Windows 8 Store apps.

The tool can be downloaded from here: http://www.microsoft.com/en-us/download/details.aspx?id=30702

Microsoft stated that the final version of the tool will be available with Update 2 of Visual Studio 2012 (Update 1 was released about 2 weeks ago).

Windows Runtime: Where did TemplatePart go?

Published at Dec 13 2012, 03:39 AM by pavely

In WPF and Silverlight, controls define their named parts (those that have them) using the TemplatePart attribute. For example, here’s the class definition for the WPF ProgressBar control:

 

[TemplatePart(Name = "PART_Track", Type = typeof (FrameworkElement))]
[TemplatePart(Name = "PART_GlowRect", Type = typeof (FrameworkElement))]
[TemplatePart(Name = "PART_Indicator", Type = typeof (FrameworkElement))]
public class ProgressBar : RangeBase
{

This indicates to those wanting to replace the control template which named parts are understood (and searched for) by the control. XAML based tools can also use this information to provide better user experience for authoring templates.

In WinRT, the TemplatePart attribute is defined, but looking at control metadata – it seems it’s not used anywhere. For example, here’s the Reflector output for the Windows.UI.Xaml.Controls.ProgressBar class:

[MarshalingBehavior(MarshalingType.Agile), Composable(typeof(IProgressBarFactory), CompositionType.Public, 0x6020000), Version(0x6020000), Threading(ThreadingModel.Both), Static(typeof(IProgressBarStatics), 0x6020000), WebHostHidden]
public class ProgressBar : RangeBase, IProgressBar
{

There’s no mention of any TemplatePart attributes.

The best way I found of getting this information directly is by looking at the default control template. One way to do this is to right-click a ProgressBar control on some page, and select Edit Template –> Edit a Copy in either Visual Studio 2012 or the new Blend for Visual Studio product. Alternatively, we can look at the generic.xaml file located in C:\Program Files (x86)\Windows Kits\8.0\Include\WinRT\Xaml\Design (assuming a 64 bit Windows installation). This file has all the default styles of controls (which include the Template property with the control’s default template). Looking a ProgressBar we find the following:

<Style TargetType="ProgressBar">
    <Setter Property="Foreground" Value="{StaticResource ProgressBarForegroundThemeBrush}" />
    <Setter Property="Background" Value="{StaticResource ProgressBarBackgroundThemeBrush}" />
    <Setter Property="BorderBrush" Value="{StaticResource ProgressBarBorderThemeBrush}" />
    <Setter Property="BorderThickness" Value="{StaticResource ProgressBarBorderThemeThickness}" />
    <Setter Property="Maximum" Value="100" />
    <Setter Property="MinHeight" Value="{StaticResource ProgressBarThemeMinHeight}" />
    <Setter Property="IsTabStop" Value="False" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ProgressBar">
                <Grid>
                    <VisualStateManager.VisualStateGroups>
                    ...
                    </VisualStateManager.VisualStateGroups>
                    <Grid x:Name="EllipseGrid"
                    ...
                    </Grid>
                    <Border x:Name="DeterminateRoot"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Rectangle x:Name="ProgressBarIndicator"
                                   Margin="{TemplateBinding Padding}"
                                   Fill="{TemplateBinding Foreground}"
                                   HorizontalAlignment="Left" />
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Most of the template is omitted for brevity – all visual states defined using the VisualStateManager and other markup. The last part is important; it includes a Rectangle named ProgressBarIndicator, which is the most important part.

For a ProgressBar, “ProgressBarIndicator” may seem pretty obvious; for other controls, this may not be that obvious.

I’m not sure why TemplatePart attributes were not applied to the existing controls, but I wish they would; maybe I’m missing something. That would give a hint to the important parts of a control template. For now, I’ll be looking at that generic.xaml for the default control templates, trying to figure out the named parts.

ALM & TFS 2012 Open Day at Microsoft

Published at Nov 25 2012, 03:18 AM by pavely

CodeValue (that’s us) is hosting an open day on Team Foundation Server 2012 with its Visual Studio 2012 integration and other little goodies, on Monday next week (December 3rd) at Microsoft offices in Ra’anana. Here’s the official banner (in Hebrew):

image

To register, just send an email to as it appears in the banner, stating your name, and you’re registered!

See you there!

More Posts Next page »