Recently I created a framework for translating JSON requests from a REST API to entities sent to the database. For simple objects, it was very easy, just create an SQL parameter for each property. However, for complex objects - having other objects as properties - this was not a solution. So I used a DataContractSerializer to transform the object to XML, send it as an XML SQL parameter and get the values from it in the stored procedures. Then I noticed date time inconsistencies between the two approaches. What was going on?

Let's start with the code. The DateTime object created from the JSON is a date and time value with a timezone, like 16:00 UTC+1. That is 15:00 in universal time. One you send it as a parameter for a stored procedure, the value received by the stored procedure is 16:00 (the server has the same timezone). In SQL Server, DATETIME and DATETIME2 types don't store timezone information. However, when sent through XML, the value looks like this: 2015-03-09T16:00:0.0000000+01:00. Using SELECT [Time] = T.Item.value('@Time','DATETIME2') FROM @Xml.nodes('//Location/SDO') as T(Item), the value returned is 15:00! You get 16:00+01 if you translate to DATETIMEOFFSET.

So let's recap: When you send a DateTime with timezone offset as an SQL parameter, the value reaching the SQL server is the local time. When you extract a textual value with timezone offset from an XML into a DATETIME, using the .value method, the value you get back is basically the Universal Time.

Solutions? Well, if you are going to use DateTime, you might as well consider that servers and devices are not always in the same timezone. Always translating values to universal time might be a good idea. Another solution is to extract from XML to a DATETIMEOFFSET type, which holds both the datetime and the timezone offset. Converting that value to DATETIME or DATETIME2 removes the timezone (Warning: it does NOT give the local time, unless you are in the same zone as the timezone in the datetimeoffset value).

and has 12 comments
I wanted to take an arbitrary XML format and turn it into C# classes. I even considered for a while to write my own IXmlSerializable implementation of the classes, but quickly gave up because of their large number and heavy imbrication. Before we proceed you should know that there are several ways in which to turn XML into C# classes. Here is a short list (google it to learn more):
  • In Visual Studio 2012, all you have to do is copy the XML, then go to Edit -> Paste Special -> Paste XML as classes. There is an option for pasting JSON there as well.
  • There is the xsd.exe option. This is usually shipped with the Windows SDK and you have to either add the folder to the PATH environment variable so that the utility works everywhere, or use the complete path (which depends on which version of SDK you have).
  • xsd2Code is an addon for Visual Studio which gives you an extra menu option when you right click an .xsd file in the Solution Explorer to transform it to classes
  • Other zillion custom made tools that transform the XML into whatever

