I’d like to provide you with a SilverBullet™, a small snippet of Silverlight, a class or namespace hidden in the silverlight .NET framework, to help you out in times of need. It’s not to learn, but something to keep in your pocket. Just remember it’s there and you’re safe.
When running Silverlight outside the browser, there’s the possibility that the computer that is running the applications is disconnected. This is where the System.Windows.ApplicationServiceContext class comes in. This class represents the initial state when the application is started. It has no methods of any significance, only two read only properties.
- ApplicationInitParams : Gets the parameters specified by the page where the silverlight plug-in is embedded in.
- RunningOffline: Indicated if the application is running in offline mode
The ApplicationInitParams property is a Dictionary of a string/string key/value pair and contains parameters with their values. On MSDN is a detailed article about how to define the HTML for using init parameters and query parameters and how to read them in Silverlight.
The RunningOffline property is a bool. It is True if the application is running offline and False when the application is running online. If you have enabled you application to run out of the browser, you can check this property to see if you can access any online services which may not be available when running offline.
Introduction
Today I would like to show you how to style a TreeView control in Silverlight using Expression Blend 3. The TreeView is a control to visualize hierarchical data structures. The TreeView control isn’t part of the standard Silverlight 2 or 3 download, but can be downloaded from http://www.codeplex.com/silverlight. The TreeView control is available in WPF natively and styling is only a small bit different than in Silverlight. I try to explain one way of doing this and there are others. If you have any questions what so ever or suggestions for other tutorials, please let me know.
Initial Startup
We’ll start by creating a new Silverlight 3 Application project.
Add reference to System.Windows.Controls.Toolkit.dll which is in the Silverlight Toolkit available on Codeplex.

The toolkit assemblies can be found in C:\Program Files\Microsoft SDKs\silverlight\v3.0\Toolkit\March 2009\Libraries when you’ve used the defaults during the installation.
After adding the reference, the toolkit is available in the Asset Library.
Add the TreeView to the RootLayout Grid and make it span the entire area. At this point nothing is visible, because there’s no data yet.
Sample Data
One of the features I really like in Expression Blend 3 is the generation of sample data. By using sample data you don’t have to wire your application up to a real data source and making it available when designing an application. Often I create sample data in Blend 3 to add it to parts of my production work in Blend 2.
A TreeView uses hierarchical data, which often are collections in collections in collections etc. I would like to have three different types of data all in collections. Create the first collection of data by going to the Data panel, click the Add sample data source icon and select Define New Sample Data…

Make sure the Enabled sample data when application is running checkbox is checked, so that you can see the result of the styled checkbox when running the application. Accept all other settings and hit the Ok button.

Rename the default collection to RootLevelCollection.
Change the type of Property1 to number by clicking on the little abc icon at the end of the line and select number from the dropdown list. Rename the property to NumberProperty.

Add a simple property and by clicking on the plus icon and rename it to NameProperty.

Change the string format by clicking on the abc icon and select Name from the Format dropdown list.

Add a new collection to the RootLevelCollection by clicking on the little down arrow on the same line and select Add Collection Property. Rename this to FirstLevelCollection.
Repeat the steps above to end up with the following properties:
RootLevelCollection
- NameProperty – Simple Property of String (Format: Name)
- NumberProperty – Simple Property of Number
- FirstLevelCollection – Collection Property
FirstLevelCollection
- CompanyProperty – Simple Property of String(Format: Company Name)
- NumberProperty – Simple Property of Number
- UrlProperty – Simple Property of String(Format: Website Url)
- SecondLevelCollection – Collection Property
SecondLevelCollection
- ImageProperty – Simple Property of Image
- NameProperty – Simple Property of String(Format: Name)
- PhoneProperty –Simple Property of String(Format: Phone number)
The sample data tree should look something like this. I added a few red lines to make the structure of the tree a bit more clear.

