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 access legacy forms checkboxes and ActiveX checkboxes in Word using C#!

Apparently, doing this simple task is not well documented. None of my searches lead to anything useful, so here is what I wrote for how to handle the search for all checkboxes in a word document then set them all to false. Obviously, you can use this to get values, launch rockets, whatever it is you want to do.

[csharp]
//go through legacy fields.
foreach (FormField c in vstoDoc.FormFields)
{
try
{
if (c.Type == WdFieldType.wdFieldFormCheckBox)
{
if (c.CheckBox.Value)
c.CheckBox.Value = false;
}
}
catch { }
}

//go through the activex fields.
foreach(Field f in vstoDoc.Fields)
{
if (f.Type == WdFieldType.wdFieldOCX)
{
try
{
if (f.OLEFormat != null)
{
if(f.OLEFormat.ProgID.ToLowerInvariant().Contains("checkbox"))
{
if(f.OLEFormat.Object.Value)
f.OLEFormat.Object.Value = false;
}
}
}
catch { }
}

}
[/csharp]

I am sure you figured out my variable vstoDoc is the document. If not, well, McDonalds always need a new fry cook.

Happy Coding!

How to unshelve a shelveset from one branch into another branch!

I was doing a lot of work in our Main branch for a new version of our software. Lo and behold, this iteration requires we work on both the future and current version at the same time. Only a few of us are on the new version, therefore the Main branch code branched into a future version branch. Ugh. All my work sitting in a shelveset for the Main branch.

Moving it sounds painful to me. Luckily there is a really cool automated method provided by TFS. You simply need to deal with playing with the command line.

This guy did a good job giving an overview:

http://geekswithblogs.net/TarunArora/archive/2011/06/06/unshelve-shelveset-created-from-one-branch-to-another.aspx

This guy was easier for me to read:

http://chunkyinterface.wordpress.com/2012/02/17/migrating-shelvesets-between-branches-in-tfs/

tfpt unshelve - Unshelve into workspace with pending changes

Allows a shelveset to be unshelved into a workspace with pending changes.
Merges content between local and shelved changes. Allows migration of shelved
changes from one branch into another by rewriting server paths.

Usage: tfpt unshelve [shelvesetname[;username]] [/nobackup]
[/migrate /source:serverpath /target:serverpath]

shelvesetname The name of the shelveset to unshelve
/nobackup Skip the creation of a backup shelveset
/migrate Rewrite the server paths of the shelved items
(for example to unshelve into another branch)
/source:serverpath Source location for path rewrite (supply with /migrate)
/target:serverpath Target location for path rewrite (supply with /migrate)

Here is an example I used in action:

tfpt unshelve "Native Templates Work" /migrate /source:$/Source/Main /target:$/Source/Main-6.0

Happy coding!

How to programmatically change your Windows domain password using C# (.NET)

Ever wanted to write a program that would change your password for you? Why on earth would you want this? Well, imagine you have a password policy that requires you to change your password every X days. Well, maybe you like your password and think it dumb to have to keep changing it. Maybe you would forget your new password and resort to writing it down.

Ideally, you should come up with a good password to begin with, then changing it would not be really necessary. Unless of course you are under attack by the Chinese.

So, I wrote a program that changes the password in code. Moreover, it does it multiple times then the puts it back to the original. My problem solved. Here is the code for your education and amusement. Now that you know how to change your password, will you use this for purposes of good or evil? Try leaving the world a better place.

[csharp]
using System;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;
using System.Windows.Forms;

