WPF Design Time Resources Dictionary

[Reblogged from WPF Design Time Support (Part 2) thanks to jbe2277]

The WPF Designer works best if there is just one WPF project in the solution which is the application (exe) and so contains the App.xaml file. Then it will find all XAML resources that are necessary to render the views flawlessly. But in larger applications the views are often separated into different WPF projects (e.g. per module). In such a scenario the WPF designer is not able to find the resources defined or referenced in App.xaml anymore when this file resides in another project.

Microsoft introduced the Design-time Resources Dictionary file to overcome this issue. Blend is able to detect that some resources could not be resolved and asks us if we want to add a resource dictionary to use for displaying resources at design time.

blend-designtimeresources

Visual Studio uses this file as well but it is not able to create the file. If you want to create this file in Visual Studio then you have to create a Resource Dictionary (WPF). Use DesignTimeResources.xaml as file name and after creation move the file into the Properties folder in your project tree.

Now unload the project (Context menu of the project node in Solution Explorer). Then select Edit YourProject.csproj in the context menu of the unloaded project node. Search for the XML element that contains DesignTimeResources.xaml and replace it with the following XML snippet:

<Page Include="Properties\DesignTimeResources.xaml" Condition="'$(DesignTime)'=='true' OR ('$(SolutionPath)'!='' AND Exists('$(SolutionPath)') AND '$(BuildingInsideVisualStudio)'!='true' AND '$(BuildingInsideExpressionBlend)'!='true')">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
  <ContainsDesignTimeResources>true</ContainsDesignTimeResources>
</Page>

Reload the project. The DesignTimeResource dictionary can be filled with MergedDictionaries. In the following example the merged dictionaries reside in another assembly. Thus, the long Source path is used.

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/Waf.InformationManager.Common.Presentation;Component/Resources/ImageResources.xaml"/>
        <ResourceDictionary Source="/Waf.InformationManager.Common.Presentation;Component/Resources/ConverterResources.xaml"/>

This file will be ignored by the compiler. It does not have any effects on the running application. It is just used to improve the design time experience.

Web Browser Control – Specifying the IE Version

Thanks to Rick Strahl for this 🙂

http://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version

Straight to the point:

Feature Delegation via Registry Hacks

Fortunately starting with Internet Explore 8 and later there’s a fix for this problem via a registry setting. You can specify a registry key to specify which rendering mode and version of IE should be used by that application. These are not global mind you – they have to be enabled for each application individually by writing a registry value for each specific EXE that is hosting the WebBrowser control.

This setting can be made for all users on local machine registry key or per user in the current user key of the registry.

For the Current User:

I’d recommend using the current user setting, as this setting can be made in one place and doesn’t require admin rights to write to the registry. This means you can actually make this change from within your application even if you don’t use an installer or run under an Admin account.

You do have to restart the app to see the change.

The key to write to is:

HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION

Value Key: DWORD  YourApplication.exe

Note that the FeatureControl and FEATURE_BROWSER_EMULATION keys may not exist at all prior to installation, so you may have to install that whole branch.

For all Users:

There are two different sets of keys for 32 bit and 64 bit applications.

64 bit or 32 bit only machine:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

Value Key: DWORD – YourApplication.exe

32 bit on 64 bit machine:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

Value Key: DWORD YourApplication.exe

The value to set this key to is (taken from MSDN here) as decimal values:

11001 (0x2AF9)
Internet Explorer 11. Webpages are displayed in IE11 Standards mode, regardless of the !DOCTYPE directive.

11000 (0x2AF8)
Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

10001 (0x2711)
Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.

10000 (0x2710)
Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

9999 (0x270F)
Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.

9000 (0x2328)
Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

8888 (0x22B8)
Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.

8000 (0x1F40)
Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.

7000 (0x1B58)
Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

The added key looks something like this in the Registry Editor:

RegistryEditorEmulation_2

Note that the 32 bit and 64 bit settings are significant depending on the type of application you are running. If you are running a 32 bit application on a 64 bit machine you need to use the Wow6432Node key to register this setting. If you’re running a 32 bit application on a 32 bit machine, or 64 bit application on a 64 bit application, then the standard registry key should be used.  This means if you’re installing a 32 bit application using an installer you probably will want to set both the Wow64 key and the regular key on the machine.