To bind the sample data to the TreeView, drag the RootLevelCollection to the TreeView element in the Objects and Timeline Panel. You should see some of the data appear in the tree immediately, although it doesn’t look very much like a tree yet.
Creating Hierarchical Data Templates
To show the data in the best way possible, every type of data needs it’s own Data Template. The HierarchicalDataTemplate, that you might know from WPF, is included in the Silverlight Toolkit. The Silverlight version doesn’t include all methods and properties the WPF version does, but provides an easy way to style hierarchical data.
Due to a bug in Silverlight, Expression Blend will show an error when using nested Hierarchical Data Templates. There seems to be a problem in the xaml parser, which says the xaml is invalid. But it isn’t and the application will run anyway. I’ll show you how to work around this error. Let’s hope this gets fixed in the final release.
Because the sample data created earlier contains three levels, three collections of a different class, three different data templates are needed to show the data properly. To keep these templates separated and enable the possibility to share the templates between different pages and UserControls very easy, I prefer to put data templates in there own Resource Dictionary. A resource dictionary is a xaml file that contains only resources. To add a new dictionary to your project click File –> New Item… and select Resource Dictionary from the list. If you want you can give it a useful name, for now, just accept the default by clicking Ok.
Now you need to link the new resource dictionary to the TreeView so it can access the templates. Go to the Resource panel and right-click [TreeView] control, select Link to Resource Dictionary and click ResourceDictionary1.xaml.
Right-click ResourceDictionary1.xaml in the resource panel and hit View XAML to open the resource dictionary.
To make use of a HierarchicalDataTemplate xaml, you first need to reference it’s namespace. Do this by adding the following line to the opening ResourceDictionary tag at the beginning of the file:
xmlns:common="clr-namespace:System.Windows;assembly=System.Windows.Controls"
The hierarchical data template has three dependency properties. For now, use only the ItemSource property. The ItemSource property can be bound to the collection used for the next level in the hierarchical tree. In this example this would be the FirstLevelCollection. The contents of the data template are not very special. Just an horizontal oriented StackPanel with two TextBlocks. The first one is bound to the NumberProperty and is slightly bigger than the other. That one is bound to the NameProperty of the root sample data class. Add a small margin to give the TextBlocks a little more space.
<common:HierarchicalDataTemplate x:Key="RootLevel"
ItemsSource="{Binding Path=FirstLevelCollection}">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5,0,3,0"
Text="{Binding Path=NumberProperty}"
FontWeight="Bold" FontSize="12" />
<TextBlock Margin="3,0,5,0"
Text="{Binding Path=NameProperty}" />
</StackPanel>
</common:HierarchicalDataTemplate>
This data template needs to be known by the TreeView. Right-click on the TreeView control in the Objects and Timeline Panel and go to Edit Other Templates –> Edit Generated Items(ItemTemplate) –> Apply Resource and select RootLevel from the list.
You should see some changes to the tree now. It doesn’t look a lot like a tree yet. To style the second level of the tree, add another HierarchicalDataTemplate to the ResourceDictionary. This template has to be defined before it’s used, which will be by the root template. It looks similar to the template above, only the key and the bindings are different. This template has it’s ItemSource bound to the collection for the second level, SecondLevelCollection.
<common:HierarchicalDataTemplate x:Key="Level1"
ItemsSource="{Binding Path=SecondLevelCollection}">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5,0,3,0"
Text="{Binding Path=NumberProperty}" />
<TextBlock Margin="3,0,3,0"
Text="{Binding Path=CompanyProperty}" />
<TextBlock Margin="3,0,5,0"
Text="{Binding Path=UrlProperty}" />
</StackPanel>
</common:HierarchicalDataTemplate>
At this point nothing will happen, because the two templates need to be connected. The HierarchicalDataTemplate uses a dependency property, similar to the one on the TreeView, to do this: ItemTemplate. To use the Level1 data template as an item template add the following line to the start tag of the RootLevel template:
<common:HierarchicalDataTemplate
x:Key="RootLevel"
ItemsSource ="{Binding Path=FirstLevelCollection}"
ItemTemplate="{StaticResource Level1}">
...
As soon as this gets evaluated by Blend and error is thrown: Invalid Xaml. Don’t be too scared by this, because when you run the application by pressing F5, the application will run without any problems. This is the bug I was talking about earlier. They way I work around this when editing the templates in Expression Blend is adding an commented area to cut-paste the ItemTemplate property to and from. Use this construction when editing the templates in Blend and cut-paste it back when running the application:
<common:HierachicalDataTemplate
x:Key="RootLevel"
ItemsSource ="{Binding Path=FirstLevelCollection}"
>
<!--
ItemTemplate="{StaticResource Level1}"
!—>
...
There's only the second level of the template left to style. It’s similar to the other two. Bind the source of the image to the ImageProperty and set it’s width and height to 25.
<common:HierarchicalDataTemplate x:Key="Level2">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5,0,3,0"
FontStyle="Italic"
Text="{Binding Path=NameProperty}" />
<TextBlock Margin="3,0,3,0"
Text="{Binding Path=PhoneProperty}" />
<Image Margin="3,0,5,0"
Height="25" Width="25"
Source="{Binding Path=ImageProperty}"/>
</StackPanel>
</common:HierarchicalDataTemplate>
Don’t forget to set the ItemSource property on the Level1 template to Level2 when running the application.
To quickly access the templates for editing. Select the MainControl.Xaml file for editing and go to the Resource panel. When you expand the ResourceDictionary1.xaml dictionary file, you can open the templates for editing by clicking on the button next to the template names:
When running the application should look something like:
It looks like a tree now, but not a very awesome one. Let’s style it a little further.
Creating Control Templates
To make the tree look a little better, you need to change its ItemContainerStyle.

Give it a fancy name. To add it to the ResourceDictionary select the Resource dictionary radio button in the define in section. Hit OK to confirm and close the window.

