## Color confusions…

3.April.09 – 12:27

when i was working with WPF earlier this morning i wondered how microsoft got to the color names in their System.Windows.Media.Colors class.

At least i’m somewhat confused that Gray (#FF808080) is darker than DarkGray (#FFA9A9A9)

they probably have some really strange monitor settings over there in redmond

## Using the new WPF Ribbon with CompositeWPF

13.November.08 – 18:45

When using the new WPF Ribbon CTP with CompositeWPF (aka Prism), you probably want your modules to fill the ribbon with tabs. To let modules add content to your shell window, you have to mark the designated areas as Region.When trying to add a Region name to the ribbon with some xaml code like this :

<r:Ribbon cal:RegionManager.RegionName="ApplicationRibbon"> ....</r:Ribbon>

you will get a KeyNotFoundException.
Diving a little bit deeper shows you that the RegionManager cannot find a RegionAdapter mapping for Microsoft.Windows.Controls.Ribbon.Ribbon.That means that we have to write a RegionAdapter for the Ribbon Control.Implementing IRegionAdapter should suffice but as we are lazy, we could just inherit from RegionAdapterBase<T> (where our T will be Ribbon) and we will end up with something short like this:

 public class RibbonRegionAdapter : RegionAdapterBase<Ribbon>
{
protected override void Adapt(IRegion region, Ribbon regionTarget)
{
region.Views.CollectionChanged += delegate {
foreach (var tab in region.Views.Cast<RibbonTab>())
{
if (!regionTarget.Tabs.Contains(tab))
{
}
}
};
}

protected override IRegion CreateRegion()
{
return new SingleActiveRegion();
}
}


at least we have to Register this RegionAdapter in our bootstrapper. Therefore we just override the Bootstrapper’s ConfigureRegionAdapterMapping’s method:

protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
if (mappings != null)
{
}
return mappings;
}


Now we should be able to add RibbonTab’s to the ribbon from within our Modules using RegionManager (we can easily resolve this from our IoC Container).

This is no full featured quality guide for using the Wpf Ribbon control with CompositeWpf. It just shows that writing custom region adapters is actually quite an easy thing.

## Barcodes everywhere…

10.November.08 – 18:41

if you’re interested, check out our blog at lemQi. I just posted a comparison of Project Bamby compared to other (commercial) barcode recognition libraries working with image processing. Also, Sebastian posted some stuff about thresholding methods we used.

There will be much more activity over there than here in the next time, although i have some stuff pending on my “ToPublish” list

## DateTime parsing performance

30.July.08 – 11:10

In one of my current projects i have to convert a lot of strings to DateTime structures. Sometimes tens of thousands datetime-string arrive at the service per second. As performance is an issue in this project, i was looking for the most performant way to do all the stuff. that’s why i put on a little test to evaluate performance of the different DateTime parsing methods.

Our 4 candidates are :

• DateTime.Parse
• DateTime.ParseExact
• DateTime.TryParse
• DateTime.TryParseExact

I also wanted to know if there is a difference when using different IFormatProviders. To benchmark i used the InvariantCulture, a concrete CultureInfo (”de-DE” in this case as i could not see any difference between “de-DE”,”en-US”,”fr-FR”,…) and no IFormatProvider for the Parse/TryParse methods (having an IFormatProvider is mandatory for the ***Exact methods).
The following chart shows the result for 10.000.000 calls to every one of those methods.

I was kinda surprised that TryParse was not faster than Parse. But overall the results showed what i expected. TryParseExact is by far the fastest of them all. So , if you care about performance and have to parse a lot of strings into a DateTime structure, use TryParseExact().

Edit:I was pointed out to the System.Convert.ToDateTime() Method, but as it uses DateTime.Parse() internally, performance is the same as DateTime.Parse(), so TryParseExact is still the way to go.

## WPF WebBrowser control issues with AllowsTransparency = True

7.July.08 – 15:55

I recently played around with the new Webbrowser control delivered with the SP1 update of .NET 3.5 .
But when i tried to use it in a WPF Window that has its WindowStyle set to None and AllowsTransparency to True (due to some custom window drawing), i noticed that the Webbrowser control disappeared.

The Webbrowser control is just a native Win32 Hwnd that gets hosted inside some WPF content area. But it’s quite annoying that the Transparency stuff gets pass on to it.
I wonder how i could circumvent this limitation as i don’t need transparency in the webbrowser control itself. Its just to get some homegrown, fancy-looking window style.

I’m looking forward to see this fixed by Microsoft in some future release.

## sorry for downtime

24.May.08 – 14:43

