Archive for the ‘C# (C-Sharp)’ Category.

How read the 64 bit registry from a 32 bit application or vice versa

I found out that I needed to read the 64 bit registry from a 32 bit app today.
Why you might ask?
Well, I need to get the RegisteredOrganization value from HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion and unfortunately Microsoft has a bug where the WOW6432 version of this key always says Microsoft, so a 32 bit application would always return Microsoft as the RegisteredOrganization, regardless of what the user entered when they installed the OS. This is hardly desired.
Note: This is also why all Visual Studio projects created in Windows 7 64 bit have Microsoft in the project’s Assembly Information. Change the WOW6432 version of the RegisteredOrganization and you fix this Visual Studio issue.
Well, turns out C# doesn’t have functionality until .NET 4, so prior to .NET 4, to choose the 64 bit hive when running a 32 bit app, so we have to do use a DLLImport and use RegOpenKeyEx, RegCloseKey, and RegQueryValueEx.
I don’t have this well commented, and it is not very newbie proof, but here are three different ways to do this. Hopefully you can understand one or more of these.

Example 1 – .NET 4 Example

Here is how to do this in .NET 4.
using Microsoft.Win32;

namespace Read64bitRegistryFrom32bitApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string value64 = string.Empty;
            string value32 = string.Empty;

            RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
            localKey = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
            if (localKey != null)
            {
                value64 = localKey.GetValue("RegisteredOrganization").ToString();
            }
            RegistryKey localKey32 = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
            localKey32 = localKey32.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
            if (localKey32 != null)
            {
                value32 = localKey32.GetValue("RegisteredOrganization").ToString();
            }
        }
    }
}

.NET 3.5 SP1 and Prior

This can also be done in .NET 3.5 and prior but it is not easy.
We have to do use a DLLImport and use RegOpenKeyEx, RegCloseKey, and RegQueryValueEx. Here are some examples.

Example 1 – A console application to read the 64 bit registry from a 32 bit application or vice versa

Here is the code in a simple one file project:
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Read64bitRegistryFrom32bitApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string value64 = GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "RegisteredOrganization");
            Console.WriteLine(value64);
            string value32 = GetRegKey32(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "RegisteredOrganization");
            Console.WriteLine(value32);
        }

        public enum RegSAM
        {
            QueryValue = 0x0001,
            SetValue = 0x0002,
            CreateSubKey = 0x0004,
            EnumerateSubKeys = 0x0008,
            Notify = 0x0010,
            CreateLink = 0x0020,
            WOW64_32Key = 0x0200,
            WOW64_64Key = 0x0100,
            WOW64_Res = 0x0300,
            Read = 0x00020019,
            Write = 0x00020006,
            Execute = 0x00020019,
            AllAccess = 0x000f003f
        }

        public static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
        public static UIntPtr HKEY_CURRENT_USER = new UIntPtr(0x80000001u);

        #region Member Variables
        #region Read 64bit Reg from 32bit app
        [DllImport("Advapi32.dll")]
        static extern uint RegOpenKeyEx(
            UIntPtr hKey,
            string lpSubKey,
            uint ulOptions,
            int samDesired,
            out int phkResult);

        [DllImport("Advapi32.dll")]
        static extern uint RegCloseKey(int hKey);

        [DllImport("advapi32.dll", EntryPoint = "RegQueryValueEx")]
        public static extern int RegQueryValueEx(
            int hKey, string lpValueName,
            int lpReserved,
            ref uint lpType,
            System.Text.StringBuilder lpData,
            ref uint lpcbData);
        #endregion
        #endregion

        #region Functions
        static public string GetRegKey64(UIntPtr inHive, String inKeyName, String inPropertyName)
        {
            return GetRegKey64(inHive, inKeyName, RegSAM.WOW64_64Key, inPropertyName);
        }

        static public string GetRegKey32(UIntPtr inHive, String inKeyName, String inPropertyName)
        {
            return GetRegKey64(inHive, inKeyName, RegSAM.WOW64_32Key, inPropertyName);
        }

        static public string GetRegKey64(UIntPtr inHive, String inKeyName, RegSAM in32or64key, String inPropertyName)
        {
            //UIntPtr HKEY_LOCAL_MACHINE = (UIntPtr)0x80000002;
            int hkey = 0;

            try
            {
                uint lResult = RegOpenKeyEx(RegHive.HKEY_LOCAL_MACHINE, inKeyName, 0, (int)RegSAM.QueryValue | (int)in32or64key, out hkey);
                if (0 != lResult) return null;
                uint lpType = 0;
                uint lpcbData = 1024;
                StringBuilder AgeBuffer = new StringBuilder(1024);
                RegQueryValueEx(hkey, inPropertyName, 0, ref lpType, AgeBuffer, ref lpcbData);
                string Age = AgeBuffer.ToString();
                return Age;
            }
            finally
            {
                if (0 != hkey) RegCloseKey(hkey);
            }
        }
        #endregion
    }
}

Example 2 – A static class to read the 64 bit registry from a 32 bit application or vice versa

Or if you want this in its own separate class, here is a static class you can add to your project.
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Read64bitRegistryFrom32bitApp
{
    public enum RegSAM
    {
        QueryValue = 0x0001,
        SetValue = 0x0002,
        CreateSubKey = 0x0004,
        EnumerateSubKeys = 0x0008,
        Notify = 0x0010,
        CreateLink = 0x0020,
        WOW64_32Key = 0x0200,
        WOW64_64Key = 0x0100,
        WOW64_Res = 0x0300,
        Read = 0x00020019,
        Write = 0x00020006,
        Execute = 0x00020019,
        AllAccess = 0x000f003f
    }

    public static class RegHive
    {
        public static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
        public static UIntPtr HKEY_CURRENT_USER = new UIntPtr(0x80000001u);
    }

    public static class RegistryWOW6432
    {
        #region Member Variables
        #region Read 64bit Reg from 32bit app
        [DllImport("Advapi32.dll")]
        static extern uint RegOpenKeyEx(
            UIntPtr hKey,
            string lpSubKey,
            uint ulOptions,
            int samDesired,
            out int phkResult);

        [DllImport("Advapi32.dll")]
        static extern uint RegCloseKey(int hKey);

        [DllImport("advapi32.dll", EntryPoint = "RegQueryValueEx")]
        public static extern int RegQueryValueEx(
            int hKey, string lpValueName,
            int lpReserved,
            ref uint lpType,
            System.Text.StringBuilder lpData,
            ref uint lpcbData);
        #endregion
        #endregion

        #region Functions
        static public string GetRegKey64(UIntPtr inHive, String inKeyName, String inPropertyName)
        {
            return GetRegKey64(inHive, inKeyName, RegSAM.WOW64_64Key, inPropertyName);
        }

        static public string GetRegKey32(UIntPtr inHive, String inKeyName, String inPropertyName)
        {
            return GetRegKey64(inHive, inKeyName, RegSAM.WOW64_32Key, inPropertyName);
        }

        static public string GetRegKey64(UIntPtr inHive, String inKeyName, RegSAM in32or64key, String inPropertyName)
        {
            //UIntPtr HKEY_LOCAL_MACHINE = (UIntPtr)0x80000002;
            int hkey = 0;

            try
            {
                uint lResult = RegOpenKeyEx(RegHive.HKEY_LOCAL_MACHINE, inKeyName, 0, (int)RegSAM.QueryValue | (int)in32or64key, out hkey);
                if (0 != lResult) return null;
                uint lpType = 0;
                uint lpcbData = 1024;
                StringBuilder AgeBuffer = new StringBuilder(1024);
                RegQueryValueEx(hkey, inPropertyName, 0, ref lpType, AgeBuffer, ref lpcbData);
                string Age = AgeBuffer.ToString();
                return Age;
            }
            finally
            {
                if (0 != hkey) RegCloseKey(hkey);
            }
        }
        #endregion

        #region Enums
        #endregion
    }
}
Here is an example of using this class.
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Read64bitRegistryFrom32bitApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string value64 = RegistryWOW6432.GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "RegisteredOrganization");
            string value32 = RegistryWOW6432.GetRegKey32(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "RegisteredOrganization");
        }
    }
}

