The type initializer for +’System.Windows.PresentationSource’ threw an exception.

I had an issue with a 3rd party control. I couldn’t blame them too much since the issue only happened in the WPF control hosted in a MFC C++ application. brutal for sure.

Why host WPF in C++? That is a question for another time, but let’s just say its an app written in the early 90’s and still has been rewritten, just bolted on and refactored.

Well, I created the test application and it worked great on my machine at home. I loaded it into my work computer and blammo, it threw up on the get handle call. WTF?

If you step into the .NET source(slow but very helpful), you get this.

System.Runtime.Versioning.BinaryCompatibility.ParseTargetFrameworkMonikerIn/toEnum in the call stack. and  NULL parameter exception.

Turns out through some goofiness in VC++, it will insert a null value in a manifest.

The fix is really easy. Delete all the files in your AppData\Local\Temp folder under your profile.

Here is a link to a guy who wrote about it in much more detail, but man that was non-intuitive fix. It worked though, so I am happy!

Thanks Microsoft for stealing another hour of my life. Thanks Telerik for being there to steal a week trying to reproduce bugs in your silly slow controls.

Happy coding!

 

WPF Validation Errors not showing on initial load of control or window

I was setting validation errors on the initial load of my view model, and to my annoyance the window would show up like everything was great. The validation code was definitely running, the HasErrors was true, the dictionaries were filled with the errors but the form was like, “What errors?”  This irritated me. Well, WPF is stupid in this regard and doesn’t handle things properly. If you are like me, you set your datacontext after creating the view. Well, that is the logical way, but if you want validation you need to slightly alter that. I found a work around that fixes the problem, but is a little more annoying. Simply put, pass in your VM to the constructor of the view. Cache that, then set your DataContext(DC) on the load event. Sample code below:

public partial class AcceptRejectViewOldMeetsNew : UserControl
 {
   private object dcToSet = null;
   public AcceptRejectViewOldMeetsNew(object dc)
  {
    InitializeComponent();
    dcToSet = dc;
    this.Loaded += AcceptRejectViewOldMeetsNew_Loaded;
  }
  void AcceptRejectViewOldMeetsNew_Loaded(object sender, System.Windows.RoutedEventArgs e)
  {
    DataContext = dcToSet;
    }
 }

Happy Coding!

How to handle action on enter key press in textbox in WPF

Did you want your OK button or your commit action to take place when you hit enter in a text field in a WPF dialog? You may have implemented a Find dialog, or maybe you have a one field text entry and you want the Enter key to commit the action.

Well, its actually really easy once you learn the simple trick to wiring up the commands.

I have a command called SaveProcessCommand on my viewmodel. I have it wired to my dialogs “OK” button. I also wanted the user to just hit Enter when they were done typing, since that is how my usability study determined users expect.

Enter the simple InputBinding. Pretty cool.

[csharp] <TextBox Margin="10,0,0,0" HorizontalAlignment="Stretch" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1">
<TextBox.InputBindings>
<KeyBinding Command="{Binding SaveProcessCommand}" Key="Enter"/>
</TextBox.InputBindings>
</TextBox>
[/csharp]

I have the binding to the property update on each keystroke, so it is always up to date. The InputBinding then wires up the Enter key to a command. The command can do whatever you want, you are using MVVM right? Happy Coding!

How to reclassify your project into a WPF project in Visual Studio

How to change project type to wpf class library in Visual Studio 2012.

Are you looking to change your project from a normal C# class library to a Window Presentation Framework project?

Well, it is not that hard once you learn the trick. It took me a little while to dig up the info, so hopefully this saves you some time.

Open your csproj file in notepad. Look for the ProjectTypeGuids key. If not found, add it.

Here is what it should look like when your done.