Anyway, the way to turn this XML into classes manually (since I didn't like the output of any of the tools above and some were even crashing) is this:
  • Create a class that is decorated with the XmlRoot attribute. If the root element has a namespace, don't forget to specify the namespace as well. Example:
    [XmlRoot(ElementName = "RootElement", Namespace = "http://www.somesite.org/2005/someSchema", IsNullable = false)]
  • For each descendant element you create a class. You add a get/set property to the parent element class, then you decorate it with the XmlElement (or XmlAttribute, or XmlText, etc). Specify the ElementName as the exact name of the element in the source XML and the Namespace url if it is different from the namespace of the document root. Example:
    [XmlElement(ElementName = "Integer", Namespace = "http://www.somesite.org/2005/differentSchemaThanRoot")]
  • If there are supposed to be more children elements of the same type, just set the type of the property to an array or a List of the class type representing one element
  • Create an instance of an XmlSerializer using the type of the root element class as a parameter. Example:
    var serializer = new XmlSerializer(typeof(RootElementEntity));
  • Create an XmlSerializerNamespaces instance and add all the namespaces in the document to it. Example:
    var ns = new XmlSerializerNamespaces(); ns.Add("ss", "http://www.somesite.org/2005/someSchema"); ns.Add("ds", "http://www.somesite.org/2005/differentSchemaThanRoot");
  • Use the namespaces instance to serialize the class. Example: serializer.Serialize(stream, instance, ns);

The above technique serializes a RootElementEntity instance to something similar to:
<ss:RootElement xmlns:ss="http://www.somesite.org/2005/someSchema" xmlns:ds="http://www.somesite.org/2005/differentSchemaThanRoot">
<ds:Integer>10</ds:Integer>
</ss:RootElement>

Now, everything is almost good. The only problem I met doing this was trying to deserialize an XML containing xsi:type attributes. An exception of type InvalidOperationException was thrown with the message "The specified type was not recognized: name='TheType', namespace='http://www.somesite.org/2005/someschema', at " and then the XML element that caused the exception. (Note that this is an internal exception of the first InvalidOperationException thrown that just says there was an error in the XML)

I finally found the solution, even if it is not the most intuitive. You need to create a type that inherits from the type you want associated to the element. Then you need to decorate it (and the original element) with an XmlRoot attribute specifying the namespace (even if the namespace is the same as the one of the document root element). And then you need to decorate the base type with the XmlInclude attribute. Here is an example.

The XML:

<ss:RootElement xmlns:ss="http://www.somesite.org/2005/someSchema" xmlns:ds="http://www.somesite.org/2005/differentSchemaThanRoot">
<ds:Integer>10</ds:Integer>
<ss:MyType xsi:type="ss:TheType">10</ss:MyType>
</ss:RootElement>

You need to create the class for MyType then inherit TheType from it:
[XmlRoot(Namespace="http://www.somesite.org/2005/someSchema")]
[XmlInclude(typeof(TheType))]
public class MyTypeEntity {}

[XmlRoot(Namespace="http://www.somesite.org/2005/someSchema")]
public class TheType: MyTypeEntity {}
Removing any of these attributes makes the deserialization fail.

Hope this helps somebody.

I was trying to add some content to Infragistics WPF controls and some of the images used were blurry. I have tried setting SnapToDevicePixels, but to no visible effect. I did stumble upon a property in the Infragistics.Windows.Utilities class, called SnapElementToDevicePixels. I didn't know what it does, but I tried it anyway. Voila! The image got crisp and clear.

This is the comment from the property in the Infragistics WPF sources:

/// <summary>
/// SnapElementToDevicePixels Attached Dependency Property
/// </summary>
/// <remarks>
/// <p class="body">The SnapsElementToDevicePixels is meant to be used on elements such as an Image that
/// does not currently support SnapsToDevicePixels.</p>
/// <p class="note"><b>Note:</b> The RenderTransform of the element is used so you should not set the RenderTransform
/// on the same element on which you are setting SnapElementToDevicePixels to true. You may set the RenderTransform on
/// an ancestor element. Also, you should not set this property on an element that is an ancestor of one or more
/// elements that have this property set to true. In such a case the results are undefined since the child element's
/// RenderTransform could be calculated before that of the ancestor element. Since this property should be set on
/// discrete elements such as an Image, this scenario should not be required.</p>/// </remarks>

In order to use it, make sure you load the Infragistics.Windows namespace in your XAML:

xmlns:Windows="clr-namespace:Infragistics.Windows;assembly=Infragistics3.Wpf.v9.2"

and then set the Windows:Utilities.SnapElementToDevicePixels property to True.

I was trying to build a control that has a border around it only in design mode. You do have the static class DesignerProperties and its method GetIsInDesignMode(DependencyObject element) to detect that in code, and you do have a property DesignMode on Components, but one that is not a Dependency property. How can you detect DesignMode in XAML?

Well, looking at the source for DesignerProperties I noticed that it does two things:
  1. Register an attached property called IsInDesignMode to itself
  2. Get/Set that dependency property in the GetIsInDesignMode/SetIsInDesignMode methods


More on how to create attached properties here: How to Create an Attached Property and here: Showing Attached Properties in the Cider/Visual Studio WPF Designer.

So, all I had to do is use a trigger on the IsInDesignMode attached property. For that, these steps must be followed:
  • Add the ComponentModel namespace to your XAML: xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=PresentationFramework"
  • Use ComponentModel:DesignerProperties.IsInDesignMode in your Triggers as the Property
  • Use (ComponentModel:DesignerProperties.IsInDesignMode) in your DataTriggers as the Path of Bindings


Please take notice of the brackets around the property when used in Binding Path mode. It is the only way to use attached properties there. It also gives you more advanced intellisense and warnings and a faster type resolution at runtime.

Another thing to take into consideration is that (at least in Silverlight) this mechanism is buggy, at least that's what I found in this blog post.

In order to customize controls the way you want, you can either use a DataTemplate, different specific ControlTemplate properties, use the properties that the controls publish, but in the end, to get it right, you must actually change the ControlTemplate of the control itself. The best practice is to use an external resource dictionary that contains a style that changes various properties and also, if needed, the ControlTemplate.

The problem there is that there is no way to partially change the control template. I mean, yeah, I could think of a few ways, but in the end is the same thing: you need to replace the control template completely. And now you have two ... err.. actually three problems.

First, there are ways of getting the default control template, with all the functionality (we are talking about one, two or even more pages of XAML) and change only what you want. It's not trivial, but it can be done, either by copying it from the published sources (like the Windows SDK or the Expression Blend SystemThemes folder) or by using a utility like ShowMeTheTemplate.

Second, there is the issue of control templates differing depending on the Windows theme. And therefore one must either accept that the application will only look one way for every theme and Windows operating system, or provide templates for all the themes available (there are 6 defaults and a generic fallback theme).

Now, there are many tutorials about how to do that, basically just create a Themes folder, change AssemblyInfo.cs to

[assembly: ThemeInfo(
ResourceDictionaryLocation.SourceAssembly, //where theme specific resource dictionaries are located
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
)]

, copy the xaml files (with certain names) there and change them as you see fit. There is a catch, though! This will only work on your custom controls. Default controls already have a template in the operating system theme, so you need to do one extra thing in order to overwrite them, and that is to write the following in the a parent control Resources block:

<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="{ThemeDictionary [LibraryOrApplicationNamespace]}" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

otherwise it will NOT work.

You can get the same result by adding this to the static constructor of the control, provided you have access to the sources:

DefaultStyleKeyProperty.OverrideMetadata(typeof([MyControlClass]), new FrameworkPropertyMetadata(typeof(MyControlClass)));


One thing you also need to be aware of is that Visual Studio caches the themes. If you change them, especially if you do it outside visual Studio, you need to force a Rebuild of the project.

I was trying to bind a property to the value of a property of the parent UserControl in WPF. When you google for it you get something pretty interesting: give a name to the user control right inside the user control XAML, then reference it with ElementName.

What I found after hours of torment was that this doesn't always work. I guess it only works up to the first item container in the logical tree and then stops. So that when I tried to use a property ImageSource of the user control in a Menu.Icon it failed!

My solution looks pretty ugly, but it does work in all cases!


<Image Source="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Controls:MyUserControl}},Path=MainMenuImageSource}"
Width="16" Height="16"></Image>



In other words: find the ancestor of the type of your user control and use it as the RelativeSource of the binding.

Update: When I had more time to thing I realised that a MultiBinding needs a Converter, but a simple Binding also has a Converter and I guess that is what I should have used. I will update the post when I get to work on Monday.

I started to build the prototype of a control and I hit a wall where WPF binding was concerned.

For example: I wanted to bind my control to a collection of Items which could be Groups, Sections or Items. Groups have more Sections and Items. Sections have more Items, but they should be displayed as a non clickable section with its Item children under it. Everything in a menu.

At first I used an XML data source, which allowed me to use XPath to select all the Items in a Group, all the Sections and all the Items in the Section like this: XPath="Item|Section|Section/Item". However, when switching to an object schema, the normal Path syntax was too restrictive to allow for this. Even with a MultiBinding, I could find no Path syntax in which to select children of a certain type and their children. However! MultiBinding uses a Converter to usually merge two or more collections together. I used it to get the children and their own children! So forget XAML in this case, just use code:

public class SectionHeaderConverter:IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
List<ToolBarItem> list = new List<ToolBarItem>();
foreach (IEnumerable<ToolBarItem> collection in values)
{
foreach (ToolBarItem element in collection)
{
list.Add(element);
var toolBarSectionHeader = element as ToolBarSectionHeader;
if (toolBarSectionHeader != null)
{
foreach (var item in toolBarSectionHeader.Items)
{
list.Add(item);
}
}
}
}
return list;
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}