Example 3 – Adding extension methods to the managed RegistryKey object that read the 64 bit registry from a 32 bit application or vice versa

You know what else is a cool idea? Making it an extension class to the normal managed registry C# code. So you can create a regular managed RegistryKey and then just call an extension function off it.
using System;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;

namespace Read64bitRegistryFrom32bitApp
{
    /// <summary>
    /// An extension class to allow a registry key to allow it to get the
    /// registry in the 32 bit (Wow6432Node) or 64 bit regular registry key
    /// </summary>
    public static class RegistryWOW6432
    {
        #region Member Variables
        #region Read 64bit Reg from 32bit app
        public static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
        public static UIntPtr HKEY_CURRENT_USER = new UIntPtr(0x80000001u);

        [DllImport("Advapi32.dll")]
        static extern uint RegOpenKeyEx(
            UIntPtr hKey,
            string lpSubKey,
            uint ulOptions,
            int samDesired,
            out int phkResult);

        [DllImport("Advapi32.dll")]
        static extern uint RegCloseKey(int hKey);

        [DllImport("advapi32.dll", EntryPoint = "RegQueryValueEx")]
        public static extern int RegQueryValueEx(
            int hKey, string lpValueName,
            int lpReserved,
            ref uint lpType,
            System.Text.StringBuilder lpData,
            ref uint lpcbData);
        #endregion
        #endregion

        #region Functions
        public static string GetRegKey64(this RegistryKey inKey, String inPropertyName)
        {
            string strKey = inKey.ToString();
            string regHive = strKey.Split('\\')[0];
            string regPath = strKey.Substring(strKey.IndexOf('\\') +1);
            return GetRegKey64(GetRegHiveFromString(regHive), regPath, RegSAM.WOW64_64Key, inPropertyName);
        }

        public static string GetRegKey32(this RegistryKey inKey, String inPropertyName)
        {
            string strKey = inKey.ToString();
            string regHive = strKey.Split('\\')[0];
            string regPath = strKey.Substring(strKey.IndexOf('\\') + 1);
            return GetRegKey64(GetRegHiveFromString(regHive), regPath, RegSAM.WOW64_32Key, inPropertyName);
        }

        private static UIntPtr GetRegHiveFromString(string inString)
        {
            if (inString == "HKEY_LOCAL_MACHINE")
                return HKEY_LOCAL_MACHINE;
            if (inString == "HKEY_CURRENT_USER")
                return HKEY_CURRENT_USER;
            return UIntPtr.Zero;
        }

        static public string GetRegKey64(UIntPtr inHive, String inKeyName, RegSAM in32or64key, String inPropertyName)
        {
            //UIntPtr HKEY_LOCAL_MACHINE = (UIntPtr)0x80000002;
            int hkey = 0;

            try
            {
                uint lResult = RegOpenKeyEx(inHive, inKeyName, 0, (int)RegSAM.QueryValue | (int)in32or64key, out hkey);
                if (0 != lResult) return null;
                uint lpType = 0;
                uint lpcbData = 1024;
                StringBuilder AgeBuffer = new StringBuilder(1024);
                RegQueryValueEx(hkey, inPropertyName, 0, ref lpType, AgeBuffer, ref lpcbData);
                string Age = AgeBuffer.ToString();
                return Age;
            }
            finally
            {
                if (0 != hkey) RegCloseKey(hkey);
            }
        }
        #endregion

        #region Enums
        public enum RegSAM
        {
            QueryValue = 0x0001,
            SetValue = 0x0002,
            CreateSubKey = 0x0004,
            EnumerateSubKeys = 0x0008,
            Notify = 0x0010,
            CreateLink = 0x0020,
            WOW64_32Key = 0x0200,
            WOW64_64Key = 0x0100,
            WOW64_Res = 0x0300,
            Read = 0x00020019,
            Write = 0x00020006,
            Execute = 0x00020019,
            AllAccess = 0x000f003f
        }
        #endregion
    }
}
Here is an example of using these extension functions.
using System;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;

namespace Read64bitRegistryFrom32bitApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string value64 = string.Empty;
            string value32 = string.Empty;
            RegistryKey localKey = Registry.LocalMachine;
            localKey = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
            if (localKey != null)
            {
                value32 = localKey.GetRegKey32("RegisteredOrganization");
                value64 = localKey.GetRegKey64("RegisteredOrganization");
            }
        }
    }
}
If anything is confusing please comment.
Resources:
  • RegOpenKeyEx Function – http://msdn.microsoft.com/en-us/library/ms724897%28v=VS.85%29.aspx
  • RegQueryValueEx Function – http://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx
  • http://www.pinvoke.net/default.aspx/advapi32/RegQueryValueEx.html
  • http://www.pinvoke.net/default.aspx/advapi32/RegOpenKeyEx.html
  • http://www.pinvoke.net/default.aspx/advapi32/RegCreateKeyEx.html
  • http://www.pinvoke.net/default.aspx/advapi32/RegCloseKey.html
  • http://stackoverflow.com/questions/1470770/accessing-registry-using-net
  • http://connect.microsoft.com/VisualStudio/feedback/details/400597/registeredorganization-reg-key-on-x64-vista-7

Copyright ® Rhyous.com – Linking to this post is allowed without permission and as many as ten lines of this page can be used along with this link. Any other use of this page is allowed only by permission of Rhyous.com.

C# Random Password Generator

BSD#

I needed to generate a random password in C# and I wanted to do it right.

I consulted a security expert and he mentioned that I should use a seed created with RNGCryptoServiceProvider so I did a search and quickly found this blog entry that had a good start.
http://eyeung003.blogspot.com/2010/09/c-random-password-generator.html

However, I needed three enhancements to this code.

  1. Store the password as a SecureString.
  2. Make upper case and lower case characters separate options.
  3. Guarantee that each character option would be used.

So I added these enhancements. Here are some notes about the enhancements:

  • SecureString – Since most password code requires strings instead of secure strings, even code such as a SQL connection strings, I cannot fault the original writer for leaving the password as a string. However, passwords should be stored as SecureString objects as much as possible. With my enhancements, it still flips back and forth between secure string and string, but hopefully is a SecureString as often as possible.
  • I include the ability to convert the SecureString to a string, because of the issue mentions in the previous bullet point.
  • I separated the character options. I also added back the characters that were listed as confusing. If someone thinks these are confusing, use a font where they are not confusing or remove them again.
  • Using all options – I guarantee that each option is used. The first characters in the password are chosen, one from each option, in a random order. I still didn’t like that, I created a scramble but in order to create the scramble, I had pull the password out as a string to get each character to scramble.
  • I also added some exception objects to make exceptions clear if there are any.
  • I also tested this on C# (Mono) on FreeBSD and it works.

Ok, here is the new version that includes my enhancements to the original code.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;

namespace System.Security
{
    public enum CharacterTypes : byte
    {
        Alpha_Lower = 1,
        Alpha_Upper = 2,
        Alpha_Upper_and_Lower = 3,
        Digit = 4,
        AlphaLowerNumeric = Digit + Alpha_Lower,        //  5 (4+1)
        AlphaUpperNumeric = Digit + Alpha_Upper,        //  6 (4+2)
        AlphaNumeric = Alpha_Upper_and_Lower + Digit,   //  7 (4+3)
        Special = 8,
        // You could add more character types here such as Alpha_Lower  + Special, but why?
        AlphaNumericSpecial = AlphaNumeric + Special    // 15 (8+7)
    }

    public class RandomPasswordGenerator
    {
        // Define default password length.
        private static int DEFAULT_PASSWORD_LENGTH = 16;

