| Comments

I should have known better honestly.  I’ve had one strike with cloud billing catching me by surprise and I’m not sure why I’m shocked it happened again.  This time, however, I thought I really did plan it out, pay attention to things and asked what I thought were the right questions.  Unfortunately I didn’t get the full answers.  This time I was stung by my shiny new SQL Azure service choice.

UPDATE 12-APR-2012: Based on comments I've received I feel the need to clarify that I'm not bashing Azure or cloud services in general here.  I don't think anywhere I indicated Azure was a crap product or that I hated it at all.  In fact, I indicated I was completely happy with the service offering.  My frustration was *only* with the fact that the pricing was unclear to me based on how I researched it...that is all and nothing more.  As many have pointed out, cloud services like Azure are extremely important in the marketplace and the ability to scale real-time with minimal effort is an exceptional feature.  *FOR ME* I currently don't have those needs so I couldn't justify the charges beyond what I had planned...that is all, nothing more.  My experience with SQL Azure was a positive one as a product.  Quick setup, familiar tools to manage, worry-free database management, great admin interface and a reliable data storage solution.  My architecture, however, just didn't prove ideal currently with my site not being in Azure as well.  When VM roles come out of beta I will be sure to evaluate moving sites there and plan better.

A while back I heard about the change in price for some Windows Azure services and the one that piqued my interest was the SQL Azure.  At the time it hit me right as I needed to move around some of my hosting aspects of my site.  The lure of the $5/month SQL Azure database (as long as it was < 100MB) was appealing to me.  The SQL server aspect of my site has always been a management headache for me as I don’t want to have to worry about growing logs, etc.

Stung by marketing

I followed the announcements to the http://www.windowsazure.com site and read the descriptions of the services.  I was immediately convinced of the value and heck, it was a service from my company so why shouldn’t I give it a try and support it?  When I began to set it up, however, there were questions being asked during setup and I started to get concerned.  I asked around about if this $5 fee was really the only fee.  I didn’t want to get surprises by things like compute time.  Perhaps I wasn’t asking specific enough questions, but all answers I got was that signs pointed to yes, that would be my only fee.

NOTE: As of this writing yes I am a Microsoft employee, but this is my own opinion and I realize that peoples’ expectations and results vary.  This is only my experience.  I’m not only an employee but also a customer of Microsoft services and in this instance a full paying customer.  No internal benefits are used in my personal Azure hosting accounts.

Yesterday I learned that wasn’t the case.  I received my first Azure billing statement and it was way more than I expected.  Yes my $5 database was there as expected, but also was suddenly “Data Transfer” charges of $55.

Trying to make sense of billing

I immediately tried to make sense of this billing.  I immediately remembered that I had created a storage account as well for a quick test and perhaps I forgot to disable/delete that service.  I logged into the management portal and saw that my storage account was properly deleted and nowhere to be seen.  But how to make sense of these charges from the past week then?  Luckily Azure provides detail usage download data so I grabbed that.  The CSV file I download did indeed provide some detail…perhaps too much as some of it I couldn’t discern, namely the one piece that I had hoped would help me: Resource ID.  This ID was a GUID that I thought pointed to a service that I used.  It did not, or at least that GUID was nowhere to be seen on my Azure management portal.

I contacted the billing support immediately to help.  I was able to talk with a human fairly quickly which was a plus.  The gentleman explained to me that I had a lot of outgoing data leaving the Azure data centers and that was the source of the costs.  He asked if I knew if anything was connecting to my SQL Azure instance externally.  Well, duh, yes it was my site!  He went on to explain that this constitutes “Data Transfer” and I’m billed at a per GB rate for any data that leaves the Azure data center. 

I took a deep breath and asked where this was documented in my SQL Azure sign-up process.  We walked through the site together and he agreed that it wasn’t clear.  After being put on hold for a while, I was assured I would receive a credit for the misunderstanding.  Unfortunately for Azure, the damage was done and they lost a customer.

Where the failure occurred

For me the failure was twofold: me for not fully understanding terms and Azure for not fully explaining them in context.  I say “in context” because that was the key piece that was missing in my registration of my account.  Let me explain the flow I took (as I sent this same piece of internal feedback today as well) as a customer once I heard the announcement about the SQL Azure pricing changes:

  • I received notice of updated SQL Azure pricing
  • I visited the site http://www.windowsazure.com for more information
  • I clicked the top-level “PRICING” link provided as that was my fear
  • I was presented with a fancy graphical calculator.  I moved the slider up to 100MB and confirmed the pricing on the side (no asterisks or anything)
  • I notice a “Learn more about pricing, billing and metering” link underneath the calculator and click it to learn more
  • I’m presented with a section of 10 different options all presented at the same level giving the appearance as unique services.
  • I choose the Database one and again read through and confirm the charge for the 100MB database option.
  • I click the “More about databases” link to double-verify and am presented with another detailed description of the billing