This converter was then used in the XAML as the Converter for the MultiBinding:

<MultiBinding Converter="{StaticResource SectionHeaderConverter}">
<Binding Path="Items"/>
</MultiBinding>


Now, that fixed one issue, but how can I now make the different MenuItems to
  1. have different looks depending on type/attributes
  2. behave differently depending on type/attributes
but selectively, keeping the default style and datatemplate in other cases? At first, when I used the XML datasource, having an XPath to select the type of the node based on its name was not an option because the XAML XPath implementation does not allow for XPath functions! so I used a StyleSelector for the difference between Sections (unclickable, spanning the whole width of the menu strip) and normal menu items, then a DataTemplateSelector for the difference between Groups and Items. It is also here where I bound the MenuItem Click RoutedEventHandler to an EventHandler in the datasource item class.


<Menu
ItemsSource="{Binding ElementName=ToolBarCurrent,Path=Items}"
ItemContainerStyleSelector="{StaticResource MenuItemContainerStyleSelector}"
ItemTemplateSelector="{StaticResource MenuItemTemplateStyleSelector}"
></Menu>


I don't know if that is the best way to do it, but suddenly it was like a fog lifted from my eyes and instead of that dreaded XAML I had something I know and understand used in a simple fashion. It is beyond the scope of this post to show how specific implementations of the selectors above work, but there are two issues that I had to fix:
  • Since the styles were resources defined in the resources of the containing Grid, I had to find a way to reference the Grid object from the StyleSelector:
    This is done using the
    ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(container);
    var style = (Style) ic.FindResource("SectionStyle");
  • Since the data templates were resources defined in the resources of the containing Grid, I had to find a way to reference the Grid object from the DataTemplateSelector:
    this seems to be the same problem, but actually the solution was quite different, I used the FindVisualParent helper method like this:
    var ic = Helper.FindVisualParent<Grid>(container);
    The source for it is underneath.