<ProjectTypeGuids>{60DC8134-EBA5-43B8-BCC9-BB4BC16C2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Visual Studio 2012 and Visual Studio 2010 use these to identify the project type. The settings above make it a C# WPF app.

Example:

SNAGHTML77868191

 

Happy Coding!

T4 Templates for Entity Framework Break when upgrading to Visual Studio 2012

I upgraded to Visual Studio 2012 and consequently upgraded to version 4.5 of the .NET framework. It turns out, this made our T4 templates very unhappy.

See, we use T4 templates for generating our Entity Framework(EF) models. A bunch of very fancy template coding that automagically creates our edmx and other code files from a reference database.

This worked very well in .NET 4.0, but simply upgrading to .NET 4.5 made it throw all sorts of fun errors.

The root cause turned out to be it was generating EF3 schema data which completely hosed the template code which was looking for EF2 schemas. Not to mention, I tried converting the template processing code to use the new schemas and then realized that since we target .NET 4.0, that we couldn’t compile after the templates worked.

So, I was stuck in a catch 22. Fix the templates, and can’t build the assembly, or only build the templates on a machine with .NET 4.0 and VS 2010. Both options suck.

Well, I reached out into the forums and got a little advice at least on targeting the right framework.

I changed the headers to target 4.0. That turned out to be Step 1.

<#@ template debug=”true” hostspecific=”false” language=”C#v4.0″ #>

<#@ output extension=”.edmx” #>

<#@ Assembly Name=”System.Core, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Data, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Data.Entity, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Xml, Version=4.0.0.0, Culture=neutral” #>

<#@ Assembly Name=”System.Xml.Linq, Version=4.0.0.0, Culture=neutral” #>

 

Now, step 2. I discovered through hours of staring at code and hoping for hope to find an overload, setting,property or something to say….Damn it, I wan’t EF 2 code. Yeah, you would think running in 4.0 framework mode would do that for me, right? Nothing can be simple.

I finally found it. The overloads I needed.

EntityContainer entityContainer = this.storeItems.GetItems<EntityContainer>()[0];
    this.modelGenerator = new EntityModelSchemaGenerator(entityContainer, ModelNamespace, this.entityContainerName);
    this.modelGenerator.GenerateForeignKeyProperties = true;
    this.modelGenerator.PluralizationService = this.pluralizationService;

    this.modelGenerator.GenerateMetadata(EntityFrameworkVersions.Version2);

Generate MetaData has a Version overload.

So does the schema generator.

  var generator = new EntityStoreSchemaGenerator(this.provider, this.connectionString, ModelNamespace + "." + StoreNamespace);

    IList<EdmSchemaError> errors = generator.GenerateStoreMetadata(this.filters,EntityFrameworkVersions.Version2);

 

So, now we have the fix. All is well in the world. Only lost a day or two of headbanging my screen and yelling at how much T4 is an undocumented piece of crap. Well, it least I have a stronger understanding of it now.

Hopefully this saves you some headache, since not one damn google search result explained this.

Happy Coding!

The remote certificate is invalid according to the validation procedure for FTP

I was testing a C# FTP application of mine and got this lovely gem of an error when connecting using SSL. I had a self signed certificate in the trusted store, but the FTP library kept screaming that the certificate was invalid.

Well, I found a great workaround for the time being. It should only be used by configuration or conditional compiling though.

Disable Certificate Chain Checking

[csharp]
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
[/csharp]

Using the code above, your certificate checks will always be considered good. The channel will still be SSL protected, you just won’t be looking for man in the middle attacks nor identity mismatches. Something you don’t care about in development, just production.

Happy Coding!

Initialize a static Dictionary inline in the declaration

Have you ever wanted to initialize a Dictionary object with lookup values, but didn’t want to put the code into a static constructor?

Well, here is the easy way to do it. Quite easy actually, just like declaring an Arrays initial values.

I decided I want to create a simple lookup dictionary keyed off of a string with the value being an int. Basically, I have strings that need to be matched to ints, for a custom sort algorithm with discrete inputs.

[csharp]

//discrete mapping dictionary
//initialized with the 4 values below
public static Dictionary<string,int> sortValueLookupDictionary = new Dictionary<string,int>()
{
 {"Key 1",1},
 {"Joy",2},
 {"Happy",3},
 {"Coding",4}
}

[/csharp]

Happy Coding!

Detect Windows/Operating System Version in C# .NET

Are you looking for a way to detect which OS you are running on in your .NET application? I know I had to so that I could implement workarounds that were OS specific.

Here is a simple function to get the name. You can use this as an idea of how to pick the exact version you are on.

Please don’t be one of those morons that uses this function then does a string comparison on the return. Use common sense and extract the logic from this to get what you need.

I better not see any code out there like

if(GetOSVersionName() == "Windows 98"){Do stupid stuff here}

Yes, it would technically work, so I have no doubt it will be implemented that way by some of you. Religious debate? Probably.

[csharp]
 public string GetOSVersionName()
        {
            string strVersion = "Unknown";
            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.Win32S:
                    return "Windows 3.1";
                case PlatformID.Win32Windows:
                    switch (Environment.OSVersion.Version.Minor)
                    {
                        case 0:
                            return "Windows 95";
                        case 10:
                            if (Environment.OSVersion.Version.Revision.ToString() == "2222A")
                            {
                                return "Windows 98 Second Edition";
                            }
                            else
                                return "Windows 98";
                        case 90:
                            return "Windows ME";
                    }
                    break;
                case PlatformID.Win32NT:
                    switch (Environment.OSVersion.Version.Major)
                    {
                        case 3:
                            return "Windows NT 3.51";
                        case 4:
                            return "Windows NT 4.0";
                        case 5:
                            switch (Environment.OSVersion.Version.Minor)
                            {
                                case 0:
                                    return "Windows 2000";
                                case 1:
                                    return "Windows XP";
                                case 2:
                                    return "Windows 2003";
                            }
                            break;
                        case 6:
                            switch (Environment.OSVersion.Version.Minor)
                            {
                                case 0:
                                    return "Windows Vista";
                                case 1:
                                    return "Windows 2008";
                                case 2:
                                    return "Windows 7";
                            }
                            break;
                    }
                    break;
                case PlatformID.WinCE:
                    return "Windows CE";
                case PlatformID.Unix:
                    return "Unix";
            }
            return strVersion;
        }