With this in place my Html Html Help Builder application which has wwhelp.exe as its main executable now works with HTML 5 and CSS 3 documents in the same way that Internet Explorer 9 does.

Incidentally I accidentally added an ‘empty’ DWORD value of 0 to my EXE name and that worked as well giving me IE 9 rendering. Although not documented I suspect 0 (or an invalid value) will default to the installed browser. Don’t have a good way to test this but if somebody could try this with IE 8 installed that would be great:

  • What happens when setting 9000 with IE 8 installed?
  • What happens when setting 0 with IE 8 installed?

Don’t forget to add Keys for Host Environments

If you’re developing your application in Visual Studio and you run the debugger you may find that your application is still not rendering right, but if you run the actual generated EXE from Explorer or the OS command prompt it works. That’s because when you run the debugger in Visual Studio it wraps your application into a debugging host container. For this reason you might want to also add another registry key for yourapp.vshost.exe on your development machine.

If you’re developing in Visual FoxPro make sure you add a key for vfp9.exe to see the rendering adjustments in the Visual FoxPro development environment.

Web Api: enable XML documentation for your subproject (external assembly)

I would admit that this post it’s simply a copy/paste of a stackoverflow response, that was really well done and IMHO should also be in the documentation! of course I up-voted that post 🙂

There is no built-in way to achieve this. However, it requires only a few steps:

  1. Enable XML documentation for your subproject (from project properties / build) like you have for your Web API project. Except this time, route it directly to XmlDocument.xml so that it gets generated in your project’s root folder.
  2. Modify your Web API project’s postbuild event to copy this XML file into your App_Data folder:
    copy $(SolutionDir)SubProject\XmlDocument.xml $(ProjectDir)\App_Data\Subproject.xml

    Where Subproject.xml should be renamed to whatever your project’s name is plus .xml.

  3. Next open .Areas.HelpPage.HelpPageConfig and locate the following line:
    config.SetDocumentationProvider(new XmlDocumentationProvider(
        HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

    This is the line you initially uncommented in order to enable XML help documentation in the first place. Replace that line with:

    config.SetDocumentationProvider(new XmlDocumentationProvider(
        HttpContext.Current.Server.MapPath("~/App_Data")));

    This step ensures that XmlDocumentationProvider is passed the directory that contains your XML files, rather than the specific XML file for your project.

  4. Finally, modify ./Areas/HelpPage/XmlDocumentationProvider in the following ways:
    1. Replace the _documentNavigator field with:
      private List<XPathNavigator> _documentNavigators = new List<XPathNavigator>();
    2. Replace the constructor with:
      public XmlDocumentationProvider(string appDataPath)
      {
          if (appDataPath == null)
          {
              throw new ArgumentNullException("appDataPath");
          }
      
          var files = new[] { "XmlDocument.xml", "Subproject.xml" };
          foreach (var file in files)
          {
              XPathDocument xpath = new XPathDocument(Path.Combine(appDataPath, file));
              _documentNavigators.Add(xpath.CreateNavigator());
          }
      }
    3. Add the following method below the constructor:
      private XPathNavigator SelectSingleNode(string selectExpression)
      {
          foreach (var navigator in _documentNavigators)
          {
              var propertyNode = navigator.SelectSingleNode(selectExpression);
              if (propertyNode != null)
                  return propertyNode;
          }
          return null;
      }
    4. And last, fix all compiler errors (there should be three) resulting in references to _documentNavigator.SelectSingleNode and remove the _documentNavigator. portion so that it now calls the new SelectSingleNode method we defined above.

    This Last step is what modifies the document provider to support looking within multiple XML documents for the help text rather than just the primary project’s.

    Now when you examine your Help documentation, it will include XML documentation from types in your related project.

How to extend/migrate TraitAttribute to XUnit v2 and why has become sealed

xUnit

In these days I was testing xUnit for the first time, and as a greedy developer, I started with the pre-release v2. Everything was great, except that I was trying to categories my tests in unit, integration, manual, and so on, to let me separate the CI tests from the ones, and I found misleading documentation out there, actually it was simply because there’s some breaking changes passing from v1 to v2, and one is that TraitAttribute is now sealed.

In xUnit v1 and v2 there’s the Trait attribute than can be used to add any kind of description above a test method and that can be read from visual studio test explorer and of course from gui/consoles as well. This description can be useful to let you run just a “category” of tests. See “Using Traits with different test frameworks in the Unit Test Explorer” for more information about Traits in Visual Studio 2013.

Trait and Visual Studio Test Explorer

The annoying part is that Trait takes two strings as name/value pairs, and needs to be copied all around your tests:

public class MyTests1
{
    [Trait("Category", "CI")]
    [Fact]
    public void Test1()
    {
    }

    [Trait("Category", "CI")]
    [Fact]
    public void Test2()
    {
    }

    [Trait("Category", "CI")]
    [Fact]
    public void Test3()
    {
    }
}

One convenient way is to put the Trait attribute on the class itself, in that way every single method will “inherits” that attribute, and with the latest version of visual studio + updates, you will get the expected behavior in the test explorer:

[Trait("Category", "CI")]
public class MyTests2
{
    [Fact]
    public void Test1()
    {
    }

    [Fact]
    public void Test2()
    {
    }

    [Fact]
    public void Test3()
    {
    }
}

But a more convenient way could be to define our CI attribute, and in v1 was easy as inherits:

public class CIAttribute : TraitAttribute
{
    public CIAttribute() 
        : base("Category", "CI")
    {
    }
}

and you can straight use it:

public class MyTests1
{
    [CI]
    [Fact]
    public void Test1()
    {
    }

    [CI]
    [Fact]
    public void Test2()
    {
    }

    [CI]
    [Fact]
    public void Test3()
    {
    }
}

[CI]
public class MyTests3
{
    [Fact]
    public void Test1()
    {
    }

    [Fact]
    public void Test2()
    {
    }

    [Fact]
    public void Test3()
    {
    }
}

…but how to do the same in xUnit v2, where the TraitAttribute become sealed? And why has become selead?

I ask this on a github issue and Brad Wilson (a team member of xUnit) replied me a really exhaustive explanation:

Test discovery in xUnit.net can happen without binaries (Resharper and CodeRush can discover tests as you type, by looking at the source code, even when that code doesn’t necessarily compile).

In order to support this (not being able to run code), it requires that we seal the attributes, so that discovery can be based on things that are known only from the source, and not from running compiled code.

Let’s take a common example: someone wants to make [Category("...")] which is the equivalent of[Trait("category", "...")]. Without a sealed attribute, you would write this:

public class CategoryAttribute : TraitAttribute
{
    public CategoryAttribute(string value) : base("category", value) { }
}

The problem is that Resharper or CodeRush cannot run this code, they can only look at the source. Simple examples like this may be possible, but it doesn’t take long to come up with a scenario where it becomes non-trivial and the only recourse would be to run code and see what happens.

So the tradeoff we make here is to require a bit of known-to-be-compiled code which can inspect the[Category("...")] code and return the correct trait value(s). By sealing the attribute, it says that someone who wants to write CategoryAttribute also needs to write the discoverer that can make sense of what that means without being able to run the code in question.

We have an example which does exactly this: https://github.com/xunit/samples/tree/master/TraitExtensibility

and here it is the migration of CIAttribute:

[TraitDiscoverer("ClassLibrary1.CIDiscoverer", "ClassLibrary1")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CIAttribute : Attribute, ITraitAttribute
{
}

public class CIDiscoverer : ITraitDiscoverer
{
    public IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; GetTraits(IAttributeInfo traitAttribute)
    {
        yield return new KeyValuePair&lt;string, string&gt;("Category", "CI");
    }
}

Pay attention on [TraitDiscoverer("ClassLibrary1.CIDiscoverer", "ClassLibrary1")], the first argument is “The fully qualified type name of the discoverer (f.e., ‘Xunit.Sdk.TraitDiscoverer’)” and the second argument is “The name of the assembly that the discoverer type is located in, without file extension (f.e., ‘xunit.execution’)“, it took me a while to figure it out because as usual I should RTFM first 🙂

C# .NET – Collections Comparison

generic.net.collection.interfaces

I liked a James Michael Hare’s post “C#/.NET Fundamentals: Choosing the Right Collection Class“, and I like to re-blog the comparison table:

Collection Ordering Contiguous Storage? Direct Access? Lookup Efficiency ManipulateEfficiency Notes
Dictionary Unordered Yes Via Key Key:O(1) O(1) Best for high performance lookups.
SortedDictionary Sorted No Via Key Key: O(log n) O(log n) Compromise of Dictionary speed and ordering, uses binarysearch tree.
SortedList Sorted Yes Via Key Key:O(log n) O(n) Very similar toSortedDictionary, except tree is implemented in an array, so has faster lookup on preloaded data, but slower loads.
List User has precise control over element ordering Yes Via Index Index: O(1)
Value: O(n)
O(n) Best for smaller lists where direct access required and no sorting.
LinkedList User has precise control over element ordering No No Value:O(n) O(1) Best for lists where inserting/deleting in middle is common and no direct access required.
HashSet Unordered Yes Via Key Key:O(1) O(1) Unique unordered collection, like a Dictionary except key and value are same object.
SortedSet Sorted No Via Key Key:O(log n) O(log n) Unique sorted collection, like SortedDictionary except key and value are same object.
Stack LIFO Yes Only Top Top: O(1) O(1)* Essentially same as List except only process as LIFO
Queue FIFO Yes Only Front Front: O(1) O(1) Essentially same as List except only process as FIFO

Linq Take Random – Query to Get a Random Sub Collection – Random Order

While writing a load test today, I had to simulate different kind of customers with different kind of taste, and I had a collection of item ids, and to simulate a random distribution, I had to generate a sub collection taking random ids from the collection source, in that way I can simulate different kind of customers that will end-up querying the server requesting different item details.

Googling a little-bit I found an easy way to do this, and is to Order the collection by a different Guid for each row:

var result = collection.OrderBy(t => Guid.NewGuid());

and to get (take) 10 random elements:

var result = collection.OrderBy(t => Guid.NewGuid()).Take(10);

From the Scott Mitchell’s post, you can see some empirical tests that proves a nice random distribution. Of course this is not to use in production code where you absolutely need an unpredictable results, but for load testing, and other take-it-easy purpose, that’s cool.

This is a LINQPad example:

void Main()
{
	var collection = Enumerable.Range(1, 100).ToList();
	
	for (int i = 0; i < 3; i++)
	{
		collection.OrderBy(t => Guid.NewGuid()).Take(10).Dump();
	}
}

linq-take-random

Convert XML and JSON to C# Classes

Today I found a cool Visual Studio functionality: you can paste an XML or JSON source as Classes, in fact creating all the object model to serialize and deserialize object with the xml format, all this without using xsd.exe tool.

Here’s the very simple steps regarding an XML but it’s the same for JSON:

1 – The most difficult step….. copy the xml source in the clipboard, something like CTRL+A and CTRL+C 🙂

Image

Is ridiculous to add a screenshot, but I’ve got it, so why not!

2 – Create a new empy class file… no more screenshot please! ok here we go 😉

3 – Go to Edit -> Paste Special -> Paste XML As Classes, to paste the generated classes based on the source xml

Image

Image

Here’s the code I’ve used to test the deserialization:

using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using ConsoleDump;
using ConvertXmlToCSharpClasses.Properties;

namespace ConvertXmlToCSharpClasses
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            TestSample1();

            TestSample2();

            Console.WriteLine("Press enter to exit the application...");
            Console.ReadLine();
        }

        private static void TestSample1()
        {
            var serializer = new XmlSerializer(typeof(library));
            var buffer = Encoding.UTF8.GetBytes(Resources.Sample1);
            using (var stream = new MemoryStream(buffer))
            {
                var library = (library)serializer.Deserialize(stream);
                library.book.Dump("Book");
                library.book.title.Dump("Book Title");
                library.book.author.Dump("Book Title");
            }
        }

        private static void TestSample2()
        {
            var serializer = new XmlSerializer(typeof(catalog));
            var buffer = Encoding.UTF8.GetBytes(Resources.Sample2);
            using (var stream = new MemoryStream(buffer))
            {
                var catalog = (catalog)serializer.Deserialize(stream);
                catalog.product.Dump("Product").catalog_item.Dump("Product Items")[0].size.Dump("Item Size")[0].color_swatch.Dump("Color Swatch");
            }
        }
    }
}

