How to Debug the Design Time Errors in WPF XAML File?

[Reblogged from How to Debug the Design Time Errors in WPF XAML File? thanks to Manish Dubeyy]

Introduction

While developing WPF applications, design view plays an important role not only placing the controls but also we can see the run time view at design time. How does it look like? It becomes frustrating when we see some design time errors and we cannot put a break point in XAML file to diagnose the error, moreover due to this single error sometimes, whole designer fails rendering other controls. So this article enables us to debug the design view of XAML documents in WPF.

Background

It is a pre-requisite that one should be familiar with basic WPF and most importantly one should know how to set design time data context. You can refer to other articles on CodeProject to know how to set a design time data context like this one.

Problem

While designing WPF applications, we frequently see the following types of error in our design view (See pic). Since XAML code does not allow us to insert a break point and debug the stuff, I will share a small trick to trap this error. (References are already there on the internet, but still developers are not so habituated to using it. The reason is that most of them don’t know it.)

ErrorPreview

Steps To Debug the Design Time Errors

  1. First of all, close all opened XAML documents in Visual Studio.
  2. Open the new instance of the same application in Visual Studio (say app2).
  3. Again, close all opened XAML documents. (To be on the safe side, you may close all documents in app2).
  4. Now open Task Manager just to verify whether XDesProc.exe must not be running. (Basically XDesProc.exeis responsible for debugging XAML files, so if any XAML documents are opened, then it launches automatically). So, if you find that XDesProc.exe is running (in Processes Tab), just kill it (right click on process and click on End Process Tree option).
  5. Now switch to app1 (original instance of Visual Studio in which you want break point to be hit). Now, open the file containing the design data view model (MainWindowViewModelDesignData.cs) and place a break point in the first line of its constructor.
  6. Switch to app2 again and open the View (i.e. MainWindow.xaml in which design time error is raising). It will launch the XDesProc.exe in Task Manager.
  7. Switch to app1 again, and go to Debug -> Attach to Processes… context menu item in Menu bar of Visual Studio.
  8. Search the XDesProc.exe and click on attach button.
  9. Switch to app2 and close and reopen the same XAML document (MainWindow.xaml). Once you do it, break point will get hit!2-Solve
  10. Here, you will find that you have not instantiated the PersonList property which is causingNullReference Exception in WPF Designer. After fixing it, you will see that now the designer is showing the data as well.3-DesignView

Points of Interest

For Visual Studio 2010 users, you will find devenv.exe in place of XDesProc.exe. Also, you can tweak with the exception settings if your break point does not becomes active (i.e., Go to Debug -> Exceptions settings -> Common Language RunTime Exceptions).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Advertisements

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.

Fast and easy deployment with WiX 3.10 for Visual Studio 2015

Nino Crudele's Blog

Wix is a great toolset which able to provide all we need to create a great deployment, I’m preparing the setup for jitGate, now in private beta test and I’m using WiX 3.10, this version support Visual Studio 2015, the installation is very simple and the 3.10 build is available here.

Essentially WiX is a toolset completely based on top of Windows Installer and it is completely base on XML scripting, here the name Windows Installer XML Toolset, WiX Toolset.

WiX is free and open source and the framework is able to cover all the large number of features and options offered by Microsoft Windows Installer, it also provide a large number of tool to made easy creating our deployment database and WiX already offers a large number of setup dialog forms ready and we can also customize them.

WiX is able to offer a great WPF setup interfaces, the Wix setup…

View original post 173 more words

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 🙂

Software on the hosted build server

Took directly from visual studio site: Hosted build controller.

You can check the detail list, and install the visual studio extension “Avanade Extensions for VS2012” (VS2013 version) to track the software installed on the hosted build server using the Software Inventory functionality.

The hosted build server is deployed with the following software:

  • Windows Server 2012 R2, 64-bit environment, with Windows PowerShell
  • Team Foundation Build (Team Foundation Server 2013)
  • Visual Studio
    • Visual Studio 2013 Update 2 RC
    • Visual Studio SDK 2013 RTM
    • Visual Studio 2012 Ultimate Update 4
    • Visual Studio SDK 2012 RTM
    • Visual Studio 2010 SP1
  • The .NET Framework
    • .NET 4.5.1
    • .NET 4.5
    • .NET 3.5 SP1
  • Microsoft Azure
    • SDK 2.3
    • SDK 2.2
    • SDK 2.1
    • SDK 2.0
    • SDK 1.8
    • SDK 1.7
  • Other components
    • Apache ANT 1.9.3
    • Apache Maven 3.1.1
    • Java Standard Edition Development Kit 1.7 U51
    • Microsoft Office Developer Tools for Visual Studio 2013 Update 1
    • Node.js 0.10.26
    • Node.js Tools 1.0 Alpha for Visual Studio 2013
    • SharePoint 2010 and SharePoint 2013
    • SQL Server Data Tools for Visual Studio 2010, Visual Studio 2012, and Visual Studio 2013
    • TFS Build Extensions
    • TypeScript 1.0
    • WIX Toolset 3.7
    • Web Deploy 3.0
    • Windows Phone SDK 8.0

 