        private static PasswordOption AlphaLC = new PasswordOption() { Characters = "abcdefghijklmnopqrstuvwxyz", Count = 0 };
        private static PasswordOption AlphaUC = new PasswordOption() { Characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", Count = 0 };
        private static PasswordOption Digits = new PasswordOption() { Characters = "0123456789", Count = 0 };
        private static PasswordOption Specials = new PasswordOption() { Characters = "!@#$%^&*()~<>?", Count = 0 };

        #region Overloads

        /// <summary>
        /// Generates a random password with the default length.
        /// </summary>
        /// <returns>Randomly generated password.</returns>
        public static SecureString Generate()
        {
            return Generate(DEFAULT_PASSWORD_LENGTH,
                            CharacterTypes.AlphaNumericSpecial);
        }

        /// <summary>
        /// Generates a random password with the default length.
        /// </summary>
        /// <returns>Randomly generated password.</returns>
        public static SecureString Generate(CharacterTypes option)
        {
            return Generate(DEFAULT_PASSWORD_LENGTH, option);
        }

        /// <summary>
        /// Generates a random password with the specified length.
        /// </summary>
        /// <returns>Randomly generated password.</returns>
        public static SecureString Generate(int passwordLength)
        {
            return Generate(passwordLength,
                            CharacterTypes.AlphaNumericSpecial);
        }

        /// <summary>
        /// Generates a random password.
        /// </summary>
        /// <returns>Randomly generated password.</returns>
        public static SecureString Generate(int passwordLength,
                                      CharacterTypes option)
        {
            return GeneratePassword(passwordLength, option);
        }

        #endregion

        /// <summary>
        /// Generates the password.
        /// </summary>
        /// <returns></returns>
        private static SecureString GeneratePassword(int passwordLength, CharacterTypes option)
        {
            // Password length must at lest be 1 character long
            if (passwordLength < 1)
                throw new InvalidPasswordLengthException();

            // Character type must be a valid CharacterType
            if (option < CharacterTypes.Alpha_Lower || option > CharacterTypes.AlphaNumericSpecial)
                throw new InvalidPasswordCharacterTypeException();

            PasswordOptions passwordOptions = GetCharacters(option);

            // Make sure the password is long enough.
            // For example CharacterTypes.AlphaNumericSpecial
            // requires at least 4 characters: 1 upper, 1 lower, 1 digit, 1 special
            if (passwordLength < passwordOptions.Count)
                throw new InvalidPasswordLengthException();

            SecureString securePassword = new SecureString();
            string passwordChars = String.Empty;

            foreach (PasswordOption po in passwordOptions)
            {
                passwordChars += po.Characters;
            }

            if (string.IsNullOrEmpty(passwordChars))
                return null;

            var random = RandomSeedGenerator.GetRandom();

            for (int i = 0; i < passwordLength; i++)
            {
                int index;
                char passwordChar;
                if (!passwordOptions.AllOptionsAreUsed)
                {
                    PasswordOption po = passwordOptions.GetUnusedOption();
                    index = random.Next(po.Characters.Length);
                    passwordChar = po.Characters[index];
                }
                else
                {
                    index = random.Next(passwordChars.Length);
                    passwordChar = passwordChars[index];
                }

                securePassword.AppendChar(passwordChar);
            }

            return securePassword;
        }

        private int GetOptionsUsed()
        {
            int ret = 0;
            foreach (CharacterTypes option in Enum.GetValues(typeof(CharacterTypes)))
            {

            }
            return ret;
        }

        /// <summary>
        /// Gets the characters selected by the option
        /// </summary>
        /// <returns></returns>
        private static PasswordOptions GetCharacters(CharacterTypes option)
        {
            PasswordOptions list = new PasswordOptions();
            switch (option)
            {
                case CharacterTypes.Alpha_Lower:
                    list.Add(AlphaLC);
                    break;
                case CharacterTypes.Alpha_Upper:
                    list.Add(AlphaUC);
                    break;
                case CharacterTypes.Alpha_Upper_and_Lower:
                    list.Add(AlphaLC);
                    list.Add(AlphaUC);
                    break;
                case CharacterTypes.Digit:
                    list.Add(Digits);
                    break;
                case CharacterTypes.AlphaNumeric:
                    list.Add(AlphaLC);
                    list.Add(AlphaUC);
                    list.Add(Digits);
                    break;
                case CharacterTypes.Special:
                    list.Add(Specials);
                    break;
                case CharacterTypes.AlphaNumericSpecial:
                    list.Add(AlphaLC);
                    list.Add(AlphaUC);
                    list.Add(Digits);
                    list.Add(Specials);
                    break;
                default:
                    break;
            }
            return list;
        }
    }

    public static class RandomSeedGenerator
    {
        /// <summary>
        /// Gets a random object with a real random seed
        /// </summary>
        /// <returns></returns>
        public static Random GetRandom()
        {
            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] randomBytes = new byte[4];

            // Generate 4 random bytes.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(randomBytes);

            // Convert 4 bytes into a 32-bit integer value.
            int seed = (randomBytes[0] & 0x7f) << 24 |
                        randomBytes[1] << 16 |
                        randomBytes[2] << 8 |
                        randomBytes[3];

            // Now, this is real randomization.
            return new Random(seed);
        }
    }

    public class PasswordOption
    {
        public int Count { get; set; }
        public String Characters { get; set; }
    }

    public class PasswordOptions : List<PasswordOption>
    {
        public bool AllOptionsAreUsed
        {
            get
            {
                foreach (PasswordOption po in this)
                {
                    if (po.Count < 1)
                        return false;
                }
                return true;
            }
        }

        public PasswordOption GetUnusedOption()
        {
            PasswordOptions options = new PasswordOptions();
            foreach (PasswordOption po in this)
            {
                if (po.Count < 1)
                    options.Add(po);
            }
            if (options.Count < 1)
                return null;

            var random = RandomSeedGenerator.GetRandom();
            int optionIndex = random.Next(options.Count);
            return options[optionIndex];
        }
    }

    public class InvalidPasswordLengthException : ArgumentException { }
    public class InvalidPasswordCharacterTypeException : ArgumentException { }

    public static class SecureStringExtender
    {
        public static string ConvertToPlainTextString(this SecureString securePassword)
        {
            if (securePassword == null)
                throw new ArgumentNullException("securePassword");

            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }

        public static SecureString Scramble(this SecureString securePassword)
        {
            SecureString retSS = securePassword;
            Random random = RandomSeedGenerator.GetRandom();
            int moves = random.Next(securePassword.Length, securePassword.Length * 2);
            for (int i = 0; i < moves; i++)
            {
                int origIndex = random.Next(securePassword.Length);
                int newIndex = random.Next(securePassword.Length);
                char c = retSS.GetAt(origIndex);
                retSS.InsertAt(newIndex, c);
            }
            return retSS;
        }

        public static Char GetAt(this SecureString securePassword, int index)
        {
            if (securePassword.Length < index)
                throw new ArgumentException("The index parameter must not be greater than the string's length.");
            if (index < 0)
                throw new ArgumentException("The index must be 0 or greater.");
            return securePassword.ConvertToPlainTextString().Substring(index, 1).ToCharArray()[0];
        }
    }
}

Now if you want to make a simple command line executable that uses the code above, just create a new console project and call this line:

Console.WriteLine(RandomPasswordGenerator.Generate().ConvertToPlainTextString());

I added more code to handle command line parameters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;

namespace ConsoleApplication2
{
    class Program
    {
        private static int PasswordLength;
        private static String Characters;

        static void Main(string[] args)
        {
            if (args.Length > 2)
            {
                ShowArgs();
                return;
            }

            if (args.Length > 0)
            {
                foreach (char c in args[0])
                {
                    if (char.IsDigit(c))
                    {
                        ShowArgs();
                        return;
                    }
                }
                PasswordLength = Convert.ToInt32(args[0]);
            }

            if (args.Length == 2)
                Characters = args[1];

            Console.WriteLine(RandomPasswordGenerator.Generate().ConvertToPlainTextString());
        }