You can also download the test project.

4 – Enjoy your saved time

Image

 

WPF: ContentControl vs ContentPresenter

A small post to explain the little but important difference between ContentControl and ContentPresenter.

The most significant difference is that ContentPresenter has the ContentSource property while ContentControl hasn’t.

The ContentPresenter.ContentSource property specify which dependency property of the parent template instnace should be used to fill the ContentPresenter.Content.

For instance if you have a UserControl “MyControl” that defines a dependency property called  “MyProperty”, you can use the value of MyControl.MyProperty in the MyControl.Template in this way:

<ControlTemplate TargetType="MyControl">
      <StackPanel>
          <ContentPresenter ContentSource="MyProperty" />
      </StackPanel>
</ControlTempalte>

Instead using the ContentControl you could write the same template in this way:

<ControlTemplate TargetType="MyControl">
      <StackPanel>
          <ContentControl Content="{TemplateBinding MyProperty}" />
      </StackPanel>
</ControlTempalte>

In fact the ContentControl has a template that uses a ContentPresenter to show it’s own Content property using the ContentSource. The ContentPresenter is a light-weight component that is supposed to be used in a template as a simple place-holder for the Content property. The default value for the ContentPresenter.ContentSource is “Content”, so you just need to add an empty ContentPresenter in a template to let be the place-holder of the Content property of the template parent instance.