To get to the template, right-click the Style element and select Edit Control Parts –> Edit Template.
The TreeViewItemTemplate consists of 3 important parts: the Header, which represents one item; ItemsHost, which represents the child items of the header (these items can be headers with children too); and the ExpanderButton, which is the indicator if a header is expander or not. First, lets change the look and feel of the ExpanderButton.
Right-Click the ExpanderButton element and select Edit Control Parts(Template) –> Edit Template.
The default template contains a couple of grids and two paths. These are unnecessary, so delete the [Grid] element including the two paths. The paths were animated, so ignore the message about this.
Add a Border to the Root grid element. Start by giving it a fixed width and height of 24. Change its Corner Radii to 8,3,3,8 and its Border Thickness to 1,2,1,1 to give it a little flow to the right. Change the Border Color to a gradient, starting and ending on a darkish blue color like #FF0D0A45. Add a Gradient Stop at about 20% and make this a little whiter than the start and end. Set the Background Color to a SolidBrush and change its color to a lighter version of the gradient, like #FF5C5A88.
Next, add a Grid to the border and make sure all properties are set to their defaults. Add two TextBlocks to he grid and name them PlusSign and MinusSign. Type in the PlusSign textblock a “ + “ and in the MinusSign textblock a “ – “. Set the Horizontal- and the Vertical Alignment on both textblocks to Center. Change their fonts to Verdana, make them Bold and increase their sizes to 18. Set the Foreground Color to full white on both. Hide the MinusSign by default by setting its opacity to 0. This only has to become visible when the tree is expanded.
The Xaml should look something like:
<Border x:Name="border"
BorderThickness="1,1,2,1"
Width="24" Height="24"
CornerRadius="8,3,3,8"
Background="#FF5C5A88">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1"
StartPoint="0.5,0">
<GradientStop Color="#FF0D0A45" Offset="0"/>
<GradientStop Color="#FF0D0A45" Offset="1"/>
<GradientStop Color="#FF3A385B" Offset="0.2"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Grid>
<TextBlock x:Name="PlusSign"
Text="+" TextWrapping="Wrap"
FontFamily="Verdana" FontWeight="Bold"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Foreground="#FFFFFFFF" FontSize="18"/>
<TextBlock x:Name="MinusSign"
Text="-" TextWrapping="Wrap"
FontFamily="Verdana" FontWeight="Bold"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="18" Opacity="0"
Foreground="#FFFFFFFF"/>
</Grid>
</Border>
The change to looks of ExpanderButton when it is checked, you can use the Visual State Manager. Go to the States panel and select Checked under the CheckStates Visual State Group. Notice the red border around the drawing area, this indicates that every change you make is recorded and stored in this particular Visual State.
With the Checked State selected, change the Opacity of the MinusSign element to 100 and of the PlusSign to 0. At this point the MinusSign is visible when the TreeView is expanded. Change the Corner Radii of the Border to 8,8,3,3 and the Thickness to 1,1,1,2.
The Xaml for the Checked State is placed inside the code for the Visual State Manager. It should look something like:
<vsm:VisualState x:Name="Checked">
<Storyboard>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Duration="00:00:00.0010000"
Storyboard.TargetName="MinusSign"
Storyboard.TargetProperty="(UIElement.Opacity)">
<EasingDoubleKeyFrame KeyTime="00:00:00" Value="1"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Duration="00:00:00.0010000"
Storyboard.TargetName="PlusSign"
Storyboard.TargetProperty="(UIElement.Opacity)">
<EasingDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
Duration="00:00:00.0010000"
Storyboard.TargetName="border"
Storyboard.TargetProperty="(Border.CornerRadius)">
<DiscreteObjectKeyFrame KeyTime="00:00:00">
<DiscreteObjectKeyFrame.Value>
<CornerRadius>8,8,3,3</CornerRadius>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
Duration="00:00:00.0010000"
Storyboard.TargetName="border"
Storyboard.TargetProperty="(Border.BorderThickness)">
<DiscreteObjectKeyFrame KeyTime="00:00:00">
<DiscreteObjectKeyFrame.Value>
<Thickness>1,1,1,2</Thickness>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
To make the tree a bit more user friendly, you want to highlight the ExpanderButton when the mouse cursor is hovering. Got to the States panel and select MouseOver this time. It’s in the Common States Visual State Group. To keep the same gradient it would be nice if you could only shift the colorization. You can do this by changing the color mode setting. If you look at a color editor, notice that there the R, G and B are underlined. When you click on one a small listbox pops up and you can change the color mode. If you change it to HSL, Hue – Saturation – Lightness, you have the possibility to shift the Hue, which happens to be the colorization.
Change the Hues for the the Border gradient and for the Background color to 48.
To position the ToggleButton properly, remove the second column of the root Grid of the template and set the width of the first column to 32 and the with of the now second column to 1 star. The same goes for the two rows, the first to 32 pixels and the second to 1 star. Making this piece of xaml look something like:
<Grid Background="{x:Null}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="32"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="32"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
...
Click the button with the arrow next to ToggelButton Template in the Objects and Timeline panel to leave the template.
To place the child items in a container, right click the ItemsHost element in the Objects and Timeline panel and select Group into… and select Grid, or press Ctrl+G on the keyboard. Make sure all properties are set to their defaults, the Grid tag in xaml should be empty. Next, right click the Grid you’ve just added and go to Group into… again, but this time select Border. Give this border a gradient for its Background brush and make it go from an almost white purple to just a little darker than that, like from #FFD4D2F9 to #FF908BEE. The BorderBrush for this border will be the same as the border used for the ToggleButton explained earlier. Set the border Thickness to 1 on all four to make the border visible. Change the border’s CornerRadius to 1,4,8,4 to give a modern look.
Change the location of the border to row 1, column 1, rowspan 1 and gridspan 1. To make the border indent less that 32 pixels, but keeping it bound to the second column, change the Left Margin to –27. This will make it look like its indentation is only 5 pixels, but, to keep the TreeView work correctly, resize it only to the second column. Set the Left Padding to 5 to let the contents of the border indent even a little more.
When you run the application at this point, a small line will be shown for every item of the TreeView. This is cause by the Visual State Manager only hiding and showing the ItemsHost at this time. To make the entire border disappear, copy the following two properties from the ItemsHost to the Border in the xaml editor.
Visibility="Collapsed"
x:Name="ItemsHost"
The border will be named ItemsHost now. And when you run the application, the border should become visible when TreeView Items are expanded. It is possible you’ll see an error when the properties are removed from the ItemsHost. I assume this is cause by the same bug as with the Hierarchical templates. If you want to make the border visible again, move these properties back to the ItemsHost, which is now called ItemsPresenter, its default name.
I personally like a shiny edge on borders. It’s very easy add that little spark. Start by adding a rectangle to the grid and place this above the ItemsPresenter(this used to be ItemsHost) element in the same grid. Keep the width and height of 100. Set the Fill to No Brush to make its background transparent. The Stroke brush has to be set to a gradient, going from fully transparent white to 50% transparent white. Set its radii to 8 and its StrokeThickness to 1. Make it Horizontally align to the Right and the Vertical alignment to the Bottom. Set the right and bottom margins to 3, keeping the left and top margins 0. The last part is best done in xaml and has to do with the start and end positions of the gradient. The gradient needs a StartPoint of 0.7, 0.7 and an EndPoint of 1.0,1.0. The xaml for the rectangle:
<Rectangle Fill="{x:Null}"
RadiusX="8" RadiusY="8"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Width="100" Height="100"
Margin="0,0,3,3">
<Rectangle.Stroke>
<LinearGradientBrush
EndPoint="1,1"
StartPoint="0.7,0.7">
<GradientStop Color="#00FFFFFF" Offset="0"/>
<GradientStop Color="#7FFFFFFF" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Stroke>
</Rectangle>
Before running the application, make sure you’ve cut-pasted the ItemTemplates to the right places in the Hierarchical data templates and set the Visibility and Name properties correctly on the Border in the TreeViewContainerStyle.
running version in Silverlight 3
Where to go from here
This tutorial only showed what can be done styling the TreeView, which templates are available, and where can they be found. Imagine what you can do with real data, creating a style that looks and feels one with the data. You can even go beyond the basic TreeView and create multiple columns or a Tab-like style.
One place I want to mention is the blog of Bea Stollnitz. On her blog she give a lot of information and explanation about TreeViews and ListViews, for WPF and Silverlight.
The code for the tutorial can be downloaded here.
I’d like to provide you with a SilverBullet™, a small snippet of Silverlight, a class or namespace hidden in the silverlight .NET framework, to help you out in times of need. It’s not to learn, but something to keep in your pocket. Just remember it’s there and you’re safe.
One of the great new features of Silverlight 3 is the so called “Out of Browser” support. This means you can run your application without the browser, but still using the browser secure sandbox. The ApplicationIdentity class can be used to provide some extra information about your application when running outside the browser. The ApplicationIdentity class is primarily used in the AppManifest.xaml file in which information about the application is stored, but the identity information can be read from code.
When you look at this file in a new Silverlight 3 project, the ApplicationIdentity part is commented. Uncommenting this section will enable Out of Browser support for your application.
The ApplicationIdentity class provides four read-only static dependency properties.
- Blurb Contains a short description of the application
- ShortName Contains a short version of the application title
- Title Contains the longer version of the application title
- Icons Contains a list of references to images used as Icons in different sizes
The Blurb, ShortName and Title properties are regular strings and can be used like any other strings in xaml.
The Icons property is of type IconCollection, which is a collections of icons. An Icon has two properties, Source and Size. Source holds the path to a .PNG file of the icon. Size is a string representation of the size, “16x16” for example.
Here’s an example of how the ApplicationIdentity class is used in the AppManifest.xaml file.
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
... >
<Deployment.Parts>
...
</Deployment.Parts>
<Deployment.ApplicationIdentity>
<ApplicationIdentity
ShortName="Out of Browser Silverlight Application"
Title="SilverBullet #4 - Test App">
<ApplicationIdentity.Blurb>
A demo application explaining Application Identity
when running outside of the browser.
</ApplicationIdentity.Blurb>
<ApplicationIdentity.Icons>
<Icon Size="256x256">Favorites.png</Icon>
</ApplicationIdentity.Icons>
</ApplicationIdentity>
</Deployment.ApplicationIdentity>
</Deployment>
You can read the ApplicationIdentity dependency properties from code by using the class directly by getting the values like:
string Blurb = GetValue(ApplicationIdentity.BlurbProperty) as string;
string Title = GetValue(ApplicationIdentity.TitleProperty) as string;
IconCollection icons = GetValue(ApplicationIdentity.IconsProperty) as IconCollection;
aRandomImage.Source = new BitmapImage(new Uri(icons[0].Source));
I’d like to provide you with a SilverBullet™, a small snippet of Silverlight, a class or namespace hidden in the silverlight .NET framework, to help you out in times of need. It’s not to learn, but something to keep in your pocket. Just remember it’s there and you’re safe.
There are situations where you want to know which UI element has focus. One way of doing this is handling the GotFocus and LostFocus events. These events are only raised when an element gets or looses focus, and are handled asynchronously. When you want to know what element has focus in other situations or if you need to get the focus synchronously, you can use the FocusManager class which can be found in the System.Windows.Input namespace.
The FocusManager class has only one static method:
public static Object GetFocusedElement();
The GetFocusedElement method often returns a Control, but may return null if the browser windows doesn’t have focus or if there are no true Control elements in the UI.
Using the FocusManager is easy. Here’s a small example of a possible usage:
var focusedElement = FocusManager.GetFocusedElement() as Control;
if (focusedElement != null)
Output.Text = focusedElement.Name;
One last note: The FocusManager class is also available in the “normal” .NET Framework 3.0 or later.
I ran into this series of videos when exploring Microsoft Showcase this morning. If you’re just starting with Expression Blend or if are more experienced, these sessions can provide you with much useful information. There are 7 part, all listed below. If you want to learn more about the Expression Products or any other Microsoft product, just browse and Bing around Microsoft Showcase.
Microsoft Expression Blend Essentials (1/7): Projects and Hierarchies
Microsoft Expression Blend Essentials (2/7): Layout Controls
Microsoft Expression Blend Essentials (3/7): Custom and User Controls
Microsoft Expression Blend Essentials (4/7): Interaction
Microsoft Expression Blend Essentials (5/7): Animation
Microsoft Expression Blend Essentials (6/7): Data Binding
Microsoft Expression Blend Essentials (7/7): WPF and Microsoft Silverlight
Tags van Technorati:
Expression Blend
I’d like to provide you with a SilverBullet™, a small snippet of Silverlight, a class or namespace hidden in the silverlight .NET framework, to help you out in times of need. It’s not to learn, but something to keep in your pocket. Just remember it’s there and you’re safe.
The System.Json namespace provides support for Javascript Object Notation or JSON. By using the classes in this namespace you are able to use Json objects in your C# or VB code. These object are often used in JavaScript and to send to and be returned by services.
The namespace contains four classes. The first, JsonValue is the base class for the other three. It has a few methods to load, save and parse strings and streams. The ToString method is overloaded to return text based Json.
The JsonPrimitive class represents a Json primitive type in the CLR. For example a byte, string or int. It’s constructed like:
var pInt = new JsonPrimitive(25);
var pString = new JsonPrimitive("abc");
var pDouble = new JsonPrimitive(3.14);
The JsonArray class represents an array of JsonValues. Using the JsonPrimitives from the earlier example, JsonArray can be constructed and used like:
var ar = new JsonArray {pInt, pString, pDouble};
output.Text = ar.ToString();
After running this, the output.Text value will contain:
[25,"abc",3.14]
The JsonObject represents a collection of key/pair values. Using the same values again, JsonObject can be constructed and used like:
var ob = new JsonObject {
{"pInt", pInt},
{"pString", pString},
{"pDouble", pDouble}
};
output2.Text = ob.ToString();
In this case, output2.Text will contain:
{"pInt":25,"pString":"abc","pDouble":3.14}
Last thing I would like to mention is the JsonType enumeration. This enum is returned by the JsonType property on the JsonValue class. And represents the type of CLR object the JsonValue instance is representing.
I’d like to provide you with a SilverBullet™, a small snippet of Silverlight, a class or namespace hidden in the silverlight .NET framework, to help you out in times of need. It’s not to learn, but something to keep in your pocket. Just remember it’s there and you’re safe.
This first SilverBullet™ I would like to give you is the Environment class. It’s in the System namespace and provides information about the environment your application is running in. Use it to get information about the system, like command-line arguments, version of the CLR and the time the system is running. Some properties and methods in this class are used internally and can cause security risks. These properties and methods will throw an MethodAccessException. All properties are static.
The properties that can be used are:
- Environment.ExitCode; a 32-bit int containing the current exit code.
- Environment.HasShutdownStarted; a bool indicating the CLR is shutting down or the appdomain is unloading.
- Environment.NewLine; a string containing the local systems newline characters, this is different on unix and windows.
- Environment.OSVersion; an OperatingSystem object containing a platform id and version.
- Environment.TickCount; a long containing the amount of milliseconds since the system started.
- Environment.Version; a Version object describing the version of the CLR.
If you have any suggestions for another SilverBullet™, please let me know.
Tags van Technorati:
Silverlight

