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)

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.

EF6.x Correlating Poor Performing SQL to Application Code

RoMiller.com

When using an O/RM, poor performing SQL statements are often not discovered until you (or your DBA) find that a particular query is slowing down your database server. At this point, it becomes hard to identify which piece of application code is causing that SQL to be executed.

An interceptor to log slow/failed SQL

In EF6.0.0 we introduced interceptors, which allow you to get into the pipeline just before, and just after, a query/command is sent to the database.

Here is an interceptor that detects queries/commands that either failed, or exceeded a chosen threshold for execution time. In addition to the query being executed, it logs the call stack. This allows us to identify which piece of our application code initiated the database operation.

This example writes to a log file, but you can log the information to wherever needed.

Registering the interceptor

The easiest way to get our…

View original post 133 more words

Entity Framework validation with partial updates

I had this issue today, basically Entity Framework always validate all the entity, so if you want to make a partial update using Attach/Entity State way, you can’t do it if you have configured validation on your model and you don’t fill all your entity with good values, but we want to do a partial update without do another query before, and also without filling up all the entity with data I don’t have, so how to do it?

The most easiest and fastest way is to completely disable the validation for your operation, but this is not the ideal way, what about validating the property I’m near to udpate?

using (var db = new NorthwindDbContext())
{
    // disable the validation for this operation
    db.Configuration.ValidateOnSaveEnabled = false;

    var customer = new Customer
    {
        CustomerId = "ALFKI"
    };
    db.Customers.Attach(customer);

    customer.PostalCode = "123456789000";

    // throw sql exception because PostalCode goes over 10 chars maximum
    // String or binary data would be truncated.
    await db.SaveChangesAsync();
}

Thanks to Shimmy I found what I think is the most elegant solution:

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
    var result = base.ValidateEntity(entityEntry, items);

    var falseErrors = result.ValidationErrors
                            .Where(error =>
                            {
                                if (entityEntry.State != EntityState.Modified) return false;
                                var member = entityEntry.Member(error.PropertyName);
                                var property = member as DbPropertyEntry;
                                if (property != null) return !property.IsModified;
                                return false;
                            });

    foreach (var error in falseErrors.ToArray())
    {
        result.ValidationErrors.Remove(error);
    }

    return result;
}

To the Shimmy sample I’ve added the condition “if (entityEntry.State != EntityState.Modified) return false;” to avoid bypass the validation when adding an entity.

Now if you test the same code as before, you will receive an entity framework exception and no round-trip will be made on sql server:

using (var db = new NorthwindDbContext())
{
    var customer = new Customer
    {
        CustomerId = "ALFKI"
    };
    db.Customers.Attach(customer);

    customer.PostalCode = "123456789000";

    // Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
    // The field PostalCode must be a string or array type with a maximum length of '10'.
    await db.SaveChangesAsync();
}

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

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.