WPF: Attached Property in XAML Markup (The object ‘…’ already has a child and cannot add ‘…’)

Let’s say you need an attached property to set an arbitrary header content to any DependencyObject, to let you use that value and populate the Header property of any HeaderedContentControl, creating the class directly in your WPF test application:

public static class HeaderManager
{
	public static readonly DependencyProperty HeaderProperty = DependencyProperty.RegisterAttached(
		&quot;Header&quot;,
		typeof(object),
		typeof(HeaderManager),
		new PropertyMetadata(null));

	public static void SetHeader(DependencyObject element, object value)
	{
		element.SetValue(HeaderProperty, value);
	}

	public static object GetHeader(DependencyObject element)
	{
		return (object)element.GetValue(HeaderProperty);
	}
}

Then you want to attach that property to an UserControl that when injected in a TabItem can self declare it’s own header, and in first attempt you will end up trying to do this:

&lt;UserControl x:Class=&quot;RadicalTabRegion.Presentation.FirstView&quot;
             xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
             xmlns:s=&quot;clr-namespace:RadicalTabRegion.Presentation.Regions.Specialized&quot;
             mc:Ignorable=&quot;d&quot;
             d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;300&quot;&gt;

    &lt;s:HeaderManager.Header&gt;
        &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
            &lt;TextBlock Text=&quot;First View&quot;/&gt;
            &lt;CheckBox/&gt;
        &lt;/StackPanel&gt;
    &lt;/s:HeaderManager.Header&gt;

    &lt;Grid&gt;
        &lt;TextBlock Text=&quot;I'm the first view&quot;/&gt;
    &lt;/Grid&gt;