due to some server change and some other problems this site was down for maybe a week or so.  It should be up again now.

## (Very) simple WPF PropertyGrid in 20 minutes

13.May.08 – 16:29

Everyone that has ever worked with the WinForms PropertyGrid will miss it in WPF.

Therefore i wrote this tiny turorial on how to write your own very basic PropertyGrid on top of WPF.

Disclaimer:This is not a ready to use fully-featured control for production use. It just shows in a very simple manner how to get Properties and their values from objects via reflection and show them using WPF and databinding.
It is by far not a replacement of commercial WPF PropertyGrids (e.g. MindScape WPF PropertyGrid), more a fast solution for minimal requirements.

This simple PropertyGrid will not contain special Editors for non trivial data types. For now we are confident with a simple TextBox for demonstration purposes.
We will see that because of the automatic conversion features of wpf , we’re easily able to edit not only strings, but also int’s, double’s, Color’s, SolidColorBrush’es and so on in a simple TextBox.

Our WPF PropertyGrid clone should look like this:

• TextBox for searching (filtering) properties. This is especially usefule if your classes contain lots of properties
• a panel (here StackPanel) that contains all the PropertyName/PropertyValue pairs (wrapped up in a Scrollviewer)
• TextBox for descriptions that we obtain from the System.ComponentModel.DescriptionAttribute-Attribute of the property selected

First we want to realize the simple structure shown above in XAML to get started.
After short time this may look like this:

Next we reate a UserControl as a Wrapper for our Properties. This just contains a TextBlock (for the property name) and a TextBox (for the property value) bound to properties that we defined in our code-behind file.

Now where the actual work is done:

foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value)){

if (!property.IsBrowsable) continue; //not browsable. ignore

PropertyItem currentProperty = new PropertyItem();
currentProperty.PropertyName = property.Name;
Binding b = new Binding(property.Name);
b.Source = selectedObject;
//OneWay Binding if readonly, twoway else
b.Mode = property.IsReadOnly ? BindingMode.OneWay : BindingMode.TwoWay;

currentProperty.SetBinding(PropertyItem.PropertyValueProperty, b);
currentProperty.OnActive += new EventHandler(currentProperty_OnActive);

foreach (Attribute attribute in property.Attributes)	//check attributes
{
if (attribute.GetType() == typeof(DescriptionAttribute)){ //description to show in description textbox
currentProperty.PropertyDescription = ((DescriptionAttribute)attribute).Description;
}
if (attribute.GetType() == typeof(CategoryAttribute)) {  //categories known from winforms pg.not implemented
currentProperty.PropertyCategory = ((CategoryAttribute)attribute).Category;
}
}

}


That’s it! Well, what happened here?
We iterate over all properties the object, we set as SelectedObject, contains. If it’s marked as non-Browsable (System.ComponentModel.BrowsableAttribute), we’ll just skip it, otherwise we create a PropertyItem, set its name and create a Binding to connect the PropertyItem’s PropertyValue-property with the value of the actual property from SelectedObject.

And before we add the PropertyItem to our Panel, we check the attributes of the source property (e.g. to get the description from the DescriptionAttribute or the get the corresponding category from the CategoryAttribute, which is not processed for simplicity in this demo).

When we now try to set some object to our PropertyGrid’s SelectedObject-property (in this case a dummy class containing several properties, including string, int, double, color, SolidColorBrush and a property marked with Browsable(false)) it should look like this:

In the screeshot above you can see different data types in their string representation. You don’t have to care about converting them back manually to their actual type as WPF’s Binding-Helpers do everything for you (and will throw Exceptions if the string-format for your type is wrong).

At last we add some Style to our PropertyGrid and received something like this:

To use the (very) simple PropertyGrid, just add a reference to PropertyGridDemo.dll, add the namespace in XAML to your window like this :








at last you have to provide some object (that contains some properties) to the SelectedObject property:

//...
this.propertyGrid.SelectedObject = myCustomObject;
//...


## NHibernate.QueryException: unexpected token: as [from mytable as m…

5.May.08 – 8:58

Today i encountered a strange behaviour with NHibernate. The error message in the headline was kinda confusing. I spent some time on google and everything i found was that my mapping is probably wrong or contains some bugs though i knew my mapping was definitely correct.

Some time later i found out what made this error appear. When you have a lot of entities and therefore a huge mapping, it can take quite a long time to process your hbm file. When you now want to access some of your entities from another thread as the main thread via NHibernate, but NHibernate still has not finished processing your mapping, then you’ll also get the error stated above.This will remain as long as you use the same session.

Maybe this can save some other guy’s time