public static TParentItem FindVisualParent<TParentItem>(DependencyObject obj)
where TParentItem : DependencyObject
{
DependencyObject current = obj;
while (current != null)
{
var tCurrent = current as TParentItem;
if (tCurrent != null)
return tCurrent;
current = VisualTreeHelper.GetParent(current);
}
return null;
}
.

Also, regarding this particular task, I found a way to display MenuItems grouped by a property in this blog post and at first I used this solution only to find out that this type of grouping only applies to flat DataTemplates. And while it seemed to be working in my first attempts with a HierarchicalDataTemplate, the grouping was only applied to the first level and not to the next.

My conclusion: as in many "magical" technologies, the complexity of a lot of problems is beyond the ability of the technology designers to predict. Therefore the only (and often enough, the best) option is to use your own code.

In Windows Presentation Foundation all resources (like ImageSources or Resource packs) are relative to the namespace of the control. So if you have a folder Images that holds your application icons and you use (in the application XAML) an ImageSource of "Images/MyImage.png" it will work. But as soon as the XAML is moved somewhere in a UserControl in the Controls namespace of a library, the ImageSource becomes invalid. It would only work as "../Images/MyImage.png" or "/Images/MyImage.png", even if the Controls namespace is not a folder and the control is in a library, not in the application that runs it!

This is part of a larger idea, that is Pack URIs. Pack URIs are used by the Open Packaging Conventions and are of the format pack://authority/path.


Long story short, authority can be application:/// or siteoforigin:///. The slashes at the end get escaped as commas in a pack URI so you get to have stuff like pack://application:,,,/ResourceFile.xaml. The path is more tricky: AssemblyShortName[;Version][;PublicKey];component/Path.
Attention at the component keyword. It is NOT a folder, but a keyword that must be there when referencing resources from an external library.