The last thing I wanted to do for my WinPHP contest entry BlogSnor is publishing some kind of manual. Instead of walk you thru in text and images, I would like to show you a few videos.
The first video shows the registration process of a new user. He comes to the site and hits register. He logs in with his Live ID and is redirected back to BlogSnor where he has to fill out a form. After submitting this his account awaits activation by one of the administrators.
The second video shows the next step in the registration process. A administrator has got an email explaining that a new user has registered. If the administrator thinks the new user should deserve a weblog on BlogSnor he clicks the link in the email and the weblog is activated.
The Administrator sends the new user an email explaining he can login now. The user goes to http://95.211.64.138/Blogsnor and extends the url with his own blog ID. He click Admin and, because he’s already logged in with his Live ID, is directly taken to the admin screen. The new user doesn’t like the default colors and searches for “sunset” in the http://kuler.adobe.com library. He selects one of the sets and clicks submit to let BlogSnor generate all images for him.
Now everything is setup, the new user would like to create a blog post. Before he can do that, he needs to download and setup Windows Live Writer. After the installation he starts it and adds a new “other blog service” account. He enters his credentials and lets Live Writer know he would like the MetaWeblogAPI. He enters the url http://95.211.64.138/BlogSnor/WeblogMetaApi.php and let Live Writer detects his theme. Now he’s ready to start blogging.
I hope these videos help you to get going with BlogSnor. If you have any questions, please feel free to send me an email at blogsnor@live.com.