&lt;/UserControl&gt;

But if you try to compile this, you will get this error:

“The object ‘UserControl’ already has a child and cannot add ‘Grid’. ‘UserControl’ can accept only one child.”

This is because the compiler needs to know that HeaderManager.Header is an attached property, before compile xaml in baml, but because the HeaderManager class is declared in the same assembly of the xaml, it can’t. Actually I think this can be overcome by Microsoft, but never mind there’s a couple of solutions for that.

The first solution is to move the markup declaration after the first element in the UserControl content, and our case after the Grid:

&lt;UserControl x:Class=&quot;RadicalTabRegion.Presentation.FirstView&quot;
             xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
             xmlns:s=&quot;clr-namespace:RadicalTabRegion.Presentation.Regions.Specialized&quot;
             mc:Ignorable=&quot;d&quot;
             d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;300&quot;&gt;

    &lt;Grid&gt;
        &lt;TextBlock Text=&quot;I'm the first view&quot;/&gt;
    &lt;/Grid&gt;

    &lt;s:HeaderManager.Header&gt;
        &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
            &lt;TextBlock Text=&quot;First View&quot;/&gt;
            &lt;CheckBox/&gt;
        &lt;/StackPanel&gt;
    &lt;/s:HeaderManager.Header&gt;

&lt;/UserControl&gt;