namespace KeepMyPassword
{
public partial class fKeepMyPassword : Form
{
public fKeepMyPassword()
{
InitializeComponent();
}

private void cmdChangePassword_Click(object sender, EventArgs e)
{
txtCurrentPassword.Enabled = false;
cmdChangePassword.Enabled = false;
try
{
ChangePassword(txtCurrentPassword.Text);
}
catch (Exception ex)
{
MessageBox.Show("An error occurred:" + ex.Message);
}

txtCurrentPassword.Enabled = true;
cmdChangePassword.Enabled = true;
}

private string currentPassword;
private void ChangePassword(string p)
{
var currentUser = WindowsIdentity.GetCurrent().Name;
currentPassword = p;
try
{
using (var context = new PrincipalContext(ContextType.Domain))
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, currentUser))
{
for (int ix = 0; ix < 10; ix++)
{
var newPassword = p + (char)(((int)’a’) + ix);
user.ChangePassword(currentPassword, newPassword);
currentPassword = newPassword;
}
user.ChangePassword(currentPassword, p);
currentPassword = p;
MessageBox.Show("Password has been reset and back to original");
}
//set back to normal
}
catch (Exception ex)
{
MessageBox.Show("An error occurred:" + ex.Message + "nYour password is now: " + currentPassword);
}
}
}
}

[/csharp]

Happy Coding!

 

KeepMyPassword <- you can download the compiled exe if you wish. Needs .NET 4.0 to run.

A better Dictionary/Hashtable. One that allows multiple entries per key.

Ever need the speed of a dictionary or hashtable, but also want to store more than one item with the same key? i.e. Maybe you have lists of items that need to be indexed against certain keys.

Maybe, Orders keyed by UserId. Well, enter the easy to use MultiDictionary. A class I put together to make it much easier to accomplish the goal. Speed and usability in one easy to use package.

[csharp]
public class MultiDictionary<K, V>
{
private Dictionary<K, List<V>> _dict = new Dictionary<K, List<V>>();

public void Add(K key, V val)
{
List<V> values;
if (!_dict.TryGetValue(key, out values))
{
values = new List<V>();
_dict.Add(key, values);
}
values.Add(val);
}

public bool TryGetValue(K key, out List<V> values)
{
return _dict.TryGetValue(key, out values);
}

public List<V> this[K key]
{
get
{
if( _dict.ContainsKey(key) )
return _dict[key];

return new List<V>();
}
set
{
_dict[key] = value;
}
}

public bool ContainsKey(K key)
{
return _dict.ContainsKey(key);
}

public IEnumerable<K> Keys
{
get { return _dict.Keys; }
}

public IEnumerable<List<V>> Values
{
get { return _dict.Values; }
}
}

public static class Extensions
{
public static MultiDictionary<TKey, TSource> ToMultiDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
MultiDictionary<TKey, TSource> md = new MultiDictionary<TKey, TSource>();
foreach (var item in source)
{
md.Add(keySelector(item), item);
}
return md;
}

}
[/csharp]
 

 

No more key not found exceptions either. If I can’t find the key, you get back an empty collection. You can still use the ContainsKey to determine if the item is absent. This just makes it so much easier to populate your entity objects with empty collections, instead of all the null checking.

Use just like a normal Dictionary, just expect a collection to be returned every time instead of one item.

Happy coding!
 

Continue or Break using Parallel.ForEach

You might be converting your normal foreach loop over to use the Parallel.ForEach syntax to improve performance in a thread safe loop.

You also probably have some break and continue statements.

Well, it took me a few to figure out how to deal with these. Turns out, it is simple.

When you converted your loop into a compatible definition for the Parallel.Foreach logic, you ended up making the statement body a lambda, right. Well, that is an action that gets called by the Parallel function.

So, pretend it is a method. When you are done, you just return. So, replace your continues and breaks with return statements.

Easy, right? Requires the mental shift from built in operators, to library function calls.

Happy Coding!

C# dynamic variable access slow as mollasses in the winter

I recently ran into an issue where I was using the dynamic keyword to simplify my access to Office apis. I had an object that could be a Word document or an Excel workbook. I needed to set the Saved property.

Well, it was easy to use a dynamic and just set it.

i.e.

dynamic doc = GetDocument();

doc.Saved=true;

A lot easier than type checking, casting and a couple if thens.

It turns out, not so much. The use of that small function cost me 8 seconds the first go round. It was much faster the second and third time, but 8 seconds?

I rewrote the code in incredulity as I figured, it must be the Saved property and not the dynamic. Wrong. After rewrite, it took 30ms at the most, 1-2ms hot.

So, wtf? I will research it later, but man. If you write an application that matters, be careful getting all dynamic.

 

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!

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!