Example: I have the Resources/Images/image.png in a library and I want to use it in the XAML that is in the same library. The image source would be something like pack://application:,,,/libraryNameSpace;component/Resources/Images/image.png. Again look out for the component keyword.

Just yesterday I was struggling with the same issue, only this facette of it seems like a completely different bug. You see, I added this control to the library and everything worked fine EXCEPT the visual designer. It is known that the Visual Studio 2008 WPF designer is not the best possible piece of software, but this was one of those errors you don't know where it comes from.

So, let's take it from the beginning. I had something like
<HierarchicalDataTemplate DataType="{x:Type Code:League}" ItemsSource="{Binding Path=Divisions}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
Somewhere in the Window declaration there was a
xmlns:Code="clr-namespace:MyControls.Desktop.Code"
which is the namespace of the test application for the control in the library.
The application worked, but in the designer an error like "Type reference cannot find public type named 'League'.".

Many people gave the solution to remove the name of the assembly in the namespace declaration. So If I had something like "clr-namespace:MyControls.Desktop.Code;assembly=MyControls" and it was the current assembly, I should just remove it. Well, it wasn't the case here, was it?

In the end I found the solution here. You see, even if the assembly name was not specified, it was implied! And even if it was an application, not a library, it still was an assembly. And the Application name was... something with spaces in it!!

So, again, just go to the Project properties and change the Assembly name to not have spaces!

Two short points I'd like to make about working with WPF in Visual Studio 2008:
  1. In order to see Binding errors, you need to open the Output window while the app is running, since any binding error is silently dropped, but displayed there. There is also a Binding property called FallbackValue which you can set to "ERRRROOOORRR!!" :)
  2. XML files are seldom unformatted or having weird spaces and extra lines. Yet, there is not context menu for XML editors like the Format in ASP.Net as*x files. However, the option (and many more) is available in the Edit -> Advanced menu.
    • Format entire document: Ctrl+K, Ctrl+D
    • Format selection: Ctrl+K, Ctrl+F
  3. Unfortunately, some of the useful commands are just set up in the Options menu, like what to do with extra lines. So go to Tools -> Options -> Text Editor -> XAML -> Formatting.
    • To set it so that the XML is auto formatted at completion of start/end tag or when pasting code, go to the General option
    • To get rid of extra empty lines, go to the Spacing option and choose either Collapse multiple empty lines in content to a single line or Remove empty lines in content

It can't be done. Maybe in XAML 2009. In the old one, it just fails. I am using ReSharper and it automatically finds the controls in XAML in the loaded libraries and creates the appropriate namespace. For a library called "My Controls" it adds an "assembly=My Controls" at the end of the clr-namespace and the compilation fails with "Unknown build error".

The only solution I could find for this is to rename the library so that it doesn't have spaces in it. In my case the library was actually another project and I changed the name in the project properties to have underscore rather than space.

and has 0 comments
While working on RegexConverter I've started learning things about XML. I disliked it before, but now... I loathe it completely. It feels like the XML people are from another planet and I have to twist my brain at straight angles just to understand what they meant.

One of the problems I met was "how to declare in an XML schema a unique constraint/index on the entire document when there are nested elements of the same type". In other words, something like this:
<regex>
<group index="1">
<group index="2">
</group>
<group index="3">
</group>
</group>


Bottom line:
  1. Use the declared namespace
  2. Declare the index in the root element
  3. Use the name of the nested element (in my case group) in the selector
  4. Use the one or more levels deep selector (.//)
  5. Use the declared namespace AGAIN.
.

Concrete example:
<xs:element name="regex" type="regexType">
<xs:unique name="uniqueIndex">
<xs:selector xpath="mstns:group|.//mstns:group"></xs:selector>
<xs:field xpath="@index"></xs:field>
</xs:unique>
</xs:element>


I tried to solve this for two hours only to find the solution was this idiotic. Neither one of "group","mstns:group","mstns:group|.//group" work. The only one is "mstns:group|.//mstns:group".

Grrrr...