MongoDB and DotNet (C#)


MongoDB University has opened a course to learn how to use MongoDB in C#. I signed up for these classes and I’ll like to share my notes about it.



Tags: , , , , ,

How embed fonts in Windows Phone 8 using a WebBrowser control


I hope I will be sharing some ideas from my last project. This in particular was difficult.

The problem

I have a font I want to embed into my Windows Phone Application, and I want to use in a WebBrowser Control. I have managed to embed the font and use it with standard textblocks control, however I haven’t get it working with the WebBrowser control.

The Solution

Using Data Url Scheme for embedding the font ( ). Then let the WebBrowser control to consume the font.

First things I learned it’s that a Data Url can contains basically data (e.g.images, fonts, more files. it’s really handy). Moreover, I learned that CSS can consume this data, which makes a good option to embed the font and use it off line. There may be few bumps, such as using Base64 encoding, but one we get the rhythm it won’t hurt more.

1) In your window phone project select add the font file. Here is a remark, make sure the file format is compatible with Windows Phone (TTF files) or the Windows Phone Web Browser (WOFF). TTF may require some work to get them working , for example enabling the flag for allow the file to be embedded, or making sure that its internal file structure is compatible with WP platform.

2) When embedding the file, make sure that the file properties are set: Build Action to Content and Copy to Output Directory to Copy if newer.

3) Prepare some HTML for the setting up the font. In my project sample, I’ll be using Navigate to String method and to keep HTML code apart from my C# code, I’ll be loading an external file from the XAP package, and applying some text replacements with Regular Expressions.

4) In out sample check MainPage.xaml.cs to see how the FileManager to apply the custom font.

I haven’t tried, but I think this approach could be extended to inject a custom font to an external page. Here is the output:


The code sample is at

I hope you could find this handy,



Leave a comment

Posted by on 2014/03/17 in Uncategorized


Tags: , , , ,

After moving some files my Windows Phone Project Throws a XamlParseException

I am not sure if this is an known issue for Microsoft, but at least I am aware of this. However this is the first time I am gonna document it. Since it can be very frustrating

The Problem

I want to reorganize the files in my Windows Phone Project in order to follow our implementation of MVVM, moreover we have decided that resx file will live in their own assembly project. However, once I move the Resource file to an external assembly the application just thrown an XamlParseException even though the reference in XAML is totally correct.

XamlParseExceptions may be thrown by other reasons. It is important to realize that I knew I moved the RESX file to a different assembly and before that everything was working. Certainly I updated the reference to the new assembly, and the exception was still being thrown. That is why this is a tricky issue.

The solution

It took some time to me to noticed, but somehow the project that contains the RESX file cannot contain a dot (.) character in its assembly name. If it happens then XAML parse will throw a XamlParserException even though the reference to the assembly is correct. The error message may contain something like this:

System.Windows.Markup.XamlParseException occurred
  Message=Unknown parser error: Scanner 2147500037. [Line: 10 Position: 126]
       at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
       at MyApp.App.InitializeComponent()
       at MyApp.App..ctor()

Taking a look at the location where I was loading the Resource it was this:


    <!--Application Resources-->
        <local:LocalizedStrings xmlns:local="clr-namespace:MyApp;assembly=MyApp.WindowsPhone8.Resources" x:Key="LocalizedStrings"/>

        <!--Required object that handles lifetime events for the application-->
            Launching="Application_Launching" Closing="Application_Closing"
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>


The line one of my projects generates an assembly named: ‘MyApp.WindowsPhone8.Resources’, in order to resolve the issue I only have to update the generated assembly name to be ‘MyApp_WindowsPhone8_Resources’ and then update the proper reference in the XAML. For example:

        <local:LocalizedStrings xmlns:local="clr-namespace:MyApp;assembly=MyApp_WindowsPhone8_Resources" x:Key="LocalizedStrings"/>

After performing this change your app should work normally.


Tags: , , , , , , , , , , , , ,


Pivot ( or Panorama ) Index Indicator


The Problem:

Creating a pivot (or panorama) indicator could be a challenging task. The control should:

  • Indicate in which item of the collection you are looking at
  • Let you tap on a given item and navigate in the panorama to that given item
  • Let you customize the look and feel of the items.

The Solution: A Second thought