        private static void ShowArgs()
        {
            String fullExeNameAndPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            String ExeName = System.IO.Path.GetFileName(fullExeNameAndPath);

            Console.WriteLine("Usage: " + ExeName + " [int] [string]");
            Console.WriteLine("[int] - The length of the password.  By default it is 11.");
            Console.WriteLine("[string] - The characters to use for the password.  By default it is alphanumeric case sensitive.");
        }
}

Hope you find this helpful. If you find flaws, please comment!

C# (Mono) – Reading and writing to a text file

C# (Mono) on FreeBSD
File access is made simple with C# (Mono) on FreeBSD.

Reading a text file with C# (Mono)

To read a file, use a StreamReader object. However, it is easy if you don’t do a new StreamWriter("File.txt") but instead use File.OpenText("File.txt") to create the StreamReader. Once you have the stream, you just need to run the stream’s ReadToEnd() function.

Here is a snippet to read a text file as a string.

// Open the file into a StreamReader
StreamReader file = File.OpenText("SomeFile.txt");
// Read the file into a string
string s = file.ReadToEnd();

Now that you have the text file as a string, you can manipulate the string as you desire.

Writing to a text file with C# (Mono)

To write a text file, use StreamWriter.

string str = "Some text";
// Hook a write to the text file.
StreamWriter writer = new StreamWriter("SomeFile.txt");
// Rewrite the entire value of s to the file
writer.Write(str);

You can also just add a line to the end of the file as follows:

string str = "Some text";
// Hook a write to the text file.
StreamWriter writer = new StreamWriter("SomeFile.txt");
// Rewrite the entire value of s to the file
writer.WriteLine(str);

Example for learning

An example of these in a little project file made with MonoDevelop.

using System;
using System.IO;

namespace FileAccess
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			string FileName="TestFile.txt";

			// Open the file into a StreamReader
			StreamReader file = File.OpenText(FileName);
			// Read the file into a string
			string s = file.ReadToEnd();
			// Close the file so it can be accessed again.
			file.Close();

			// Add a line to the text
			s  += "A new line.\n";

			// Hook a write to the text file.
			StreamWriter writer = new StreamWriter(FileName);
			// Rewrite the entire value of s to the file
			writer.Write(s);

			// Add a single line
			writer.WriteLine("Add a single line.");

			// Close the writer
			writer.Close();
		}
	}
}

Well, this should get you started.

A Visual Studio snippet for a class with #region sections

Here is a simple snippet to add to Visual Studio if you want:

Place it here for Visual Studio 2010: C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#

<?xml version="1.0" encoding="utf-8" ?>
<codeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<codeSnippet Format="1.0.0">
		<header>
			<title>classr</title>
			<shortcut>classr</shortcut>
			<description>Code snippet for class with prepopulated regions.</description>
			<author>Microsoft Corporation</author>
			<snippetTypes>
				<snippetType>Expansion</snippetType>
				<snippetType>SurroundsWith</snippetType>
			</snippetTypes>
		</header>
		<snippet>
			<declarations>
				<literal>
					<id>name</id>
					<toolTip>Class name</toolTip>
					<default>MyClass</default>
				</literal>
			</declarations>
			<code Language="csharp"><!&#91;CDATA&#91;class $name$
	{
	#region Member Fields
	#endregion

	#region Constructor
	/// <summary>
	/// The default constructor
	/// </summary>
	public $name$()
	{
	}
	#endregion

	#region Properties
	#endregion

	#region Functions
	#endregion

	#region enums
	#endregion
		$selected$$end$
	}&#93;&#93;>
			</code>
		</snippet>
	</codeSnippet>
</codeSnippets>

A Progress Bar using WPF's Progress Bar Control, BackgroundWorker, and MVVM

Hey all,

WPF provides a ProgressBar control.  But there isn’t really a manual for it, especially if you want to follow MVVM.

So I am going to make a little application that counts from zero to ten and tracks the progress.  You are going to see when it is OK to use the foreground and when it is not OK but better to use BackgroundWorker.

While much of this code may be production ready, you should be aware that this code intentionally implements a foreground process that is an example of what not to do.

Prerequisites

  • Visual Studio

Step 1 – Create a new WPF Application Project

  1. In Visual Studio, create a new Solution and choose WPF Application
  2. Give it a name.
  3. Hit OK.

Step 2 – Add two base MVVM files

There are two basic classes used for MVVM.

  • RelayCommand
  • ViewModelBase

These are found on different blogs and different posts all over the internet, so I would say they are public domain, or free and unlicensed.

  1. Download them zipped here. MVVM
  2. Extract the zip file.
  3. Add the MVVM folder and the two class under it to your project.

Step 3 – Create a ProgressBarViewModel class

  1. Create a new Class called ProgressBarViewModel.
  2. Adding a using MVVM statement at the top.
  3. Make the class inherit ViewModelBase.
    class ProgressBarViewModel : ViewModelBase
    {
    }
    

This will be populated as we create our View.

Step 4 – Design the GUI in MainWindow.xaml

Ok, so lets create the GUI.

  1. Add a local reference. (Line 4)
  2. Add a ProgressBarViewModel object as a resource. (Lines 6-8)
  3. Create a StackPanel in the default Grid to put everything in. (Line 10)
  4. Add a one character label in great big text to display our number. (Line 11)
  5. Add a ProgressBar element. (Line 12)
  6. Create buttons to manipulate the label. (Lines 13-16)
  7. Configure the DataContext of each element to be the the ProgressBarViewModel using the Key PBVM we gave it when we added it as a resource. (Lines 11-16)
  8. Think of and create Binding Paths for each element. Yes, we can basically just make these Path names up and add them to the ProgressBarViewModel later. (Lines 11-16)

Here is the XAML.

<Window x:Class="WPFProgressBarUsingBackgroundWorker.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFProgressBarUsingBackgroundWorker"
        Title="MainWindow" >
    <Window.Resources>
        <local:ProgressBarViewModel x:Key="PBVM" />
    </Window.Resources>
    <Grid>
        <StackPanel>
            <Label Content="{Binding Path=Value}" DataContext="{StaticResource ResourceKey=PBVM}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Name="labelNumberCounter" VerticalAlignment="Center" FontSize="175" />
            <ProgressBar Margin="0,3,0,3" Height="20" Name="progressBar" Value="{Binding Path=Value}" DataContext="{StaticResource ResourceKey=PBVM}" Minimum="{Binding Min}" Maximum="{Binding Max}"/>
            <Button Command="{Binding Path=IncrementBy1}" Content="Manual Count" DataContext="{StaticResource PBVM}" Height="23" IsEnabled="{Binding Path=IsNotInProgress}" Name="button1" Width="Auto" />
            <Button Margin="0,3,0,3" IsEnabled="{Binding Path=IsNotInProgress}" Command="{Binding Path=IncrementAsForegroundProcess}" DataContext="{StaticResource ResourceKey=PBVM}" Content="Count to 10 as a foreground process" HorizontalAlignment="Stretch" Height="23" Name="buttonForeground" VerticalAlignment="Top" Width="Auto" />
            <Button Margin="0,3,0,3" IsEnabled="{Binding Path=IsNotInProgress}" Command="{Binding Path=IncrementAsBackgroundProcess}" DataContext="{StaticResource ResourceKey=PBVM}" Content="Count to 10 as a background process" HorizontalAlignment="Stretch" Height="23" Name="buttonBackground" VerticalAlignment="Top" Width="Auto" />
            <Button Command="{Binding Path=ResetCounter}" Content="Reset" DataContext="{StaticResource PBVM}" Height="23" IsEnabled="{Binding Path=IsNotInProgress}" Name="buttonReset" Width="Auto" />
        </StackPanel>
    </Grid>
</Window>