Not once during that process was context provided.  Not at any of the steps above (3 different pricing screens) was there context that additional fees could also apply to any given service.  Data transfer, in fact, doesn’t even describe itself very well.  As I was assured in asking folks involved in Azure about my concern on pricing, this “Data Transfer” wasn’t brought up at all.  I’m not sure why at all it is listed along side services and almost presented as a separate service as it appears all Azure services are subject to data transfer fees.  This is not made clear during sign up nor marketing of the pricing for each service.  SQL Azure should clearly state that the fees are database *plus* any additional fees resulting from data transfer.  Heck Amazon does this with S3 which also makes it so confusing to anticipate the cost of billing there as well…but at least it is presented that I need to factor that into my calculation.

I’m to blame, so why am I whining

I said I’m to blame as well for not understanding better what I’m getting into.  It is unfortunate because I really did like the service and felt an assurance of more reliability with my database then I had before.  The management portal was great and the uptime and log management was something I didn’t have to think about anymore. 

So why, you might ask, am I complaining about a service fee for something that was providing me value? 

NOTE: You may ask why I didn’t just move my site within Azure as well so that no data would be leaving the data centers.  This is a fair question, but unfortunately my site won’t run on any Azure hosting services and additionally I manage a few sites on a single server so it is cost prohibitive to have multiple Azure hosting instances for me right now.

Well it is simple.  I’m not made of money.  This blog has no accounting department or annual budget and such, I have to be smart about even the smallest cost.  I already have sunk costs into the server that hosts this site as well as a few others.  A $5/month database fee was nothing and justifiable easily with the value I was getting and the minor additional cost.  $50 (and growing) just wasn’t justifiable to me.  It was already at the same cost as my dedicated server and just no longer made sense for my scenario here.  In this instance I’m the “little guy” and need to think like one.  Perhaps cloud services are not for me.

Summary

So what did I learn?  Well, I really need to understand bandwidth and transfer data better for the sites I have.  Unfortunately this isn’t totally predictable for me and as such if I can’t predict the cost then it isn’t something that I should be using.  If you are considering these types of services regardless of if they are from Azure or Amazon (or whomever) you need to really plan out not only the service but how it will be used.  Don’t be lured by those shiny cost calculators that let you use sliders and show you awesome pricing but don’t help you estimate (or alert you) to that some of those sliders should be linked together.

I think Azure (and other similar services) have real customer value…there is no doubt in that.  For me, however, it just isn’t the time right now.  The services, based on my configuration needs, just don’t make sense.  Had I had a clearer picture of this when signing up, I wouldn’t have been in this situation of frustration.  Choose your services wisely and understand your total usage of them.  For me it currently doesn’t make sense and I’m moving back to a SQL Express account on my server.  Yes I’ll have to manage it a bit more, but my costs will be known and predictable.

Hope this helps.

| Comments

My blog runs on Subtext which has a pretty good skinning model (albeit a tad outdated) and allows you to customize whatever you want.  I’ve had my own custom theme since 2009.  I figured I was due for an update.  I was further strengthened by a post from Jon Galloway last week.

Now when I saw this I figured it was another nudge.  I did also have some time this weekend without any distractions so I took it as an opportunity to do some ‘work’ on this here blog.  Now a while back I was inspired by what Scott Hanselman had done on his site with a designer.  I reached out to a few designers that I admired, but frankly never heard back :-(.  I figured that was okay as I wasn’t in a position to really pay what I know it is worth for a good designer.  So I went looking for things on the web that I could do myself.  I did want some subtle design tweaks to represent some things I’m currently passionate about.

Bootstrap your CSS

After some digging I saw a ton of pointers to Bootstrap.  This is an Open Source Javascript/CSS library that sets your site up for styling success and layout goodness.  The documentation was some of the better docs I’ve seen for a library.  Each aspect of the library/styles where in the docs that I could visually see, interact with and see the code that produced the behavior.  I liked what I saw and went to work.

When I got all the styles configured (using the basic setup from Bootstrap) I went to work on some of my own minor tweaks.  One of the things I really liked is the responsive layout options, not only for the grid but also for different screen sizes.  By adding a simple class I can specify certain aspects that shouldn’t be displayed when viewing the site on a tablet or phone.  There were other cool responsive options for this such as the main menu will switch to a drop-down approach when on a smaller device.  Using Firebug, IE F12 tools and real devices I was able to get the precise tweaks that I wanted.  Here’s what my site looks like on an iPhone as an example:

timheuer.com on an iPhone

Notice the menu at the top is gone but replaced with a little icon (which is a drop-down).  Also notice the sidebar area is no longer visible (it is on the bottom of the site in this device view).  I like this subtle configuration that was really easy to do with just adding a class name to the area I wanted to collapse.

The other thing I wanted was to implement my primary navigation links in a little-more-than-text style.  I used the CSS sprite method by creating a single image that I would then define styles that used clips within that image to pull out the right area.  Here is the image in entirety:

Notice how the normal and hover states are the same image. 

NOTE: I put this on a black background so you can see them but it is actually a transparent background so the theme’s background shows through.

What I do then is just define a style for the <a> tag like:

   1: #follow {
   2:     background-image: url("navbarglyphs.png");
   3:     background-position: -195px 0px;
   4: }
   5:  
   6: #follow:hover {
   7:     background-image: url("navbarglyphs.png");
   8:     background-position: -195px -70px;
   9: }