Introduction
The WinPHP challenge is running towards it’s closing time. Only a few days before entering I came with the idea to enter the contest. I had to put a lot of my spare time into it, but it was worth it. I learned a lot from exploring the realm of php. It’s fun to work in a language I normally do not work in. And to find ways to implement some thoughts that have been on my mind for a while. Here’s the story about the what, the where and the how of BlogSnor, my entry for the WinPHP challenge.
Flashback
Let’s start by looking back at what I was thinking of before I started.
I wanted:
-
-
Microsoft SQL Server for storing all data.
-
Windows Live ID authentication.
-
Easy to read urls for search engines and make them easy to read.
-
Send update to twitter and emails on post.
-
online and offline editing using windows Live Writer and an online editor.
-
And run it all on Windows Server 2008 and IIS7.
-
Generate an RSS feed.
I had some ideas about how to some components, but haven’t had a change to build them into an application. The main thing was the styling part. The idea of using a small set of colors with some relevance to each other to generate an entire website.
Styling
Once a user is registered to BlogSnor and his weblog is activated, he can go to the admin section where he has the possibility to select a set of colors and a banner. By default a random set of 10 styles is retrieved from kuler.adobe.com, by the user can search for a more distinct set of colors.

The colors selected by the user are sorted from light to dark of from dark to light according to the user’s preferences. This results in a style with a light or a darker feel to it. The best sets of colors are colors that have a bit of lighter and darker colors in it. The funny thing is that almost all sets of colors will result in an acceptable style. In some situations, where the color of the text and it’s background are to close together, the engine decides to change the text color to white or black to give it a bit more contrast. When the user has selected a set of colors and clicks submit, a whole new set of images and a css file is generated.
For the generation of the images I wanted to use Xaml. Xaml is a great way to define use interfaces, but can be of much help describing graphics too. I’ve written a detailed description about the image generation using WPF thru .NET assemblies in a previous post. For the banners I used 8 big (1800x600) images as a basis. A small portion is randomly selected and colorized.
Storing Data
Using Microsoft SQL server 2008 was the obvious choice, because this contest is about running on Windows server. The design of the database is very straight forward. This constructions allows weblogs to have multiple authors. This isn’t fully supported in the first version of BlogSnor, but can easily be implemented in the future. All possible tags are stored in a single table. This allows a user to add tags with a single click in Live Writer and create an summary of all used tags on the main page.