Step 5 – Populate the ProgressBarViewModel

  1. Create the following member fields.
    • Double _Value;
    • bool _IsInProgress;
    • int _Min = 0;
    • int _Max = 10;
  2. Create a matching property for each member field. Make sure that in the set function of the property you call NotifyPropertyChanged(“PropertyName”).
  3. Create a function for each of the four buttons and populate these functions with the code. See the functions in the code below:
    • Increment()
    • IncrementProgressForeground()
    • IncrementProgressBackgroundWorker()
    • Reset()
  4. Create and populate the functions for the BackgroundWorker.
    • worker_DoWork
    • worker_RunWorkerCompleted()
  5. Create the following RelayCommand instances as member Fields.
    • RelayCommand _Increment;
    • RelayCommand _IncrementBy1;
    • RelayCommand _IncrementAsBackgroundProcess;
    • RelayCommand _ResetCounter;
  6. Create matching ICommand properties for each RelayCommand, instantiating the RelayCommand with the correct function.

Here is the code for the ProgressBarViewModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Text;
using System.Windows.Input;
using MVVM;

namespace WPFProgressBarUsingBackgroundWorker
{
    class ProgressBarViewModel : ViewModelBase
    {
        #region Member Fields
        Double _Value;
        bool _IsInProgress;
        int _Min = 0, _Max = 10;
        #endregion

        #region Member RelayCommands that implement ICommand
        RelayCommand _Increment;
        RelayCommand _IncrementBy1;
        RelayCommand _IncrementAsBackgroundProcess;
        RelayCommand _ResetCounter;
        #endregion

        #region Constructors
        /// <summary>
        /// The default constructor
        /// </summary>
        public ProgressBarViewModel()
        {
        }
        #endregion

        #region Properties
        /// <summary>
        /// Used to mark if the counter is in progress so the counter can't be started
        /// while it is already running.
        /// </summary>
        public bool IsInProgress
        {
            get { return _IsInProgress; }
            set
            {
                _IsInProgress = value;
                NotifyPropertyChanged("IsInProgress");
                NotifyPropertyChanged("IsNotInProgress");
            }
        }

        public bool IsNotInProgress
        {
            get { return !IsInProgress; }
        }

        public int Max
        {
            get { return _Max; }
            set { _Max = value; NotifyPropertyChanged("Max"); }
        }

        public int Min
        {
            get { return _Min; }
            set { _Min = value; NotifyPropertyChanged("Min"); }
        }

        /// <summary>
        /// This is the Value.  The Counter should display this.
        /// </summary>
        public Double Value
        {
            get { return _Value; }
            set
            {
                if (value <= _Max)
                {
                    if (value >= _Min) { _Value = value; }
                    else { _Value = _Min; }
                }
                else { _Value = _Max; }
                NotifyPropertyChanged("Value");
            }
        }

        #region ICommand Properties
        /// <summary>
        /// An ICommand representation of the Increment() function.
        /// </summary>
        public ICommand IncrementBy1
        {
            get
            {
                if (_IncrementBy1 == null)
                {
                    _IncrementBy1 = new RelayCommand(param => this.Increment());
                }
                return _IncrementBy1;
            }
        }

        /// <summary>
        /// An ICommand representation of the IncrementProgressForegroundWorker() function.
        /// </summary>
        public ICommand IncrementAsForegroundProcess
        {
            get
            {
                if (_Increment == null)
                {
                    _Increment = new RelayCommand(param => this.IncrementProgressForeground());
                }
                return _Increment;
            }
        }

        /// <summary>
        /// An ICommand representation of the IncrementProgressForeground() function.
        /// </summary>
        public ICommand IncrementAsBackgroundProcess
        {
            get
            {
                if (_IncrementAsBackgroundProcess == null)
                {
                    _IncrementAsBackgroundProcess = new RelayCommand(param => this.IncrementProgressBackgroundWorker());
                }
                return _IncrementAsBackgroundProcess;
            }
        }

        /// <summary>
        /// An ICommand representation of the Reset() function.
        /// </summary>
        public ICommand ResetCounter
        {
            get
            {
                if (_ResetCounter == null)
                {
                    _ResetCounter = new RelayCommand(param => this.Reset());
                }
                return _ResetCounter;
            }
        }
        #endregion ICommand Properties
        #endregion

        #region Functions
        /// <summary>
        /// This function manually increments the counter by 1 in the foreground.
        /// Because it only increments by one, the WPF control bound to Value will
        /// display the new value when this function completes.
        /// </summary>
        public void Increment()
        {
            // If we are in progress already, don't do anything
            if (IsInProgress)
                return;

            // If the value is already at 10, start the counting over.
            if (Value == 10)
                Reset();
            Value++;
        }

        /// <summary>
        /// This function starts the counter as a foreground process.
        /// This doesn't work.  It counts to 10 but the UI is not updated
        /// until the function completes.  This is especially problematic
        /// since the buttons are left enabled.
        /// </summary>
        public void IncrementProgressForeground()
        {
            // If we are in progress already, don't do anything
            if (IsInProgress)
                return;
            Reset();
            IsInProgress = true;
            Value = 0;
            for (int i = _Min; i < _Max; i++)
            {
                Value++;
                Thread.Sleep(1000);
            }
            IsInProgress = false;
        }

        /// <summary>
        /// This starts the counter as a background process.
        /// </summary>
        public void IncrementProgressBackgroundWorker()
        {
            // If we are in progress already, don't do anything
            if (IsInProgress)
                return;

            Reset();
            IsInProgress = true;
            BackgroundWorker worker = new BackgroundWorker();
            // Configure the function that will run when started
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);

            /*The progress reporting is not needed with this implementation and is therefore
            commented out.  However, in your more complex application, you may have a use for
            for this.

            //Enable progress and configure the progress function
            worker.WorkerReportsProgress = true;
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);

            */

            // Configure the function to run when completed
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

            // Launch the worker
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// This is the function that is called when the worker is launched with the RunWorkerAsync() call.
        /// </summary>
        /// <param name="sender">The worker as Object, but it can be cast to a worker.</param>
        /// <param name="e">The DoWorkEventArgs object.</param>
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = _Min; i < _Max; i++)
            {
                Value++;
                Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// This worker_ProgressChanged function is not in use for this project. Thanks to INotifyPropertyChanged, this is
        /// completely unnecessary.
        /// </summary>
        /// <param name="sender">The worker as Object, but it can be cast to a worker.</param>
        /// <param name="e">The ProgressChangedEventArgs object.</param>
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // Does nothing yet
            throw new NotImplementedException();
        }

        /// <summary>
        /// This worker_RunWorkerCompleted is called when the worker is finished.
        /// </summary>
        /// <param name="sender">The worker as Object, but it can be cast to a worker.</param>
        /// <param name="e">The RunWorkerCompletedEventArgs object.</param>
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            IsInProgress = false;
        }

        /// <summary>
        /// This function resets the Value of the counter to 0.
        /// </summary>
        private void Reset()
        {
            Value = Min;
        }
        #endregion
    }
}

I’m sorry that this is not the most Newbie proof post. But I tried to comment like crazy the code so you can get through it.

Now if you find a discrepancy in my walk-through, please comment. Also, if it is easier for you to just download the project, here it is:
WPFProgressBarUsingBackgroundWorker.zip

Russian Government going Open Source…and the future

Well, I have seen governments claim they are going to open source before, but not from Russia, and not with such a realistic plan to migrate over a few years.

Here is a link to the article via Google translate:

Putin ordered the transfer of power on Linux

The now

Business drives software development.  Open Source communities help, but even today much of the ongoing development for Linux is driven by businesses such as Red Hat and Novell and others.  If you think your Linux code is being written by unpaid developers in their spare time, you are somewhat correct but only partially.  Most changes are made by developers who are paid.

While communities are nice, they can’t match the hours or output of experienced developers working forty to sixty hours a week.

Looking Ahead…the Apps…and C# (Mono)

The more open source is used in business, the more development power it will have.  But it is not the open source Operatings Systems that prevent people from moving to Linux or BSD.  Ubuntu, SUSE, Fedora, CentOS, PC-BSD, and numerous others are all very usable desktops that are user friendly.  It is the software that runs on them that everyone is waiting for.