Sounds like the perfect scenario for a custom control, and in some of the cases it is. However, after some minutes thinking about this idea, I realized that the ListBox supports most of these requirements but only one pending task: it has to interact properly with the Panorama or Pivot.  Thus, the current solution uses a ListBox (Custom Styles and Templates) for modifying the look and file, and prepares a behavior (more specifically a TargetedTriggeredAction<T1,T2> ) for letting the ListBox interact with a index based collection (e.g. Pivot, Panorama, ListBox, etc … ).

A behavior …  (What’s that?)

Well with XAML a bunch of new concepts arrived to .NET development world. One in particular which is very useful is a behavior . You can think about a behavior like a encapsulated functionality that can be reused on different context under the same type of items.  The most popular behavior i guess it is EventToCommand which can be applied to any FrameworkElement and it maps the Loaded Event to a Command when implementing a View Model.

Thus, since We have a ListBox already in place, we only want it to behave synchronized with a Pivot or Panorama. Thus, the external control will be a parameter for our behavior.

    public class SetSelectedItemAction : TargetedTriggerAction
        private Selector _selector;

        protected override void OnAttached()

            _selector = AssociatedObject as Selector;
            if (_selector == null)

        protected override void OnDetaching()
            if (_selector == null)
            _selector = null;

        protected override void Invoke(object parameter)
            if (_selector == null)

            if (Target is Panorama)
                InvokeOnPanorama(Target as Panorama);
            if (Target is Pivot)
                InvokeOnPivot(Target as Pivot);
            if (Target is Selector)
                InvokeOnSelector(Target as Selector);

        private void InvokeOnSelector(Selector selector)
            if (selector == null)
            selector.SelectedIndex = _selector.SelectedIndex;

        private void InvokeOnPivot(Pivot pivot)
            if (pivot == null)
            pivot.SelectedIndex = _selector.SelectedIndex;

        private void InvokeOnPanorama(Panorama panorama)
            if (panorama == null)
            panorama.DefaultItem = panorama.Items[_selector.SelectedIndex];

The idea is that you should be able to sync other elements by just dropping this behavior on a ListBox and setting up few properties, for example:

			HorizontalAlignment="Stretch" Margin="12" VerticalAlignment="Top"
            SelectedIndex="{Binding SelectedIndex,ElementName=panorama,Mode=TwoWay}"
            ItemsSource="{Binding PanoramaItems}"
            ItemsPanel="{StaticResource HorizontalPanelTemplate}"
            ItemContainerStyle="{StaticResource ListBoxItemStyle1}"
            ItemTemplate="{StaticResource IndexIndicatorDataTemplate}"
                <i:EventTrigger EventName="SelectionChanged">
                    <local:SetSelectedItemAction TargetObject="{Binding ElementName=panorama}"/>

The behaviors can take more responsibility other than keep sync the selected item in one way. However my design decision was to use other mechanisms for keeping sync the indexes. (e.g. you could appreciate a TwoWay binding using SelectedIndex Property of the Target Pivot or Panorama).

Also, the ListBox has bound a list of items (empty items) just for being able to generate as much items as the Panorama has. This is other logic that may be moved to the behavior (however in my two previous attempts it didn’t work that well).

Here is the code sample, of this simple behavior and how ti keeps sync with the Panorama.

The following screenshot shows an indicator in the top/left corner where you can see the current tab of the Panorama that is being shown. Moreover, the user can tap on a given item to get directly to that selected tab.




Tags: , , , , , , , , , ,

Custom Configuration files in .NET


I would like to share some ideas about how to deal with configuration files on .NET. I am sure that there should be many options for implementing configuration files. Some are more likely to better than others and others may depend on the platform (e.g. mobile, desktop, cloud, etc..)  In particular I’ll explain an approach that should be working for your Web Application and for your Desktop application.

The problem:

We want to quickly create a configuration file, since we foresee that our application will have a good amount of settings.


I’ll take advantage of the default .NET mechanism for configuration files. It’s plenty flexible and quite extensible. The major drawback is that you’ll have to write code, and sometimes a not-so-easy code. Alternatively you can relay on the existent section handlers, and try to use them when possible.

A brief talk about configuration files