The second solution is to move the HeaderManager class into a different class library, so in a different assembly, and this is the best approach because let you use the attached property more naturally, without incurring in that compile error even if you declare the property just before the UserControl.Content, that is more natural for an Header property. For instance if you add the class into a class library called “RadicalTabRegion.Windows.Presentation” you will end-up with this XAML that just works fine:

&lt;UserControl x:Class=&quot;RadicalTabRegion.Presentation.FirstView&quot;
             xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
             xmlns:s=&quot;clr-namespace:RadicalTabRegion.Windows.Presentation.Regions.Specialized;assembly=RadicalTabRegion.Windows.Presentation&quot;
             mc:Ignorable=&quot;d&quot;
             d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;300&quot;&gt;

    &lt;s:HeaderManager.Header&gt;
        &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
            &lt;TextBlock Text=&quot;First View&quot;/&gt;
            &lt;CheckBox/&gt;
        &lt;/StackPanel&gt;
    &lt;/s:HeaderManager.Header&gt;

    &lt;Grid&gt;
        &lt;TextBlock Text=&quot;I'm the first view&quot;/&gt;
    &lt;/Grid&gt;

&lt;/UserControl&gt;

This example is a part of an implementation I’m making for Radical to implement a TabControlRegion, that is able to inject a simple UserControl into a TabItem (generated at runtime) and let the developer deeply customize the TabItem.Header simply declaring the attached property directly into the UserControl. This is under development right now, and it is just one of the possible solutions, if I will like it, I will post the entire code, and pull a request for integrating the new region directly into Radical.

C#: Enable Cookie Container on System.Net.WebClient (for Authentication)

As I told on the previous post the WebClient can be easily extended to add more functionality such in this case the Cookie Container, and let use it to authenticate versus the web pages that are protected using an authenticated cookie:

public class CookieWebClient : WebClient
{
	public CookieContainer CookieContainer { get; private set; }

	/// <summary>
	/// This will instanciate an internal CookieContainer.
	/// </summary>
	public CookieWebClient()
	{
		this.CookieContainer = new CookieContainer();
	}

	/// <summary>
	/// Use this if you want to control the CookieContainer outside this class.
	/// </summary>
	public CookieWebClient(CookieContainer cookieContainer)
	{
		this.CookieContainer = cookieContainer;
	}

	protected override WebRequest GetWebRequest(Uri address)
	{
		var request = base.GetWebRequest(address) as HttpWebRequest;
		if (request == null) return base.GetWebRequest(address);
		request.CookieContainer = CookieContainer;
		return request;
	}
}

And then you can use it as follow:

using (var client = new CookieWebClient())
{
	var loginData = new NameValueCollection
	{
		{ "UserName", "TestUser" },
		{ "Password", "MyPassword" }
	};

	// Login into the website (at this point the Cookie Container will do the rest of the job for us, and save the cookie for the next calls)
	client.UploadValues("http://domain.com/Account/LogOn", "POST", loginData);

	// Call authenticated resources
	client.UploadString("http://domain.com/ProtectedArea/MyProtectedResource", "POST", "some data");
}

CookieWebClient takes also a CookieContainer as parameter, to let you control the cookie container outside, and passing over different CookieWebclient instantiation.