For querying the database I create a class based on the Singleton Pattern. Because I wanted to query the database multiple times in a single session using the same connection I used a static function. This combination gave me a way to use a single line of code for each query, like $result = db :: query (“select * from Weblog”); .
I configured the SQL server, installed on the remote server that was provided for the challenge, so that I could access it from my local SQL Server Management Studio. This way I could write and test queries without needing to remote connect to the contest server and work in management studio there.
A nice side effect of using the remote access is the possibility to use the SQL Profiler that comes with non-free versions of SQL studio which I happen to run for work. Using the profiler I was able to debug the queries send to the server and catch many unsuspected errors.
Authentication
For authentication I wanted to use the Windows Live ID authentication. I use this mechanism to log into many Microsoft sites for years and always wanted to know how this works. I turned out to be very easy to implement nowadays. Just register your site with Live Service and you’re ready to go. On MSDN there’s detailed documentation on how to implement Live Id in your own site. You redirect to a Windows Live site and let the user login there. A token is returned and the code to process that to a user ID is provided by Microsoft. All you have to do is store a cookie with the token to make sure the users doesn’t have to log in every time he enters the site.
URL Rewriting
To make the URLs more easy to read I used the URL Rewriter that was installable thru the Web Platform Installer. This uses a Regular Expression to filter parts of the url and send this to another url, thus gives the ability for the user to write a normal readable URL and let the website use URLs with complex query parameters.
Another thing I want to mention here is actually a feature of IIS7. Since IIS7 configuration is stored in a Web.Config file. This file is stored in the root of your web application and doesn’t contain machine specific information. This means that you can create a number of URL redirects and rewrites on your local test machine and all you have to do to make this work on your production server is copying this web.config file and all your settings are used there too.
Sending Updates
I thought of sending notifications to twitter and to visitors thru email. I decided at the beginning of the project to let the idea of creating a subscription mechanism go. This would take too much time and doesn’t add very much to the project. Sending Twitter updates was something I definitely wanted to implement. It’s very easy to do and only takes a few lines of code. Because twitter was so easy to use, I added small twitter timeline to the sidebar of the weblog.
Twitter can return a timeline of a user in xml form, which made it very easy to present to the user in a nice looking way. The only thing that took a little more thought was the linking. I wanted to link hash tags like #winphp to the twitter search and the user representation @sorskoot to the user page. I added one small extra feature. Some twitter updates are replies to other updates. This information is provided in the twitter xml message. Therefore I added a @ in these cases to link to the message that is replied to.
You can follow all updates on @BlogSnor.
Editing of Posts
I personally use Windows Live Writer for writing blog posts. So I wanted to implement this.