The market is already there to make millions extra if you application runs cross platform, one Windows, MAC, Linux, and BSD.

But most the applications written for Windows, the business desktop of today, are using .NET Framework. So naturally those companies are going to want to make their code cross platform.  And they are going to find it is easier than they thought to move their applications between platforms using C#.  I have recently decided that C# is the future of applications on all platforms.

Some MAC and Linux users don’t like Microsoft and will fight off the idea of a Microsoft provided development platform such as C# (Mono) on their systems.  But when a corporation decides that you must run software X, and software X requires .NET, and you have to either give up your MAC or Linux box for a Windows box, or use C# (Mono), then users will come around.

If you are a company writing software for Windows only today and using C#, you need to take a look at Mono. Even if the return on investment of developing a C# (Mono) based version of your product is a slight loss to break even, it is an investment in the future.  Once written, maintenance costs will be less than the original development costs and that slight loss to break even margin will turn to a small profit.  And with the experience, you next app will migrate to C# (Mono) that much easier and soon, all you apps will run anywhere that C# (Mono) can run.

This is going to take off in a way Java hasn’t because developers for windows prefer and will continue to prefer .NET over Java.  And when it comes to business apps, Java just isn’t the language of choice.  Business applications are written in C#.

Running Pinta on FreeBSD – A C# (Mono) Image Editor

I wanted to continue with the C# (Mono) on FreeBSD theme this week. The next C# (Mono) post for FreeBSD is simply running a .C# (Mono) app on FreeBSD.

My first thought was this, “I wonder if there is a mono version of Paint.NET?”. Paint.NET is my favorite image editor for Windows.

After a quick search, I found the Pinta project, which is a Mono clone of Paint.NET.

Installing Pinta on FreeBSD

So anyway, the steps for running on FreeBSD are quite simple.  This is a preview of my next FreeBSD Friday post, as I will continue the mono them to promote you app.

  1. Follow this post to get mono on FreeBSD.
    http://rhyous.com/2010/12/10/c-mono-on-freebsd/
  2. Download the Pinta tarball: http://pinta-project.com/download
    $ fetch http://github.com/downloads/jpobst/Pinta/pinta-0.5.tar.gz
  3. Extract it:
    $ tar -xzf pinta-0.5.tar.gz
  4. Change to the directory:
    $ cd pinta-0.5
  5. Run configure.
    $ ./configure
  6. This failed the first time I ran it because I didn’t have a .tmp directory in my home directory. So I create one.
    $ mkdir ~/.tmp
  7. Run make.
    $ make
  8. Then as root or with sudo, run make install.
    # make install
  9. Make the shell rehash the commands in PATH.
    $ rehash
    – or depending on your shell –
    $ hash -r
  10. Now just run pinta.
    $pinta

    Warning! I had to remove those annoying ^M characters from the /usr/local/bin/pinta file to get it to run. Otherwise, I got this error:
    : No such file or directory

  11. I use KDE so I was able to add a menu item for pinta easily.  An installed logo would be nice. I found one in the source at this path: pinta-0.5/xdg/96×96/pinta.png.  I copied it to /usr/local/lib/pinta.

More information

Pinta installs the following files

/usr/local/bin/pinta
/usr/local/lib/pinta/

/usr/local/lib/pinta/Pinta.Core.dll
/usr/local/lib/pinta/Pinta.Effects.dll
/usr/local/lib/pinta/Pinta.Gui.Widgets.dll
/usr/local/lib/pinta/Pinta.Resources.dll
/usr/local/lib/pinta/Pinta.Tools.dll
/usr/local/lib/pinta/Pinta.exe

I added manually added the log so I had something to put in the KDE menu.
/usr/local/lib/pinta/pinta.png

The first file, /usr/local/bin/pinta, is a shell script that runs this:
#!/bin/sh
exec /usr/local/bin/mono /usr/local/lib/pinta/Pinta.exe “$@”

The other files are the application. It is a little weird to see .exe and .dll files on FreeBSD, but I’ll get over it.

C# (Mono) on FreeBSD

Well, if you have read my blog at all, you will realize that I have a developer job writing in C# on Windows, but it is my personal hobby to use FreeBSD.

I am very excited about Mono. I love the C# language. I also love FreeBSD.

I am going to go ahead and say something bold. Few people know realize this yet, but the ability to code in C# on open source platforms is going to be the single most important feature in the coming years. It will eventually be a standard library that will exist or be one of the first items installed on every system.

For more information:

http://www.mono-project.com/Mono:FreeBSD
Packaging for Mono and related applications on FreeBSD (http://www.freebsd.org) is handled by the BSD# Project. The purpose of this project is to maintain the existing Mono/C# ports in the FreeBSD ports tree, port new applications, and work on resolving FreeBSD specific issues with Mono. BSD# is entirely user supported and is not an official FreeBSD or Mono project.

For Licensing information:

http://www.mono-project.com/Licensing

Installing Mono

Mono is a port and as always a port is easy to install on FreeBSD.

#
#
cd /usr/ports/lang/mono
make BATCH=yes install

Compiling Hello World in Mono

The mono compiler is gmcs. It is simple to compile C# code.

  1. Create a new file called hw.cs. C# class files end in .cs.
  2. Add this text to the file:
    using System;
    
    namespace HelloWord
    {
         class HelloWord
        {
            static void Main(string[] args)
            {
                System.Console.WriteLine("Hello World");
            }
        }
    }
    
  3. Save the file.
  4. Compile the code to create an hw.exe program.
    # gmcs hw.cs

Running a Mono Program

Mono programs must be run using the “mono” command.

# mono hw.exe
Hello World

A Mono IDE: MonoDevelop

There is an IDE for Mono called MonoDevelop. MonoDevelop is a port and as always a port is easy to install on FreeBSD.

#
#
cd /usr/ports/devel/monodevelop
make BATCH=yes install

The Mono Develop port integrated with KDE to add itself to the KDE menu under Applications | Development | MonoDevelop. So you can run it from there.

This IDE allows you to create C# solutions. It is possible to run compile them on FreeBSD and run them on Windows, or compile them on Windows and run them on FreeBSD.

Is It Really Cross Platform

C# and Mono are supposed to be cross platform. So I can write it in Windows using Visual Studio or I can write in FreeBSD using Mono Develop and either way it should run on both Windows and FreeBSD and any other platform that supports mono.

So here are the results of my quick tests:

Test 1 – Does the Hello World app run in Windows.

Yes. I copied the file to a Windows 7 64 bit box and ran it. It worked.

Test 2 – Does a GTK# 2.0 Project run in Windows

No. I created a GTK# 2.0 project on FreeBSD in Mono Develop, and didn’t add anything to it, I just compiled it. I copied the file to windows and ran it. However, it crashed.

Supposedly you have to install the GTK# for .NET on the windows box, but it still didn’t work.

Test 3 – Does a Windows Form Application compiled in Visual Studio 2010 in Window 7 run on FreeBSD

Not at first. I created a basic Windows Form application, and didn’t add anything to it, I just compiled it. I copied it to FreeBSD and ran it. It crashed. However, by default .NET 4.0 is used.

Yes, if compiled with .NET 3.5 or earlier. I changed the project to use .NET 3.5 and tried again. It ran flawlessly.

Test 4 – Does a Windows Presentation Foundation project compiled in Visual Studio 2010 in Window 7 run on FreeBSD

No. There is PresentationFramework assembly so the application crashes immediately. I tried multiple .NET versions.

Note: I didn’t really test much more than the basics. I just created new projects, left them as is and tried them. It would be interesting to see a more fully developed application tested and working on both platform and to know what issues were encountered in doing this.

No WPF

Unfortunately there is no WPF and no plans for it. Of course, WPF stand for Windows Presentation Foundation, and so the who “Windows” part of that might need to be changed to something like XPF, Xorg Presentation foundation.

However since there is Moonlight, which is to Silverlight as Mono is to C# and .NET, and Silverlight is a subset of WPF, I have to assume that WPF will arrive in mono eventually, even if it is by way of Moonlight first.

WPF databinding to methods encapulated in an ICommand

Databinding in WPF allows binding the Command property to methods encapulated in an ICommand. By creating an ICommand object to hold an event function, the Command value can bind to the event function as an ICommand.

The goal of Model-View-ViewModel is to have zero code in the code behind of a WPF Control Instead, everything the WPF Control does happens using databinding.

While this article will show you how to do this, you be left a little fuzzy as to understanding of the implementation. It may take some time and research to fully understand everything this is doing. Understand that methods can be objects, and this is a process to turn a method object into an ICommand so it can be using in WPF for databinding.

Preparation and Prereqs

You should have Visual Studio 2008/2010.

In Visual Studio, create a new WPF Application project and give it a name.

Step 1 – Creating an new class that inherits from ICommand

  1. In your new project in Visual Studio, add a new class called RelayCommand.
    Note: It can be named anything, but since that is the name used by Microsoft when discussing MVVM, I will use the same name.
  2. Change the using statements to implement the following : System, System.Diagnostic, System.Windows.Input
  3. Make the new RelayComand class public.
  4. Make the new RelayCommand class implement ICommand.
    using System;
    using System.Windows.Input;
    
    namespace WpfDataBindingToICommand
    {
        public class RelayCommand : ICommand
        {
            #region Constructors
            public RelayCommand()
            {
            }
            #endregion
        }
    }
    
  5. Right-click on the ICommand text and choose Implement Interface | Implement Interface. This adds the following code to the bottom of your class.
            #region ICommand Members
    
            public bool CanExecute(object parameter)
            {
                throw new NotImplementedException();
            }
    
            public event EventHandler CanExecuteChanged;
    
            public void Execute(object parameter)
            {
                throw new NotImplementedException();
            }
    
            #endregion
    
  6. Create two member variables or fields that we will use to hep use inside the ICommand interface functions.
    1. Action<object>
    2. Predicate<object>

            #region Member Variables
            readonly Action<object> _ActionToExecute;
            readonly Predicate<object> __ActionCanExecute;
            #endregion
    
  7. Implement the CanExecute(object parameter) function.
            public bool CanExecute(object parameter)
            {
                return __ActionCanExecute== null ? true : __ActionCanExecute(parameter);
            }
    
  8. Implement the EventHandler CanExecuteChanged. In doing this the MVVM experts used the CommandManager, which might be worth reading about.
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
  9. Implement the Execute(object parameter) function.
            public void Execute(object parameter)
            {
                _ActionToExecute(parameter);
            }
    
  10. Create constructors that allow us to initialize the object by passing in the Action

The final class looks as follows:

using System;
using System.Windows.Input;

namespace WpfDataBindingToICommand
{
    /// <summary>
    /// This RelayCommand object is used to encapsulate function logic into an oject that inherits ICommand.
    /// </summary>
    public class RelayCommand : ICommand
    {
        #region Member Variables
        readonly Action<object> _ActionToExecute;
        readonly Predicate<object> _ActionCanExecute;
        #endregion

        #region Constructors
        /// <summary>
        /// This creates a new RelayCommand.
        /// </summary>
        /// <param name="inActionToExecute">This is the logic of the actin to execute. This objects is usually a method that returns void.</param>
        public RelayCommand(Action<object> inActionToExecute)
            : this(inActionToExecute, null)
        {
        }

        /// <summary>
        /// This creates a new RelayCommand.
        /// </summary>
        /// <param name="inActionToExecute">This is the logic of the actin to execute. This objects is usually a method that returns void.</param>
        /// <param name="inActionCanExecute">This is the logic for whether the action can execute.</param>
        public RelayCommand(Action<object> inActionToExecute, Predicate<object> inActionCanExecute)
        {
            if (inActionToExecute == null)
                throw new ArgumentNullException("execute");

            _ActionToExecute = inActionToExecute;
            _ActionCanExecute = inActionCanExecute;
        }
        #endregion

        #region ICommand Members
        public bool CanExecute(object parameter)
        {
            return _ActionCanExecute == null ? true : _ActionCanExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _ActionToExecute(parameter);
        }
        #endregion
    }
}

Step 2 – Creating a ViewModelBase abstract base class

This object is used to create common logic for all objects that will be using in Binding. This object will implement INotifyPropertyChanged so it only has to be implemented once.

  1. Create a new class named ViewModelBase.
  2. Change the using statements to implement the following : System, System.CompenentModel
  3. Make the new ViewModelBase class public and abstract.
  4. Make the new ViewModelBase class implement INotifyPropertyChanged.
  5. Right-click on the INotifyPropertyChanged text and choose Implement Interface | Implement Interface. This adds the following code to the bottom of your class. Yes, it is just a one line event handler object.
            #region INotifyPropertyChanged Members
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            #endregion
    
  6. Create a function called NotifyPropertyChanged to help implement the object. Make sure it has a permission level of at least protected.
            #region Functions
            protected void NotifyPropertyChanged(String inPropertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(inPropertyName));
                }
            }
            #endregion
    
  7. Make the new ViewModelBase class public and abstract.

The final object looks as follows:

using System;
using System.ComponentModel;

namespace WpfDataBindingToICommand
{
    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        #region Constructors
        public ViewModelBase()
        {
        }
        #endregion

        #region Functions
        protected void NotifyPropertyChanged(String inPropertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(inPropertyName));
            }
        }
        #endregion

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }
}

Note: You may also want to implement IDisposable.

Step 3 – Creating the ViewModel and Model

We are going to have the ViewModel and business in the same object for this example, but sometimes you will have a separate ViewModel object that represents your data/business.

  1. Create a new class named SampleViewModel.
  2. Change the using statements to implement the following : System, System.Windows, System.Windows.Input
  3. Make the new SampleViewModel class public.
  4. Make the new SampleViewModel class inherit ViewModelBase.
    using System;
    using System.Windows;
    using System.Windows.Input;
    
    namespace WpfDataBindingToICommand
    {
        public class SampleViewModel : ViewModelBase
        {
            #region Constructors
            public SampleViewModel()
            {
            }
            #endregion
        }
    }
    
  5. Create a string field and property and make sure to have the property’s set function call NotifyPropertyChanged.
        public class SampleViewModel : ViewModelBase
        {
            string _Message = "Hello. This is the default message.";
    
            public string Message
            {
                get { return _Message; }
                set
                {
                    _Message = value;
                    NotifyPropertyChanged("Message");
                }
            }
        }
    
  6. Create a simple function to show a MessageBox.
            public void ShowMessage(String inMessage)
            {
                MessageBox.Show(inMessage);
            }
    
  7. Create an ICommand field and property. Make sure the property returns a RelayCommand object that references the ShowMessage method. This is a read only property.
            RelayCommand _ShowMessageCommand;
    
            public ICommand ShowMessageCommand
            {
                get
                {
                    if (_ShowMessageCommand == null)
                    {
                        _ShowMessageCommand = new RelayCommand(param => this.ShowMessage(Message));
                    }
                    return _ShowMessageCommand;
                }
            }
    

    Note: Notice that in order to pass the ShowMessage method, instead of the return value of the function, into the RelayCommand objectwhich is void anyway, the param => syntax is used.

The final SampleViewModel looks as follows.

using System;
using System.Windows;
using System.Windows.Input;

namespace WpfDataBindingToICommand
{
    public class SampleViewModel : ViewModelBase
    {
        #region Member Variables
        string _Message = "Hello. This is the default message.";
        RelayCommand _ShowMessageCommand;
        #endregion

        #region Constructors
        public SampleViewModel()
        {
        }
        #endregion

        #region Properties
        public string Message
        {
            get { return _Message; }
            set
            {
                _Message = value;
                NotifyPropertyChanged("Message");
            }
        }