## WCF and Streaming data made easy

3.May.08 – 8:47

Wcf is great when it comes to message exchange. But Wcf even contains functionality when you want to stream data.

This is especially useful if you want to transmit a huge amount of data (think about the maxBufferSize option in Wcf configuration) or you want your clients to start processing data before the Wcf operation call has finished.

Using Wcf for streaming data is incredibly easy. Let’s look at a small example. We define our ServiceContract in the same way we are used to ist except the fact that we can just return a System.IO.Stream (or inherited) object to our clients:

[ServiceContract]
public interface IStreamService
{
[OperationContract]
Stream GetData(string fileName);
}


We now want to define a service that just takes a filename as an argument and returns the data the file contains in a stream. Therefore our implementation of IStreamService is quite easy too:

  public class StreamService : IStreamService
{
public Stream GetData(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open)
return fs;
}
}


That’s everything we have to do on the service side (exception configuration). When you want to use streaming, be sure to use one of the following bindings:

• BasicHttpBinding
• NetTcpBinding
• NetNamedPipeBinding

These bindings expose a Property called “TransferMode” where you can specify how you want to transmit your data. This could be either “Buffered” (default) or “Streamed” (or even StreamedResponse/StreamedRequest if you want to stream just in one direction).

Next just add a service reference to your client (within visual studio).You way also want to set the maxReceivedMessageSize property of your binding to a value high enough to contain your whole stream data, as everything transmitted via your stream is regarded as one huge message. But you can leave maxBufferSize to its default (64k bytes) as this indicates only the amout that is buffered before it gets processed.

Then we can just use the stream as we did years ago :

StreamDemo.StreamServiceClient client = new WcfStreamDemoClient.StreamDemo.StreamServiceClient();
Stream str = client.GetData(@"c:\path\to\myfile.dat");
FileStream fs = new FileStream(@"c:\wcf\transmitted\copy.dat", FileMode.Create);

int b,i=0;
do
{
fs.WriteByte((byte)b); //write byte to local file
i++;
} while (b != -1);
str.Close();
fs.Close();


That’s it!
I can imagine a lot of distributed applications where this could be really useful. Maybe this micro tutorial can be useful too

## WPF DataBinding and Value Formatting for fun and profit

25.April.08 – 8:38

WPF offers great functionality when it comes to DataBinding. You can e.g. set a List of Customer-Objects as DataContext on a ListView and don’t have to care about the rest.The following example shows a List of Customer’s bound to a ListView:

But what if you want to display some Properties of your objects in another format (i.e. something other that ToString() returns) ? You can either override ToString() or try to use another (imho more elegant) way.
Therefore WPF offers an Interface called IValueConverter

public interface IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture);
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
}


When implementing this interface in your own class, you can probably do everything you can imagine with the values you try to format. You can e.g. display the birthdate instead of its (normal) DateTime representation as Base64-string (this has no real use, it’s just an example of how far you can go). Therefore we create the following converter:

public class Base64Converter : IValueConverter
{
#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToBase64String(Encoding.ASCII.GetBytes(value.ToString()));
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Encoding.ASCII.GetString(System.Convert.FromBase64String(value.ToString()));
}

#endregion
}


Next we have to add our Namespace to the Window:

<Window x:Class="CustomValueConverter:Window1"
. . .
xmlns:converters="clr-namespace:CustomValueConverter.Converter">


In the next step we create our Converter in our Window’s Resources:

. . .
<Window.Resources>
<converter:Base64Converter x:Key="base64"/>
</Window.Resources>
. . .


And from now on we can use our Converter everywhere we use DataBinding. For example:

. . .
<TextBlock Text="{Binding Path=Birthday,Converter={StaticResource base64}}"/>
. . .


would give the following result:

You can also pass parameters directly from XAML to a class implementing IValueConverter. This could be useful if you want to e.g. display some DateTime values in your own format.
Therefore we change our Convert()-method in the following way:


public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((DateTime)value).ToString((string)parameter);
}


Now the DateTime value will be formatted corresponding to our format string we supply as a parameter from XAML. We can declare our parameters like this :

<TextBlock Text="{Binding Path=Birthday,
Converter={StaticResource parameterized},
ConverterParameter='dd@MM@yyyy'}"/>


what gives us the following result

With ValueConverters you can transform your objects to any representation you want. You’re only limited by your imagination.
The ConvertBack() method of IValueConverter is needed to convert the values from Convert() back to its original representation.
This is necessary especially if you bind some values to TextBoxes (or other value-changing controls) and don’t want your user to use the original representation of your object’s values.