Now I was having a bit of difficulty with this because I was misunderstanding the background-position value in CSS.  A quick set of second eyes with Shawn Wildermuth (who is doing a bunch of HTML dev posts right now) helped me realize my math was wrong and I needed to use the negative value instead of what I was using.  Once that forehead-slap moment was done, I was set. 

I still have a few tweaks to go (need to re-work the comments sections but didn’t have the time to think about a design more) but I’m happy with the quick re-design.  It is very simple for sure, but I like it.  I tried on a few different screen sizes and I think I have met Jon’s challenge to adapt to the available space for the screen.  If you are working with a new site and aren’t a CSS/JS guru I highly recommend looking at Bootstrap as a solid starting point for your efforts.

| Comments

If you’ve been playing around with the Windows 8 Consumer Preview then hopefully you’ve seen the hundreds of samples provided and downloaded some apps form the store.  In a lot of those applications you’ll notice the common theme of the use of an AppBar…the command bar that shows when you swipe from the top or bottom of the screen.  You can also invoke the AppBar by right-clicking or using the Windows 8 keyboard shortcut of Windows key + ‘z’ to bring it up as well.

Bing Maps AppBar
Picture of the AppBar in the Bing Maps application

Most of the applications use the standard AppBar button concepts that clicking invokes some action for the app.  There may be times, however, where that button serves as a “toggle” to something in your app.  Using the Bing Maps app as an example, the “Show Traffic” command is actually a toggle command that, well, shows traffic.  You want to give your users some visual indication whether that toggle selection is on/off.  This can be accomplished in XAML by using 2 buttons and toggling their visibility, but that may be overkill for what you simple want to do.