.NET configuration files supports hierarchies and they are extensible. Almost all the cases with defaults is fairly enough, for creating custom sections there I will be explaining three approaches, but certainly there are more. The decision of which approach to take it will depend of how much time you have and also if the team has the will and chance for installing at least the Configuration Section Designer. 

1) Create Custom Section Handler with Code Snippets

This is the simplest one, it’s basically get code snippets of how to create sections for the SectionHandler class. Then you are more likely to have many property of similar times (probably primitive types) but it can safe time for producing the class and understand it. I won’t be providing samples for this.

2) Using the Custom Section Designer from CodePlex at

This is my favorite, but unfortunately it demands that you will have to install a Visual Studio Extension for opening configuration section projects. The best of this approach is that you can get:

  • XSD validation + intelisense
  • XSD Documentation
  • Ease to modify content.
  • etc…

First get proper installer for the extension Then create a configuration section project (these projects outputs a dll), by conversion these projects end with “.Configuration” for example “MyApp.Configuration” will be dll project that loads the configuration section. In our sample it is provided a project called: ConfigurationFileSample.Configuration


The previous screenshot exemplifies a Section in which it has been defined a Element called Mappings, which is a collection of Mapping elements. By following the instructions at you will easily create this configuration. The magic arrive when you are typing these values into visual studio (or any XML editor that supports XSD validation property).

Once you are done designing your configuration file. You save and compile. If it success then add a configuration file to your main project, and also add a reference to the configuration file project. for referencing our custom section we do it into the configSections element. For example:

<!-- NOTE: In here a custom section is specified, this section has been created by writing code--></pre>

Visual studio will enable help toltips and XSD validation for you. As you can see in the following screenshot


For loading configuration files in code, after adding the reference to the dll, the app can use an static helper of simply use the GetSection method.

For example for loading the section using the default instance:

// NOTE: It is also possible to load the default custom section
Console.WriteLine("\nLoading default Minestrone thru singleton!");
var minestroneSection = Minestrone.MinestroneSection.Instance;

Or also you could load a specific section:

// NOTE: You could ask for a given custom section
Console.WriteLine("\nLoading Minestrone by manually specifying a section: minestroneSection");
var minestroneSection = ConfigurationManager.GetSection("minestroneSection") as Minestrone.MinestroneSection;

3) Using one of the build in Section Handlers
As I mentioned you also could you the built-in Sectionhandlers from .NET framework There is a list of them at the end of this page: (basically all the subclasses of System.Configuration.ConfigurationSection )

For example for referencing it into the configuration file:

    <!-- NOTE:This custom section uses .NET framework sections instead, see for a list of the classes available into the framework --></pre>

and for loading it from code:

// NOTE: Loads a custom section, but it uses a .NET built-in class
            Console.WriteLine("\nLoading a ApplicationSettings using a built-in .NET type. (more at ) ");
            var myConfigSection = ConfigurationManager.GetSection("myConfigSection") as System.Collections.Specialized.NameValueCollection;
            for (int appSettingIndex = 0; appSettingIndex < myConfigSection.Count; appSettingIndex++)
                Console.WriteLine(string.Format("Key:{0} Value:{1}", myConfigSection.AllKeys[appSettingIndex], myConfigSection[appSettingIndex]));
            Console.WriteLine("\n\n PRESS ANY KEY TO FINISH! ");

We are almost there, but WAIT!!!!

I know that at this time I haven’t shown how to specify section. Well basically because you can provide the details of the section inline into the same file or specifcying an external file using the configSource attribute (which is available for any custom section).

For example see how the minestroneSection is defined in an external file, and how myConfigSection  is written inline into the configuration file. There are advantages of each approach (e.g. when you want to apply XSLT transformations you may want to apply transformations to a simple file rather than a long and complex XML) o perhaps you may have a config file per environment (e.g. minestrone.debug.config…,)

<?xml version="1.0" encoding="utf-8" ?>
    <!-- NOTE: In here a custom section is specified, this section has been created by writing code-->
    <section name="minestroneSection" type="Minestrone.MinestroneSection, ConfigurationFileSample.Configuration, Version=, Culture=neutral, PublicKeyToken=null"/>

    <!-- NOTE:This custom section uses .NET framework sections instead, see for a list of the classes available into the framework -->
    <section name="myConfigSection" type="System.Configuration.AppSettingsSection, System.Configuration, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

    <add key ="ALPHA" value="1|1"/>
    <add key ="BETA" value="1|1"/>
    <add key ="GAMA" value="1|1"/>

  <!-- NOTE: Loading section from a external file-->
  <minestroneSection configSource="minestroneSection.config" />

    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />

I hope this is good enough for setting up quickly custom configuration files in your .NET projects.
The sample is at and please remember to install the Custom Section Designer if you want to take the option for more detailed configuration file.



Tags: , , , , ,

Previewing Microsoft Office Documents and PDF in WPF using a Preview Handler Host


I had recently to implement a mechanism for showing documents into a WPF application. The very first solution was to start a new process using the path of the selected file. The only condition for this to work it’s that the file extension should have been previously registered to be opened with an specific application. A drawback is that the document is shown by an external application that we are not able to handle (at all or at least easily).

Then the client decided showing documents by embedding them into the application. So, I started researching about how to display Portable documents, Word documents, Excel documents into a WPF application. Finally after some research I got to a nice solution which will display many documents formats with the only condition of having the proper software installed into the PC where the application is gonna run.

The Problem
Showing a office document (XLS, DOC, XLSX, DOCX) or portable document (PDF) into a WPF APP.

This is not a bullet proof solution, but it is kind extensible for brave developers. The relays on the installed Preview Handlers. For example for visualizing Microsoft Office documents you will have to have installed Microsoft Office in the computer where the application is going to run. It’s the same case for PDF files, where you need to have a Preview Handler installed.
Moreover, the technology of Preview Handler has been built using native code, in order to embedded into a WPF application the app will be hosting WinForm content, this introduces a different set of restrictions about the interaction of the control once it has been instantiated.

The Solution
Preview Handlers is a technology added into Windows Vista, and it’s meant to readonly quick preview of files. It’s available on Windows Explorer
Enabling Previews in Windows Vista Folders
The Microsoft article [1] about Preview Handlers has an utility application which lists the available preview handlers in your system. Moreover after some research, I found the first implementation in [2] which was using Windows Forms and C# for development. Finally I found a more elaborated solution from Coding4Fun [3]. Since this point the solution for WPF was straightforward because it was only matter of loading a WinForm contro into WPF by using Interop components.

1) Grab the code from project. To use the Preview Handler Host you will need only two projects.
/Preview Handlers/Source/VCS/PreviewHandlerFramework
/Preview Handlers/Source/VCS/PreviewHandlerHost

Compile them and the create a new WPF project. The codeplex project hasn’t been updated in awhile, thus you’re more likely to have to update the solution file to a new version of visual studio.

2) Add to your WPF application (or library) a reference to WindowsFormIntegration library. This will allow the application to host WinForm controls. Also add System.Windows.Forms since it will be required by the Preview Handler libraries.

3) The use the WindowsFormsHost tag to embed the PreviewHandlerHostControl as the follwing XAML shows:


            <C4F_DevKit_PreviewHandler_PreviewHandlerHost:PreviewHandlerHostControl x:Name="previewHandlerHostControlInstance" />

4) Finally our C# code that for our sample is quite simple. We just select a file and let the PreviewHandlerHost control do the work.

using System;
using System.Windows;

namespace PreviewHandlerWpfApplication
    public partial class MainWindow : Window
        public MainWindow()

        private void Button_Click(object sender, RoutedEventArgs e)
            var dlg = new Microsoft.Win32.OpenFileDialog();
            if (dlg.ShowDialog().Value)
                previewHandlerHostControlInstance.FilePath = dlg.FileName;

Here is an screenshot of my mighty document viewer:


Finally the code is available at GitHub Have fun!





Posted by on 2013/01/02 in .net, c#, microsoft, Uncategorized


Tags: , , ,

Adding a static reference into a unity configuration file


I’d like to talk about how you can set up your unity configuration file to resolve static references. This is handy depending of the context, for example you would like to register the Path Separator of the file system. This if you’re on unix-based system it’s more likely to be “/” and if you are on a Windows-based system it’s going to be “\”. Certainly you could use configuration files, for this purpose, this is just an alternative where you could let you application know about specific values without knowing they’re coming from, and you usually do this for test-ability.