Convert XML to C# Classes

Today I found a cool Visual Studio 2012/2013 functionality: you can paste an XML 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:

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

 

NuGet + Visual Studio: Automatic Package Restore of Different Solutions to the Same Folder

Attachment with the sample: NugetPackageRestore.zip

Today I had a problem using nuget package restore in a quite complex project that has multiple projects and multiple solutions file located in different folders, so that nuget was restoring the packages in a wrong folder for some of my solutions.

For instance if you have a file structure like this:

Root
  |- ProjectA
  |- |- ProjectA.Model
  |- |- |- ProjectA.Model.csproj
  |- |- ProjectA.Service
  |- |- |- ProjectA.Service.csproj
  |- |- ProjectA.sln
  |- Project B
  |- |- ProjectB.Model
  |- |- |- ProjectB.Model.csproj
  |- |- ProjectB.Service
  |- |- |- ProjectB.Service.csproj
  |- |- ProjectB.sln
  |- AllMyProjects.sln

AllMyProjects.sln simply contains all the projects (ProjectA.Model.csproj, ProjectA.Service.csproj, ProjectB.Model.csproj, ProjectB.Service.csproj).

When you run the build for all the 3 solutions, nuget by default will restores everything in a folder “packages” located at the same level of the solution file, producing something like this:

Root
  |- Packages
  |- (...all the packages...)
  |- ProjectA
  |- |- Packages
  |- |- |- (...all the packages...)
  |- |- ProjectA.Model
  |- |- |- ProjectA.Model.csproj
  |- |- ProjectA.Service
  |- |- |- ProjectA.Service.csproj
  |- |- ProjectA.sln
  |- Project B
  |- |- Packages
  |- |- |- (...all the packages...)
  |- |- ProjectB.Model
  |- |- |- ProjectB.Model.csproj
  |- |- ProjectB.Service
  |- |- |- ProjectB.Service.csproj
  |- |- ProjectB.sln
  |- AllMyProjects.sln

Now, if you first compile the ProjectA.sln and ProjectB.sln, also the AllMyProjects.sln will compile fine, but this just because the packages will be correctly restored by the two specific solution ProjectA.sln and ProjectB.sln, but if you try to clean up all the packages folder, and build the AllMyProjects.sln first, you will get a lot of compile error, this because the projects are poiting the nuget restored dll(s) inside specific folders and not a generic folder instead.

One possible fix to this, is to move all the solutions file, under the same folder, to le restore the packages to the same folder for every project, but I preferred to leave the structure as is, and try to force the nuget packages restore process. In fact there’s a key configuration “repositoryPath” to override the default packages folder location.

These are the steps to move the packages folder to a common location:

1 – Create a NuGet.config file under the root folder (nuget will find and use this file using a recursive search, starting from .nuget folder of the solution folder):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value="$\..\Packages" />
  </config>
  <solution>
    <add key="disableSourceControlIntegration" value="true" />
  </solution>
</configuration>

$ = refers to the NuGet.config file
we need to type “$\..\” and not just “$\” to set the Root folder just because I think is a kind of bug.

You will end-up with something like this:

Root
  |- ProjectA
  |- |- ProjectA.Model
  |- |- |- ProjectA.Model.csproj
  |- |- ProjectA.Service
  |- |- |- ProjectA.Service.csproj
  |- |- ProjectA.sln
  |- Project B
  |- |- ProjectB.Model
  |- |- |- ProjectB.Model.csproj
  |- |- ProjectB.Service
  |- |- |- ProjectB.Service.csproj
  |- |- ProjectB.sln
  |- AllMyProjects.sln
  |- NuGet.config

2a – Edit all the projects file and fix the dll reference by replacing the old relative path with the new one

2b – In alternative to 2a, you can run the nuget command “Update-Package –reinstall” from the nuget “Package Manager Console”, but this can dirty you projects, then I prefer do it manually directly from notepad 🙂

3 – Delete all the Packages folder and try to build every solution. To best test that everything is fine, before build a solution always delete the packages folder. You should see the “Packages” folder only once:

Root
  |- Packages
  |- (...all the packages...)
  |- ProjectA
  |- |- ProjectA.Model
  |- |- |- ProjectA.Model.csproj
  |- |- ProjectA.Service
  |- |- |- ProjectA.Service.csproj
  |- |- ProjectA.sln
  |- Project B
  |- |- ProjectB.Model
  |- |- |- ProjectB.Model.csproj
  |- |- ProjectB.Service
  |- |- |- ProjectB.Service.csproj
  |- |- ProjectB.sln
  |- AllMyProjects.sln
  |- NuGet.config