The Visual Studio project templates provide a set of styles for the AppBar for you, but more importantly a base style AppBarButtonStyle that serves as the core design.  Altering this just slightly and you can have a ToggleAppBarButtonStyle for your project.  Here’s the style for that base:

   1: <Style x:Key="ToggleAppBarButtonStyle" TargetType="ToggleButton">
   2:     <Setter Property="Foreground" Value="{StaticResource AppBarItemForegroundBrush}"/>
   3:     <Setter Property="VerticalAlignment" Value="Stretch"/>
   4:     <Setter Property="FontFamily" Value="Segoe UI Symbol"/>
   5:     <Setter Property="FontWeight" Value="Normal"/>
   6:     <Setter Property="FontSize" Value="21.333"/>
   7:     <Setter Property="AutomationProperties.ItemType" Value="AppBar ToggleButton"/>
   8:     <Setter Property="Template">
   9:         <Setter.Value>
  10:             <ControlTemplate TargetType="ToggleButton">
  11:                 <Grid Width="100" Background="Transparent">
  12:                     <StackPanel VerticalAlignment="Top" Margin="0,14,0,13">
  13:                         <Grid Width="40" Height="40" Margin="0,0,0,5" HorizontalAlignment="Center">
  14:                             <TextBlock x:Name="BackgroundGlyph" Text="&#xE0A8;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0" Foreground="{StaticResource AppBarItemBackgroundBrush}"/>
  15:                             <TextBlock x:Name="BackgroundCheckedGlyph" Visibility="Collapsed" Text="&#xE0A8;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0" Foreground="{StaticResource AppBarItemForegroundBrush}"/>
  16:                             <TextBlock x:Name="OutlineGlyph" Text="&#xE0A7;" FontFamily="Segoe UI Symbol" FontSize="53.333" Margin="-4,-19,0,0"/>
  17:                             <ContentPresenter x:Name="Content" HorizontalAlignment="Center" Margin="-1,-1,0,0" VerticalAlignment="Center"/>
  18:                         </Grid>
  19:                         <TextBlock
  20:                         x:Name="TextLabel"
  21:                         Text="{TemplateBinding AutomationProperties.Name}"
  22:                         Margin="0,0,2,0"
  23:                         FontSize="12"
  24:                         TextAlignment="Center"
  25:                         Width="88"
  26:                         MaxHeight="32"
  27:                         TextTrimming="WordEllipsis"
  28:                         Style="{StaticResource BasicTextStyle}"/>
  29:                     </StackPanel>
  30:                     <Rectangle
  31:                         x:Name="FocusVisualWhite"
  32:                         IsHitTestVisible="False"
  33:                         Stroke="{StaticResource FocusVisualWhiteStrokeBrush}"
  34:                         StrokeEndLineCap="Square"
  35:                         StrokeDashArray="1,1"
  36:                         Opacity="0"
  37:                         StrokeDashOffset="1.5"/>
  38:                     <Rectangle
  39:                         x:Name="FocusVisualBlack"
  40:                         IsHitTestVisible="False"
  41:                         Stroke="{StaticResource FocusVisualBlackStrokeBrush}"
  42:                         StrokeEndLineCap="Square"
  43:                         StrokeDashArray="1,1"
  44:                         Opacity="0"
  45:                         StrokeDashOffset="0.5"/>
  46:  
  47:                     <VisualStateManager.VisualStateGroups>
  48:                         <VisualStateGroup x:Name="CommonStates">
  49:                             <VisualState x:Name="Normal"/>
  50:                             <VisualState x:Name="PointerOver">
  51:                                 <Storyboard>
  52:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
  53:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemHoverBackgroundBrush}"/>
  54:                                     </ObjectAnimationUsingKeyFrames>
  55:                                 </Storyboard>
  56:                             </VisualState>
  57:                             <VisualState x:Name="Pressed">
  58:                                 <Storyboard>
  59:                                     <DoubleAnimation
  60:                                     Storyboard.TargetName="OutlineGlyph"
  61:                                     Storyboard.TargetProperty="Opacity"
  62:                                     To="0"
  63:                                     Duration="0"/>
  64:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
  65:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundBrush}"/>
  66:                                     </ObjectAnimationUsingKeyFrames>
  67:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground">
  68:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPressedForegroundBrush}"/>
  69:                                     </ObjectAnimationUsingKeyFrames>
  70:                                 </Storyboard>
  71:                             </VisualState>
  72:                             <VisualState x:Name="Disabled">
  73:                                 <Storyboard>
  74:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="OutlineGlyph" Storyboard.TargetProperty="Foreground">
  75:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundBrush}"/>
  76:                                     </ObjectAnimationUsingKeyFrames>
  77:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground">
  78:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundBrush}"/>
  79:                                     </ObjectAnimationUsingKeyFrames>
  80:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TextLabel" Storyboard.TargetProperty="Foreground">
  81:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemDisabledForegroundBrush}"/>
  82:                                     </ObjectAnimationUsingKeyFrames>
  83:                                 </Storyboard>
  84:                             </VisualState>
  85:                         </VisualStateGroup>
  86:                         <VisualStateGroup x:Name="FocusStates">
  87:                             <VisualState x:Name="Focused">
  88:                                 <Storyboard>
  89:                                     <DoubleAnimation
  90:                                         Storyboard.TargetName="FocusVisualWhite"
  91:                                         Storyboard.TargetProperty="Opacity"
  92:                                         To="1"
  93:                                         Duration="0"/>
  94:                                     <DoubleAnimation
  95:                                         Storyboard.TargetName="FocusVisualBlack"
  96:                                         Storyboard.TargetProperty="Opacity"
  97:                                         To="1"
  98:                                         Duration="0"/>
  99:                                 </Storyboard>
 100:                             </VisualState>
 101:                             <VisualState x:Name="Unfocused" />
 102:                             <VisualState x:Name="PointerFocused" />
 103:                         </VisualStateGroup>
 104:                         <VisualStateGroup x:Name="CheckStates">
 105:                             <VisualState x:Name="Checked">
 106:                                 <Storyboard>
 107:                                     <DoubleAnimation
 108:                                     Storyboard.TargetName="OutlineGlyph"
 109:                                     Storyboard.TargetProperty="Opacity"
 110:                                     To="0"
 111:                                     Duration="0"/>
 112:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGlyph" Storyboard.TargetProperty="Foreground">
 113:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemForegroundBrush}"/>
 114:                                     </ObjectAnimationUsingKeyFrames>
 115:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BackgroundCheckedGlyph" Storyboard.TargetProperty="Visibility">
 116:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/>
 117:                                     </ObjectAnimationUsingKeyFrames>
 118:                                     <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground">
 119:                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource AppBarItemPressedForegroundBrush}"/>
 120:                                     </ObjectAnimationUsingKeyFrames>
 121:                                 </Storyboard>
 122:                             </VisualState>
 123:                             <VisualState x:Name="Unchecked"/>
 124:                             <VisualState x:Name="Indeterminate"/>
 125:                         </VisualStateGroup>
 126:                     </VisualStateManager.VisualStateGroups>
 127:                 </Grid>
 128:             </ControlTemplate>
 129:         </Setter.Value>
 130:     </Setter>
 131: </Style>

Now with that style we can have a simple style that shows a toggle on and off for the same button:

   1: ...
   2: <Page.BottomAppBar>
   3:     <AppBar>
   4:         <ToggleButton Style="{StaticResource ToggleAppBarButtonStyle}" 
   5:                 AutomationProperties.Name="Search" 
   6:                 Content="&#xE11A;" />
   7:     </AppBar>
   8: </Page.BottomAppBar>
   9: ...

The result would show:

 
ToggleButtonAppBarStyle in off/on state