After doing some research I decided to go with the Metaweblog API. Mainly because this format is supported by Windows Live Writer, but also because other applications may implement this API too and can be used also. Another thing that made me choose this API is that is uses XML-Rpc which was on my personal “things-to-learn” list for a long time. To make thing easier, a detailed description of all functions that needed to be implemented is on MSDN. Windows Live writer is sending messages to my implementation at http://95.211.64.138/BlogSnor/WeblogMetaApi.php. This URL needs to be given to Windows Live writer when it asks for it when configuring a new weblog. If you have any questions about this, please feel free to send me an email. Because Windows Live Writer is such a great tool I decided not to implement a web editor. It’s not that complex to add later and can use the same API.
Unplanned
One thing I forgot to mention at the beginning of the project was Silverlight. I use Silverlight often and I like it very much. I wanted to see if I could do anything with that. I wanted to use Silverlight without using C# and the need to compile it into a XAP file. The only way to do this was to reach back to Silverlight 1.0. The first version of Silverlight used Javascript for event handling and stuff instead of actual code behind.This way I could use php to create xaml file for Silverlight and still be able to handle some events. I created a simple tag cloud that moves a little when the mouse is hovering over it.
Another thing I implemented was the use of a Gravatar. This is a service that enables user to add a picture to there email address that can be used by weblog engines like this one. It’s API is very easy to use and they even provide a funny image when a user doesn’t have his email address registered.
I wanted to use AJAX to get the kuler color sets from adobe. I’ve found a project somebody is running on codeplex that makes it very easy to implement Microsoft AJAX in php. It lets you get JavaScript from your php file and enable you to call that when needed. This way you can call functions in you php files on the server from the client.
Last but not Least
I had fun working on this project. I learned a lot from techniques used and a lot from the community. Although everyone has different backgrounds, everyone nice and helpful to each other.
I want to thank to sponsors for running this contest.
And my wife, for having to deal with me putting all my time into this challenge.