        public ICommand ShowMessageCommand
        {
            get
            {
                if (_ShowMessageCommand == null)
                {
                    _ShowMessageCommand = new RelayCommand(param => this.ShowMessage(Message));
                }
                return _ShowMessageCommand;
            }
        }
        #endregion

        #region Functions
        public void ShowMessage(String inMessage)
        {
            MessageBox.Show(inMessage);
        }
        #endregion

        #region Enums
        #endregion
    }
}

Step 4 – Using Databinding to Bind an ICommand to a WPF Control

Ok, so lets modify the XAML of the default MainWindow.xaml code that was auto-created with the project. We will keep it simple and have a text box and a button to pop up the message.

Note: For this simple program all the work we did to implement databinding for binding events to methods seems like an absurd burden. However, for large applications, this design will lead to a better way to manage your code. It will decouple your GUI from your code, making future refactoring of the GUI much easier. This also improves the ability to make minor changes to the GUI. It also makes the code more sustainable and more easily tested. Unit tests are more effective as the GUI layer is not required and most functions are in the business layer.

  1. Create a reference to the current namespace.
    <window x:Class="WpfDataBindingToICommand.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfDataBindingToICommand"
            Title="MainWindow" Height="350" Width="525">
    
  2. Add a SampleViewModel StaticResource.
        <window.Resources>
            <local:SampleViewModel x:Key="Sample" />
        </window.Resources>
    
  3. Set the DataContext of the Grid to the SampleViewModel StaticResource.
            <grid.RowDefinitions>
                <rowDefinition Height="*" />
                <rowDefinition Height="50" />
            </grid.RowDefinitions>
    
  4. Add two rows to the Grid.
        <grid DataContext="{StaticResource ResourceKey=Sample}">
    
  5. Add a TextBox and remove the sizing and alignments. Set Margin to 5. Bind the Text property to Message.
            <textBox Text="{Binding Message}" Name="textBoxMessage" Margin="5"/>
    
  6. Add a button. Set HorizontalAlignment to Right. Set the Width to Auto. Set Margin to 5. Bind the Command property to ShowMessageCommand.
    <button Command="{Binding ShowMessageCommand}" Content="ShowMessage" Grid.Row="1" Height="23" Name="buttonShowMessage" HorizontalAlignment="Right" Width="Auto" Margin="5"/>
    

You are done. The final XAML is as follows:

<window x:Class="WpfDataBindingToICommand.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfDataBindingToICommand"
        Title="MainWindow" Height="350" Width="525">
    <window.Resources>
        <local:SampleViewModel x:Key="Sample" />
    </window.Resources>
    <grid DataContext="{StaticResource ResourceKey=Sample}">
        <grid.RowDefinitions>
            <rowDefinition Height="*" />
            <rowDefinition Height="50" />
        </grid.RowDefinitions>
        <textBox Text="{Binding Message}" Name="textBoxMessage" Margin="5"/>
        <button Command="{Binding ShowMessageCommand}" Content="ShowMessage" Grid.Row="1" Height="23" Name="buttonShowMessage" HorizontalAlignment="Right" Width="Auto" Margin="5"/>
    </grid>
</window>

Notice that we never touched the code behind of MainWindow. The GUI and the code are as decoupled as possible. Not event the event functions are needed in the code behind. This decoupling or GUI and code is our goal.

Resources

WPF Apps With The Model-View-ViewModel Design Pattern
Understanding Routed Events and Commands In WPF


Copyright ® Rhyous.com – Linking to this page is allowed without permission and as many as ten lines of this page can be used along with this link. Any other use of this page is allowed only by permission of Rhyous.com.

Tutorial – Binding to a member variable object

You have your WPF Window and you have an object that you don’t want to make a static resource. You want to declare it as a member variable in the code.

Example 1 – Binding two TextBox controls to a Person object

  1. Create a New WPF Application Visual Studio.
  2. Create a new Class named Person.cs.
  3. Give it FirstName and a LastName properties.
  4. Configure it to implement the INotifyPropertyChanged interface.
  5. Create a NotifyPropertyChanged function that all properties can share (to avoid duplicate code in every single property).
  6. Configure the properties to call the NotifyPropertyChanged function passing in a string that is the name of the property.

    Person.cs

    using System;
    using System.ComponentModel;
    
    namespace WPFPerson
    {
        public class Person : INotifyPropertyChanged
        {
            #region Member Variables
            String _FirstName;
            String _LastName;
            #endregion
    
            #region Constructors
            /*
    		 * The default constructor
     		 */
            public Person()
            {
            }
            #endregion
    
            #region Properties
            public String FirstName
            {
                get { return _FirstName; }
                set
                {
                    _FirstName = value;
                    NotifyPropertyChanged("FirstName");
                }
            }
    
            public String LastName
            {
                get { return _LastName; }
                set
                {
                    _LastName = value;
                    NotifyPropertyChanged("LastName");
                }
            }
            #endregion
    
            #region INotifyPropertyChanged Members
            public event PropertyChangedEventHandler PropertyChanged;
    
            private void NotifyPropertyChanged(String info)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(info));
                }
            }
            #endregion
        }
    }
    
  7. Go back tot he MainWindow.xaml.
  8. Add two labels, and two text boxes, and a button.
  9. Change the text boxes to be populated using binding by adding the following text:
    Text=”{Binding FirstName, Mode=TwoWay}”  

    MainWindow.xaml (WPF Window)

    <window x:Class="WPFPerson.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525" >
        <grid Name="PersonGrid" >
            <textBox Height="23" HorizontalAlignment="Left" Margin="173,87,0,0" Name="textBoxFirstName" VerticalAlignment="Top" Width="234" Text="{Binding FirstName, Mode=TwoWay}" />
            <textBox Height="23" HorizontalAlignment="Left" Margin="173,116,0,0" Name="textBoxLastName" VerticalAlignment="Top" Width="234" Text="{Binding LastName, Mode=TwoWay}"/>
            <label Content="FirstName" Height="28" HorizontalAlignment="Left" Margin="103,85,0,0" Name="labelFirstName" VerticalAlignment="Top" />
            <label Content="LastName" Height="28" HorizontalAlignment="Left" Margin="103,114,0,0" Name="labelLastName" VerticalAlignment="Top" />
            <button Content="Defaults" Height="23" HorizontalAlignment="Left" Margin="337,199,0,0" Name="buttonDefaults" VerticalAlignment="Top" Width="75" Click="buttonDefaults_Click" />
        </grid>
    </window>
    
  10. Double-click the button to create the buttonDefaults_Click event function.
    This also conveniently takes you to the Code Behind of the MainWindow.cs file.
  11. Have the buttonDefaults_Click function update to properties of your _Person object.
    _Person.FirstName = “Jared”;
    _Person.LastName = “Barneck”;
  12. Create a field/member variable using the Person object.
    private readonly Person _Person;
  13. Now in the constructor initialize the object.
    _Person = new Person();
  14. Also in the constructor, make the DataContext for each TextBox the _Person object.
    textBoxFirstName.DataContext = _Person;
    textBoxLastName.DataContext = _Person;  

    MainWindow.cs (Code Behind)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Threading;
    
    namespace WPFPerson
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            private readonly Person _Person;
    
            public MainWindow()
            {
                _Person = new Person();
                InitializeComponent();
                textBoxFirstName.DataContext = _Person;
                textBoxLastName.DataContext = _Person;
            }
    
            private void buttonDefaults_Click(object sender, RoutedEventArgs e)
            {
                _Person.FirstName = "Jared";
                _Person.LastName = "Barneck";
            }
        }
    }
    
  15. Now Now compile and make sure you don’t have any errors.

Example 2 – Forthcoming…

Example 3 – Forthcoming…

Sources:
http://www.wrox.com/WileyCDA/Section/Windows-Presentation-Foundation-WPF-Data-Binding-with-C-2005.id-305562.html