This way we exhibit all the same behaviors of the AppBarButtonStyle, but just applied to the ToggleButton element in XAML.  Now we could probably refactor both to have an even more derivative base style and use more BasedOn styling, but how it is currently structured we couldn’t have a ToggleButton based on a Button style.  But thanks to the style/template engine in XAML we can re-use a lot and serve our needs!

Notice that you can set the Content to be whatever you want.  Since my base style uses the Segoe UI Symbol font, I’m setting the unicode value for a glyph here for Search.  A set of some cool glyphs you can use can be found in my previous post on XAML AppBar button styles.

You can get the ToggleAppBarButtonStyle from here: https://gist.github.com/2131230.

Hope this helps!

| Comments

Microsoft Advertising logoToday, the Microsoft Advertising team announced an update to their AdCenter SDK to include support for monetizing your Metro style apps.

In a blog post announcing the update, Ian notes that if you were using the previous SDK that there have been breaking changes and to use the updated SDK.  This update includes support for XAML applications and adding the ad units couldn’t be easier.  After installing their SDK (which was developed using the same distribution concepts in my post about creating a distributable custom control previous post), you will be able to use Add Reference in Visual Studio, navigate to the Windows/Extensions area and add the SDK.  After that it is as simple as adding the control in your project:

   1: <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
   2:     <Border Background="Red" VerticalAlignment="Bottom">
   3:         <ads:AdControl xmlns:ads="using:Microsoft.Advertising.WinRT.UI" 
   4:                        VerticalAlignment="Bottom" Width="728" Height="90" 
   5:                        AdUnitId="YOUR_AD_UNIT_ID" 
   6:                        ApplicationId="YOUR_APPLICATION_ID" />
   7:     </Border>
   8: </Grid>

Now you do, of course, have to have a pubCenter account and create the ad units beforehand in order for this to work, but that setup time didn’t take long at all.

You may have some time for your own ad units to be provisioned and start serving ads, but the ad team created some test values you can use to see how things all work.  Download the Ads SDK today!

Hope this helps!

| Comments

At //build one of the surprising immediate things I heard about was folks wanting to build custom controls right away.  I knew that would happen, but not so quick on something so new (WinRT).  The XAML platform did not have good support for building custom controls in the Developer Preview but now that the Consumer Preview for Windows 8 and Visual Studio 11 Beta are out, there is much better support.  There are two key things when thinking about custom controls: 1) building it and 2) making it consumable by developers (even if those developers are your own company).  I’ll try to articulate the methods of both here.

Defining custom versus user control

There is usually some debate in the XAML community about the definition of a custom control.  For the purposes of this discussion I define a custom control as a control that provides a generic.xaml, can be styled/templated and is usually encapsulated in its own assembly which can then be distributed.  A custom control can contain user controls, but generally speaking does not.  A typical user control scenario is one that lives within your project and not meant to be consumed by anyone outside your project.

This definition is the same whether we are talking about C++, C# or Visual Basic.  Everything below applies to all languages.

Creating the custom control

The fundamentals of a custom control are that it is a class and it provides it’s own template/style.  This style/template definition usually lives in a file located at themes/generic.xaml.  This is the same pattern that has existed in other XAML implementations like WPF, Silverlight and Windows Phone.  The pattern is no different for Metro style apps in this regard.

The creation of the most basic custom control is very simple.  A Windows SDK sample for XAML User and Custom Controls is available for you to download for the quick review and core concept.  My intent here is to take that a step further for the end-to-end implementation if I were a control vendor.  Let’s first create our control.  For our purposes we will create a control that shows an Image and allows you to specify some Text for the label.  The label, however, will be prepended with some text that comes from string resources.

In Visual Studio we will create a class library project first.

NOTE: You can create a C#/VB Class Library and keep it managed, or convert it to a WinRT component.  You may also create this in C++ using the WinRT Component project type.  Again, these concepts are the same, the syntax will be obviously slightly different for C++ and managed code.

Once you create the class library (I called mine SimpleCustomControl and deleted the initial Class1.cs file that was created), add an item to the project.  You can do this via right-clicking on the project and choosing add item.  You will be presented with a few options, but the important one is Templated Control.

Add Item dialog

Watch was this does to your project as it will do 2 things:

  • Create a new class
  • Add a Themes folder and place a ResourceDictionary called generic.xaml in that folder

The themes/generic.xaml is very important if you use the DefaultStyleKey concept in your class.  This is very much a convention-based approach.  The contents of the class is very simple at this point, with the sole constructor and the DefaultStyleKey wired up:

   1: namespace SimpleCustomControl
   2: {
   3:     public sealed class LabeledImage : Control
   4:     {
   5:         public LabeledImage()
   6:         {
   7:             this.DefaultStyleKey = typeof(LabeledImage);
   8:         }
   9:     }
  10: }