Introduction
In an earlier article I explained how to use .NET assemblies in php. This concept is the basis of the image generation as used in my entry for the WinPHP challenge.
Because the user is in control of selection colors, all images used throughout the weblog need to be generated. Php provides a number of graphical functions, but none is capable of creating rounded corners an gradients with ease. Everything has to be done by hand. WPF on the other hand uses xaml which supports everything you can think of in modern vector graphics design. Using a .NET assembly that takes a string of xaml and returns a PNG image would be the best in this case.
Rendering Xaml in .NET
The method exposed to the outside world is the GenImageFromXaml method.
public string GenImageFromXaml(string xaml)
As you can see, this method takes a string of xaml. Although the method returns an images, a conversion to a base64 string is necessary for proper handling in php.
Wpf provides the XamlReader class. This class makes it possible to convert a string of xaml to .NET objects. These objects can be used in the same way as “normal” objects. The first thing this method needs to do is calling the static Parse method on the XamlReader class. Because this method returns an object and the process later needs a FrameworkElement a cast is inevitable.
var element = (FrameworkElement)XamlReader.Parse(xaml);
Next, this element needs to be rendered to an image. Luckily the framework provides some functionality for that. I’ll explain that a bit later. The render method, GetPngImage, returns an array of bytes which represent the png image. Convert.ToBase64String method takes that string and converts it to a base64 string. This is returned by the GenImageFromXaml method to be handled by the caller of this method, php in this case.
return Convert.ToBase64String(GetPngImage(element));
The GetPngImage method is a bit more complex.
private static byte[] GetPngImage(FrameworkElement element)
It uses the element parameter to gather information about it’s size and calculates at which size it is supposed to be rendered.
var size = new Size(element.Width, element.Height);
element.Measure(size);
element.Arrange(new Rect(size));
The image that is rendered needs a place to stay, thus a RenderTargetBitmap is needed. The constructor of this class needs a few parameters: The height and width of the image in pixels; The DotsPerInch or DPI for the X and Y axis of the image; and a PixelFormat that defines where all color information should go.
var renderTarget =
new RenderTargetBitmap((int)element.RenderSize.Width,
(int)element.RenderSize.Height,
96, 96,
PixelFormats.Pbgra32);
The renderer of the image uses an VisualBrush, which is used to paint areas with visuals.
var sourceBrush = new VisualBrush(element);
var drawingVisual = new DrawingVisual();
After all declarations and pre-calculations are done, it’s finally time for the actual drawing and rendering of the image. By using a using construction the DrawingContext is disposed immediately after the closing bracket. The DrawingContext is used to draw the sourceBrush defined earlier into the drawingVisual, giving it the maximum size of the element. The drawingVisual is than rendered into the renderTaget bitmap.
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawRectangle(
sourceBrush, null, new Rect(
new Point(0, 0),
new Point(element.RenderSize.Width,
element.RenderSize.Height)));
}
renderTarget.Render(drawingVisual);
To be able to use the final bitmap in php and make it appropriate for the web, I chose to use PNG as an image format. Mainly because PNG supports transparency and it doesn’t show many artifacts of compression and anti-aliasing as many other formats do. Encoding PNG isn’t hard in .NET. Simply instantiate a new PngBitmapEncoder and add the previously rendered image, renderTarget, to it.
var pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
The last part of the render method is returning the bytes of the PNG image. The PNG is saved into a MemoryStream. This stream is than returned in the form of a Byte Array.
using (var outputStream = new MemoryStream())
{
pngEncoder.Save(outputStream);
return outputStream.ToArray();
}
Rendering Xaml in PHP
The rendering from php using the .NET assembly created above isn’t very complex. It starts by creating a new COM class by using the assembly. Next, it uses an inline string passed into $xaml. Everything between <<<EOT and EOT is xaml and will be rendered to an png image. This string is passed to the GenImageFromXaml method on the class using the $xaml string. Because it is base64 encoded, php needs to decode the result. After that an image is created using this string and returned to the caller.
<?php
$ImgGen = new COM("BlogSnorLib.ImgGen");
$xaml = <<<EOT
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="UserControl"
Width="50" Height="50">
<Border x:Name="LayoutRoot" BorderThickness="1,1,1,1"
CornerRadius="10,5,20,5" BorderBrush="#FF096900">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF16FF00" Offset="0"/>
<GradientStop Color="#FFFFFFFF" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<Ellipse Stroke="#FF332D00" Height="25.059" Width="25.059">
<Ellipse.Fill>
<RadialGradientBrush>
<RadialGradientBrush.RelativeTransform>
<TransformGroup>
<ScaleTransform CenterX="0.5"
CenterY="0.5"
ScaleX="1.341"
ScaleY="1.341"/>
<SkewTransform AngleX="0"
AngleY="0"
CenterX="0.5"
CenterY="0.5"/>
<RotateTransform Angle="0" CenterX="0.5" CenterY="0.5"/>
<TranslateTransform X="-0.18" Y="-0.161"/>
</TransformGroup>
</RadialGradientBrush.RelativeTransform>
<GradientStop Color="#FFFFDF00" Offset="0.014"/>
<GradientStop Color="#FF756700" Offset="1"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
</Border>
</UserControl>
EOT;
$Img = $ImgGen->GenImageFromXaml($xaml);
$Img = base64_decode($Img);
$finalImage = imagecreatefromstring($Img);
imagesavealpha($finalImage, true);
$ImgGen = null;
header('Content-type: image/png');
imagepng($finalImage);
imagedestroy($finalImage);
?>
You can use this php code as an image in html like <img src=”ImgGen.php” />, where ImgGen.php is the file containing the code above.
The rendered image should look something like the image below. Note the rounded corners and radial gradient which aren’t provided by php natively, but can be used now using the .NET assembly mechanism.