[/csharp]

Happy Coding!

How to speed up Excel and Word 2003,2007 and 2010 launch times when using Automation in C#

One of the biggest impacts on the launch time for Office is the speed at which all of the addins load. Unfortunately, poorly written or unnecessary addins add a startup cost which isn’t something you want to have to pay when loading Office via automation.
I wrote a nice helper class that allows you save the pain of loading them, without impacting the users experience.
Here is the class:

[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Win32;
 
namespace Seekford.Office
{
    public class OfficeAddinManagementUtility : IDisposable
    {
        private Dictionary<string, int > wordLoadBehaviorStorage = new Dictionary<string, int >();
        private Dictionary<string ,int > excelLoadBehaviorStorage = new Dictionary<string, int >();
 
        private const string _wordAddinRootKey = @"SoftwareMicrosoftOfficeWordAddins";
        private const string _excelAddinRootKey = @"SoftwareMicrosoftOfficeExcelAddins";
        private const string _loadString = "LoadBehavior";
 
        public void DisableAllWordAddins()
        {
            if (wordLoadBehaviorStorage.Any()) return;//unbalanced?
            DisableAllAddinsInHive(_wordAddinRootKey, wordLoadBehaviorStorage);
        }
 
        public void DisableAllExcelAddins()
        {
            if (excelLoadBehaviorStorage.Any()) return;//unbalanced?
            DisableAllAddinsInHive(_excelAddinRootKey, excelLoadBehaviorStorage);
        }
 
 
        private void DisableAllAddinsInHive(string hiveLocation, Dictionary<string, int > storage)
        {
            var userKey = Registry.CurrentUser.OpenSubKey(hiveLocation);
            if (userKey != null)
            {
                var subKeys = userKey.GetSubKeyNames();
                if (subKeys != null)
                {
                    foreach (var s in subKeys)
                    {
                        var subKey = userKey.OpenSubKey(s, true);
                        int val = (int)subKey.GetValue(_loadString, 0);
                        if (val != 0)
                        {
                            subKey.SetValue(_loadString, 0);
                            storage.Add(s, val);
                        }
                    }
                }
            }
        }
 
        private void RevertAllAddinsInHive(string hiveLocation, Dictionary<string, int > storage)
        {
            var userKey = Registry.CurrentUser.OpenSubKey(hiveLocation);
            if (userKey != null)
            {
                var subKeys = userKey.GetSubKeyNames();
                if (subKeys != null)
                {
                    foreach (var s in subKeys)
                    {
                        if (storage.ContainsKey(s))
                        {
                            var subKey = userKey.OpenSubKey(s, true);
                            if(subKey != null)
                            {
                                subKey.SetValue(_loadString, storage[s]);
                                storage.Remove(s);
                            }
                        }
                    }
                }
            }
        }
 
        public void RevertAllAddins()
        {
            RevertWordAddin();
            RevertExcelAddin();
        }
 
        public void RevertWordAddin()
        {
            if(wordLoadBehaviorStorage.Any())
                RevertAllAddinsInHive(_wordAddinRootKey, wordLoadBehaviorStorage);
        }
 
        public void RevertExcelAddin()
        {
            if(excelLoadBehaviorStorage.Any())
                RevertAllAddinsInHive(_excelAddinRootKey, excelLoadBehaviorStorage);
        }
       
        public void Dispose()
        {
            RevertAllAddins();
        }
    }
} 
[/csharp]

See how easy that is.

Just wrap your Word or Excel code, call the right methods and away you go.

[csharp]
//code below is a snippet showing you to disable addins, create your automated word,
// then reenable the addins for future word users
// use the excel methods for excel addins.
               var addinManager = new OfficeAddinManagementUtility();
                try
                {
                        addinManager.DisableAllWordAddins();
			myWord = new Word();
                }
                finally
                {
                    addinManager.RevertWordAddin();
                    addinManager.Dispose();//same as above, but lets comply with regs
                }
                return myWord;
[/csharp]

The utility disables all the Office Addins and then enables them back for the next launch of Office.

It is an easy to use C# class for disabling Word 2007/2010 and Excel 2007/2010 Addins. Should work with 2003 as well.

Happy Coding!

A new guard page for the stack cannot be created

 

You get a nice error that says, “A new guard page for the stack cannot be created”, well easy fix. I could be long winded, but the issue is simply this, you caused a stack overflow.

How you say? Well, check to see if you are using a Server.Transfer that transfers you to a page that then Transfers you back and forth, or even to yourself.

Have login code that checks to see if you are logged in? If not, then it bounces you to a login page. Maybe you put it in a master page. Well, if the login page uses the master page, it will just keep transferring itself to itself and you blow the stack.

Response.Redirect will give you a different error as the browser only jumps a low number of redirects before giving up. Server.Transfer uses the internal stack, so it blows up on the server itself.

Happy coding!