This maps to the generic.xaml definition of our control.  Let’s modify our ControlTemplate in generic.xaml to be a little more than just a border:

   1: <Style TargetType="local:LabeledImage">
   2:     <Setter Property="Template">
   3:         <Setter.Value>
   4:             <ControlTemplate TargetType="local:LabeledImage">
   5:                 <Border Background="LightBlue" BorderBrush="Black" BorderThickness="2" 
   6:                         HorizontalAlignment="Center" Width="140" Height="150">
   7:                     <StackPanel HorizontalAlignment="Center">
   8:                         <Image Stretch="Uniform" Width="100" Height="100" 
   9:                                Source="{TemplateBinding ImagePath}" Margin="5" />
  10:                         <TextBlock TextAlignment="Center" FontFamily="Segoe UI" FontWeight="Light" 
  11:                                    FontSize="26.667" Foreground="Black" x:Name="LabelHeader" />
  12:                         <TextBlock TextAlignment="Center" 
  13:                                    Text="{TemplateBinding Label}" FontFamily="Seqoe UI" FontWeight="Light" 
  14:                                    FontSize="26.667" Foreground="Black" />
  15:                     </StackPanel>
  16:                 </Border>
  17:             </ControlTemplate>
  18:         </Setter.Value>
  19:     </Setter>
  20: </Style>

Now we have a place for an Image, LabelHeader and a Label.  Notice that we have {TemplatBinding} statements there.  This is how the template binds (duh) to values provided to the control.  So our ControlTemplate is expecting these properties to exist on our control.  We will create these as DependencyProperty types so we can use them in Binding, change notification, etc.  In Visual Studio we can make re-use out of the ‘propdp’ code snippet that exists for WPF.  It is slightly different in the last argument, but it will definitely save you a lot of typing.  We’ll create 2 DependencyProperties like this in our LabeledImage.cs file:

   1: public ImageSource ImagePath
   2: {
   3:     get { return (ImageSource)GetValue(ImagePathProperty); }
   4:     set { SetValue(ImagePathProperty, value); }
   5: }
   6:  
   7: public static readonly DependencyProperty ImagePathProperty =
   8:     DependencyProperty.Register("ImagePath", typeof(ImageSource), typeof(LabeledImage), new PropertyMetadata(null));
   9:  
  10: public string Label
  11: {
  12:     get { return (string)GetValue(LabelProperty); }
  13:     set { SetValue(LabelProperty, value); }
  14: }
  15:  
  16: public static readonly DependencyProperty LabelProperty =
  17:     DependencyProperty.Register("Label", typeof(string), typeof(LabeledImage), new PropertyMetadata(null));

We also had that LabelHeader property.  This is going to be a value coming from a string resource that may be localized at some point.  In our library add a folder called “en” and then within that, using the Add Item dialog in VS, add a Resources.resw file.  Within that Resources.resw file add a name/value pair of name=LabelHeader.Text and value=This is an image of a… and you can save/close the file.

Now back to our class file we are going to set the value of our TextBlock by overriding our template rendering, grabbing a reference to that TextBlock and setting the value from our string resource.

   1: protected override void OnApplyTemplate()
   2: {
   3:     base.OnApplyTemplate();
   4:  
   5:     TextBlock tb = GetTemplateChild("LabelHeader") as TextBlock;
   6:     tb.Text = new ResourceLoader("SimpleCustomControl/Resources/LabelHeader").GetString("Text");
   7: }

Now, I’m showing this way, because it is pretty verbose and there is an easier way…but you wouldn’t know it is easier unless you saw the harder way right?

First it is important to understand how these resources are indexed.  You’ll notice that I’m using a ResourceLoader class to map to what looks like {component}/{resw-file-name}/{property} which is effectively right.  When you create a resw file, at compile-time these get built into a PRI file.  This post isn’t about this whole resource loading process, but you should definitely understand this a bit.  Basically for a control creator perspective you need to understand that your string resources (and file-based resources) live in a ResourceMap that is the name of your component.

NOTE: An easy way to look at this resource indexing is to use the makepri.exe tool installed with VS.  From a VS command prompt navigate to your build output and you should see a resources.pri file.  Call makepri.exe dump and you’ll get an XML representation of that file you can look at.  Knowing that structure is very helpful.

I said there was an easier way to get that string though.  First remove the OnApplyTemplate override completely…we don’t need it for this control anymore.  Now in generic.xaml change the x:Name=”LabelHeader” to the following:

   1: <Style TargetType="local:LabeledImage">
   2: ...
   3:     <TextBlock TextAlignment="Center" FontFamily="Segoe UI" FontWeight="Light" 
   4:                FontSize="26.667" Foreground="Black" 
   5:                 x:Uid="/SimpleCustomControl/Resources/LabelHeader" />
   6: ...
   7: </Style>

This will use the XAML parser way of getting the string resource (note the ResourceMap is still in the x:Uid value).  Using the ResourceMap prefix is necessary when using this method as a custom control vendor.

We are done.  Our control is complete.