For those who does not have enough patience, the source code is at

The problem

I’d like to set my Unity Container to take the value from a static field, so I do not have to write code to set up a the container in code and in the configuration file.


The Solution

Unity Container is very flexible and moreover extensible. It takes advantage of a pattern called “TypeConverter”, which basically it’s an specialized class which maps from one type to another. Particularly in our case we will be mapping from System.string value to any valid static value by using reflection.

Type converters are used along .NET framework, here is a quick guide of How to: Implement a Type Converter:

In our case, we will assume that we’re receiving a value of type string which follows the following format:


Then, we can reference static fields by using the following syntax:

Version@System.Environment, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089

The type converter class that does this work is the following:


using System;
using System.ComponentModel;
using System.Reflection;

namespace EntLibUnity.Extensions
    /// <summary>
    /// Converts an (formatted) string to a reference of a given static member.
    /// The string uses this format: {member}@{assemblyQualifiedName}
    /// For example:
    ///     Version@System.Environment, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089
    /// </summary>
    public class StringToStaticInstanceTypeConverter : TypeConverter
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            return (typeof(string) == sourceType) || base.CanConvertFrom(context, sourceType);

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
            string stringValue;
            if (value == null
                || (stringValue = value as string) == null
                || string.IsNullOrEmpty(stringValue)
                || !stringValue.Contains("@")
                return null;

            var stringParts = stringValue.Split('@');
            if (stringParts.Length != 2)
                return null;
            var propertyPath = stringParts[0];
            var propertyPathParts = propertyPath.Split('.');
            var assemblyQualifiedName = stringParts[1];
            // Gets the static member
            var currentClassType = Type.GetType(assemblyQualifiedName, true);
            var currentPropertyInfo = currentClassType.GetProperty(propertyPathParts[0],
                                                                 BindingFlags.Public | BindingFlags.Static |
            var currentPropertyValue = currentPropertyInfo.GetValue(null, null);
            // Loops into the path to get a value
            for (var i = 1; i < propertyPathParts.Length; i++)
                currentPropertyInfo = currentClassType.GetProperty(propertyPathParts[i]);
                currentPropertyValue = currentPropertyInfo.GetValue(currentPropertyValue, null);
            return currentPropertyValue ?? base.ConvertFrom(context, culture, value);

The second step is to configure our container to recognize the TypeConverter and use it when needed. This is simple, when we’re registering types in the configuration file we have the option of specifying a type converter as you can see in the following sample:

<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="">
  <!-- Using Design-Time Configuration: -->
  <!-- The Unity Configuration Schema: -->
  <!-- Specifying Types in the Configuration File>

  <!-- Setting an alias for our TypeConverter, to prevent using the full type reference -->
  <alias alias="StringToStaticInstanceTypeConverter" type="EntLibUnity.Extensions.StringToStaticInstanceTypeConverter, EntLibUnity.Extensions" />

  <alias alias="IVersionManager" type="EntLibUnity.Infrastructure.IVersionManager, EntLibUnity.UnitySample.ConsoleApp" />
  <alias alias="VersionManager" type="EntLibUnity.UnitySample.VersionManager, EntLibUnity.UnitySample.ConsoleApp" />

  <!-- Default (unnamed) container-->
    <register type="IVersionManager" mapTo="VersionManager">
        <param name="version">
          <!-- In this case we use the expanded version of Param and set the proper typeConverter attribute-->
          <value value="Version@System.Environment, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" typeConverter="StringToStaticInstanceTypeConverter" />


Simple ;-). Finally we only have to use our container as we usually use it. In my case I’ve some extensions to load and configure the container, you can check them by downloading the source code.
Here is the final code of our main application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using EntLibUnity.Extensions;
using EntLibUnity.Infrastructure;

namespace EntLibUnity.UnitySample.ConsoleApp
    class Program
        private static IUnityContainer container;

        static void Main(string[] args)
            container =
                new UnityContainer()

            var versionManager = container.Resolve<IVersionManager>();

The source code is at

Your comments are welcome,
kind regards,

Leave a comment

Posted by on 2012/08/28 in .net, c#, developer, microsoft, Prism


Tags: , , , ,


Get every new post delivered to your Inbox.

Join 728 other followers