Consuming the control from an application

We can quickly test our control by adding a new Metro style app to our project.  Once we do this, make that the startup project and add a project reference to our control library.  Then in the default page for our app (BlankPage or MainPage depending on your template choice), add an xmlns to the top and then consume the control:

   1: <Page
   2:     x:Class="Application1.BlankPage"
   3:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   4:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   5:     xmlns:local="using:Application1"
   6:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   7:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   8:     xmlns:controls="using:SimpleCustomControl"
   9:     mc:Ignorable="d">
  10:  
  11:     <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
  12:         <controls:LabeledImage ImagePath="Assets/110Orange.png" Label="Orange" />
  13:     </Grid>
  14: </Page>

See how the ImagePath and Label are used here?  In more advanced scenarios we can bind values from our view model or other ways.  When rendered the control will show like this:

Custom control rendered

This is great…but also what we call a “project-to-project” (P2P) reference.  As a control vendor we want to distribute our control, not our source primarily.  So we need to package this up.  There are two ways you can do this.

Package your control as an Extension SDK

One of the new methods for distributing Metro style controls in VS11 is via Extension SDKs, also sometimes referred to as non-Framework SDKs.  Extension SDKs are machine-wide and available to all projects once installed.  They can be distributed via the Visual Studio gallery and using the VSIX mechanism…which allows for update notification in Visual Studio.  There are a few intricacies that you can configure your Extension SDK but for most it will get down to three things:

  • Describing your SDK and what it supports
  • Including the binary that projects need to reference
  • Including any assets/files that the control relies on to render

In examining our sample above we have a few things that map to this:

  • Describing – our sample is a C# custom control so it will only work with managed Metro style apps, we will need to describe this in our SDK
  • Binary – we have one binary: SimpleCustomControl.dll
  • Redistributables – we have a generic.xaml and a PRI file with our string resources

The last part (redist) probably is making some existing XAML control developers scratch their heads.  Why isn’t the generic.xaml embedded is what you are likely asking yourself.  In Metro style apps, XAML assets are not embedded but rather exist as “loose file” assets for your control.  This is why it is critical for getting the distribution model correct so that the runtime knows where to get the definitions for everything.

NOTE: This is a default method.  You can, of course, use other techniques to get your assets into your binary either via string constants, other embedding techniques, etc.  In doing so, however, you will now be managing all those extractions yourself rather than being able to rely on the resource APIs for Metro style apps.

The first thing we want to do is understand the structure of an SDK.  These live in %ProgramFiles%\Microsoft SDKs\Windows\v8.0\Extension SDKs directory on disk.  Within there you will have your own folder, version and then the layout of your SDK, as described by your manifest.  Here is what our manifest (SDKManifest.xml) would look like for our control:

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <FileList 
   3:   DisplayName="Simple Custom Control" 
   4:   ProductFamilyName="Simple Controls"
   5:   MinVSVersion="11.0" 
   6:   MinToolsVersion="4.0" 
   7:   CopyRedistToSubDirectory="SimpleCustomControl"
   8:   AppliesTo="WindowsAppContainer+WindowsXAML+Managed"
  10:   MoreInfo="http://timheuer.com/blog/">
  11:   <File Reference="SimpleCustomControl.dll">
  12:     <ContainsControls>True</ContainsControls>
  13:   </File>
  14: </FileList>

We are describing the display information as well as some key data:

  • Display data – the title that will show up in Add Reference
  • CopyRedistToSubdirectory – this would be the name of your component
  • AppliesTo – what I support; in this I’m saying managed, XAML, Metro style apps
  • <File> – these are the files that describe components in my SDK (not their loose assets)

Now to create the structure.  When you build the DLL your output will give you this:

Build output

We need to create the following structure that will live under the Extension SDK folder listed above:

%ProgramFiles%\Microsoft SDKs\Windows\v8.0\Extension SDKs\

--SimpleCustomControl

----1.0

------SDKManifest.xml (the file above)

------References\CommonConfiguration\neutral\SimpleCustomControl.dll

------Redist\CommonConfiguration\neutral\SimpleCustomControl.pri

------Redist\CommonConfiguration\neutral\Themes\generic.xaml

Notice the References and Redist folders.  By placing these in that structure, the project will know what it needs to get type information (References) and then during running/deployment what it needs to package (Redist) and where it puts it (CopyRedistToSubdirectory).  Put this layout in the directory and then when you choose add reference on a project you will see your option:

Add reference dialog

There are other configuration options for the SDKManifest that you can use and the required reading is the Extension SDK section in this MSDN article: How to: Create a Software Development Kit.

The next step for an Extension SDK is to really package it up nicely.  You probably don’t want your users copy directories around all the time…and what about updates as well!  Using the Visual Studio VSIX structure for this really makes it easy to do.

There are tools for Visual Studio to allow you to create a VSIX package.  This requires the Visual Studio extensibility SDK to be installed and using Visual Studio professional or higher.  Once you do that you can create a VSIX package and you will see the VSIX manifest designer.  On the Install Targets tab you will choose Extension SDK:

VSIX Install Targets

We then re-create the layout structure in the VSIX project and add the Assets to the manifest.  The result in the IDE looks something like this:

VSIX Manifest Assets

Now when we build we will get a VSIX installer that we can upload to the Visual Studio Gallery or distribute to our customers.

NOTE: Uploading the to Visual Studio Gallery has benefits in that once installed, any update you put in the gallery will provide notifications to the Visual Studio user than an update exists.  This is done via the unique Product ID value in your manifest, so choose that value accordingly and don’t change it if you want this capability.

When a user gets the VSIX, they double-click it and see the installer:

VSIX Installer

And then they can use it as normally in Add Reference just like described above.  Additional details on other VSIX deployment configurations can be found here: VSIX Deployment.

Once you have your VSIX you can upload to the Visual Studio Gallery and make it discoverable for users from within Visual Studio.  Remember that this method of Extension SDK is machine-wide which is in contrast to the second method described next.

Package your control as a NuGet Package

The other option you have is to package up your control via a NuGet package.  NuGet packages apply to the project and not the machine, but have the flexibility of not having to have anything installed and can travel their dependencies with the project.  NuGet packages are another type of package that has a manifest that describes what the content does. 

For Metro style XAML controls you will have to do a few things differently currently with the NuGet package you create.  NuGet packages are based on nuspec files, which is basically a manifest describing where to get/put things in the package.  You can also use the NuGet Package Explorer for a GUI way of reading/creating new packages.  If you are unfamiliar with the nuspec format, using the package explorer will help you get a package created quickly. 

NuGet is one area where there actually are current differences in C++ or managed code.  Right now NuGet only supports managed code projects and not C++.  I’m sure this may change in the future, but as of right now this applies only to managed code.  For our control above here is what my nuspec file looks like:

   1: <?xml version="1.0"?>
   2: <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
   3:   <metadata>
   4:     <version>1.0.0</version>
   5:     <authors>Tim Heuer</authors>
   6:     <owners />
   7:     <id>SimpleCustomControl</id>
   8:     <title />
   9:     <requireLicenseAcceptance>false</requireLicenseAcceptance>
  10:     <description>A simple custom control for Metro style apps</description>
  11:   </metadata>
  12:   <files>
  13:     <file src="SimpleCustomControl\bin\Debug\Themes\Generic.xaml" target="lib\winrt\SimpleCustomControl\Themes\Generic.xaml" />
  14:     <file src="SimpleCustomControl\bin\Debug\SimpleCustomControl.dll" target="lib\winrt\SimpleCustomControl.dll" />
  15:     <file src="SimpleCustomControl\bin\Debug\SimpleCustomControl.pri" target="lib\winrt\SimpleCustomControl.pri" />
  16:   </files>
  17: </package>

This assumes that the binaries being referenced here are all relative to the nuspec file.  Notice how all the files go into the lib\winrt folder and that we essentially re-create that SDK layout in our package as well.

Now when I build this with nuget.exe I get a package output.  In Visual Studio (with NuGet installed) I can now right-click on a project and choose Manage NuGet Packages and browse the library of packages.  In testing out my package, I create a custom library (you do this via the Settings option when you are in the Manage NuGet Packages dialog) and just point it to the folder where my nupkg file was created:

Manage NuGet Packages dialog

When the package is selected, the reference is added to my project and during build, all the right pieces are put in my APPX package where they need to go.  Once the reference is there I build and run my project and the control renders as expected!

What about the design-time experience?

All of the methods above will allow you to view your control on the XAML design surface in Visual Studio as well.  In the Extension SDK method there is actually additional affordances for you to provide additional design-time assemblies/resources to make that experience even better.  Custom control developers for XAML know about this .Design.dll that is created for their projects that can improve the design-time experience for UI controls.  I highly encourage you to do that if you are creating a control that is for wide distribution and not just yourself or your small group of friends.

Summary

Wow this felt like a long post…thanks for reading this far!  I think developing custom controls is a great way to encapsulate specific UI and behavior you want in your application.  XAML has a great ecosystem of control vendors and I fully expect them to produce controls for Metro style apps as well.  Hopefully these techniques of packaging them up for distribution will help us all take advantage of them.

I also think that creating an Extension SDK *and* a NuGet package are the best ways of thinking about it as a producer.  This enables your consumers to have the greatest flexibility in how they want to consume your control.  Creating these distribution mechanisms may seem cumbersome at first (and there are some places where Visual Studio can improve the experience of creating/managing these manifests), but once you understand the core layout that is required for a Metro style XAML control and the fact that you now have “loose files” to consider it really becomes pretty streamlined and you can automate the creation of these pretty quickly in your build systems.

Be sure to check out these resources again:

Here is the solution for the project I walked through above: SimpleCustomControl.zip

Hope this helps!