October 20, 2011

gcroot and pin_ptr

Reference managed type members in an unmanaged class by using the "gcroot<>" template. This provides a wrapper around the GCHandle class.
Look at this msdn explanantion
Also there is this article on codeproject
gcroot str;
str = gcnew String("hello");
Pinning in C++/CLI. Do this using the pin_ptr keyword. This prevents the managed object from being moved around in memory by the garbage collector
Object ^obj = gcnew MyClass();
pin_ptr pinned = obj;

October 12, 2011

CSS Positioning Concepts

CSS unit of measurement 1ex= width of letter "x"

CSS Positioning Concepts
CSS Positioning
Positioning in 10 easy steps with pictures - very good

“position:relative”
The “position:relative” is best used when you want to adjust some element's position slightly. The “relative” means it is relative to the parent tag's rendering box. More here

"position:fixed"
Position is fixed to the browser window. For example "<div style="position:fixed; right:1ex; bottom:1ex">" fixes to the bottom right hand corner of the browser window. More from the original source
When a element is “position:fixed”, it is moved into a layer by itself. Use the "z-index" parameter to specify if it is on top or below the over elements. Again, more here

October 6, 2011

Printing HTML

To initiate the Print of a web page use the following HTML and Javascript:
<a href="javascript:window.print()">Print Page</a> 
This is how the link looks: Print Page

There is more on this at Htmlgoodies

September 20, 2011

Delegating Events & Event Serialisation Problems

Delegating an event to an underlying class:
...
private Helper helper;

// Normally implementation of add/remove are hidden but it is still possible to define them explicitly
public event EventHandler SomethingChanged
{
 add
 {
  this.helper.SomethingChanged += value;
 }
 remove
 {
  this.helper.SomethingChanged -= value;
 }
}
From the Event Accessors article by Stephen Toub, we get the following advice:

The trouble with events when it comes to .NET serialization is that they're backed by a private delegate field, and delegates are serializable. When you create a delegate for an instance method, the delegate maintains a reference to the instance on which to call that method, so when you serialize an object that contains an event, the formatter, while walking the object graph, will continue on down through the delegate attempting to serialize any instances registered with that delegate. A solution is to mark the backing store for the event with [NonSerializable]

Here is an example of the suggested solution:
[NonSerializable]
private EventHandler _myEvent;

September 14, 2011

Using Attributes for Property Meta Data

Another simple example of using Attributes and reflection. This time to place meta data on a property
[AttributeUsage(AttributeTargets.Property)]
[DebuggerDisplay("Name={Name}, Descr={Description}, Min={Min}, Max={Max}")]
public class DoublePropertyMetaData
    : System.Attribute
{
    public string Name { get; set; }
    public string Description { get; set; }
    public double Min { get; set; }
    public double Max { get; set; }
    public override string ToString()
    {
        string str = string.Format("Name={0}, Descr={1}, Min={2}, Max={3}", 
            Name, Description, Min.ToString(), Max.ToString());
        return str;
    }
}

public class PropertyTest
{
    [DoublePropertyMetaData(Name = "Valve Flow Rate", 
        Description = "Rate of flow through inlet valve", 
        Max = 12345.1d, Min = 0.0d)]
    public double ValveFlowRate { get; set; }
}

public class AttributesAsMetaDataTester
{
    public void Test1()
    {
        DoublePropertyMetaData propMetaData = GetDoubleMetaData(typeof(PropertyTest));
        Console.WriteLine("Result: " + propMetaData.ToString());
    }

    private static DoublePropertyMetaData GetDoubleMetaData(Type type)
    {
        PropertyInfo[] props = type.GetProperties();
        DoublePropertyMetaData[] attributes = new DoublePropertyMetaData[0];
        foreach (PropertyInfo prop in props)
        {
            attributes = (DoublePropertyMetaData[])prop.GetCustomAttributes(
                typeof(DoublePropertyMetaData), false);
        }
        return attributes[0];
    }
}

August 23, 2011

Enum and Description Attribute

Found this helper in this article EnumHelper - Getting a Friendly Description from an Enum by Grant Barrington, initially.
Found idea for the generic enum class here
Have refactored and merged them a little and added a couple of my own methods
    /// <summary>
    /// Not really an extension class but this is more readable than an extension class.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class Enum<T> 
        where T : struct, Enum
    {
        /// <summary>
        /// Parse the given string into an enum value, ignores the case of the string
        /// </summary>
        /// <param name="value">string to parse, leading and trailing whitespace characters are removed</param>
        /// <returns>Enum value parsed from the string</returns>
        public static T Parse(string value)
        {
            return Enum<T>.Parse(value.Trim(), true);
        }

        /// <summary>
        /// Parse the given string into an enum value
        /// </summary>
        /// <param name="value">string to parse, leading and trailing whitespace characters are removed</param>
        /// <param name="ignoreCase">Whether to ignore the case of the letters in the string when parsing</param>
        /// <returns>Enum value parsed from the string</returns>
        public static T Parse(string value, bool ignoreCase)
        {
            return (T)Enum.Parse(typeof(T), value.Trim(), ignoreCase);
        }

        /// <summary>
        /// Try to parse the given string into an enum value, ignores the case of the string. Capture any exceptions
        /// </summary>
        /// <param name="value">string to parse, leading and trailing whitespace characters are removed</param>
        /// <param name="returnedValue">Enum value parsed from the string</param>
        /// <returns>true if the string was successfully parsed into a enum value of the given type</returns>
        public static bool TryParse(string value, out T returnedValue)
        {
            return Enum.TryParse<T>(value, true, out returnedValue);
        }

        /// <summary>
        /// Try to parse the given string into an enum value. Capture any exceptions
        /// </summary>
        /// <param name="value">string to parse, leading and trailing whitespace characters are removed</param>
        /// <param name="ignoreCase">Whether to ignore the case of the letters in the string when parsing</param>
        /// <param name="returnedValue">Enum value parsed from the string</param>
        /// <returns>true if the string was successfully parsed into a enum value of the given type</returns>
        public static bool TryParse(string value, bool ignoreCase, out T returnedValue)
        {
            return Enum.TryParse<T>(value, ignoreCase, out returnedValue);
        }

        /// <summary>
        /// Get the enum values of the given enum type
        /// </summary>
        /// <returns>Array of the enum values in the enum type</returns>
        public static Array GetValues()
        {
            return Enum.GetValues(typeof(T));
        }

        /// <summary>
        /// Returns first description attribute of the enum value or the enum value 
        /// itself as a string if no description attribute was found
        /// </summary>
        /// <param name="enumValue">An enum value in the given enum type</param>
        /// <returns>
        /// First description attribute found of the enum value or the enum value 
        /// itself as a string if no description attribute was found
        /// </returns>
        public static string GetAsString(T enumValue)
        {
            string res = GetFirstDescriptionAttribute(enumValue);
            if (string.IsNullOrEmpty(res))
                res = enumValue.ToString();
            return res;
        }

        /// <summary>
        /// Returns first description attribute of the enum value
        /// </summary>
        /// <param name="enumValue">An enum value in the given enum type</param>
        /// <returns>
        /// First description attribute found of the enum value or null if no description attribute was found
        /// </returns>
        public static string GetDescriptionAttribute(T enumValue)
        {
            Type type = enumValue.GetType();

            MemberInfo[] memInfo = type.GetMember(enumValue.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(
                    typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            return null;
        }

 
    }
Now use the above helpers to demonstrate how to get the description attribute on an enum entry and how to get the best string form for an enum for entry into a listbox or something
public enum DescriptionsEnum
{
    [DescriptionAttribute("Add On")]
    AddOn,
    [DescriptionAttribute("Snap On")]
    SnapOn = 7,
    Adjacent = 2,
    Fixed = 12,
};

public void Test1()
{
    int asInt = 0;            
    foreach (var entry in Enum<DescriptionsEnum>.GetValues())
    {
        asInt = (int)entry;
        Console.WriteLine(asInt.ToString() + " " + 
            entry.ToString() + ":" + 
            Enum<DescriptionsEnum>.GetDescriptionAttribute((Enum)entry));
    }
    Console.WriteLine();
    foreach (var entry in Enum<DescriptionsEnum>.GetValues())
    {
        asInt = (int)entry;
        Console.WriteLine(asInt.ToString() + " " + 
            Enum<DescriptionsEnum>.GetAsString((Enum)entry));
    }
}
and the output of the test is
0 AddOn:Add On
2 Adjacent:
7 SnapOn:Snap On
12 Fixed:

0 Add On
2 Adjacent
7 Snap On
12 Fixed
There is also an interesting article on Enum: Binding to the Description Attribute by Deborah Kurata.
Using these helpers making something to bind to is much simpler:
Dictionary<string, int> bindToMe = new Dictionary<string, int>();
foreach (var entry in Enum.GetValues(typeof(DescriptionsEnum)))
{
    asInt = (int)entry;
    bindToMe.Add(EnumHelper.GetAsString((Enum)entry), asInt);
} 

August 22, 2011

Properties in C++/CLI

See also C++/CLI lesson here
To implement them completely inline:
virtual property bool IsWritable {
  bool get() { return isWritable_; };
  void set(bool value) { isWritable_ = value; };
}
In header file (.h) for a header+source implementation:
virtual property System::String ^Name {
  System::String ^get();
  void set(System::String^); 
}
then in the source (.cpp) file:
System::String ^ XXX::Name::get() {
  return gcnew System::String(xxx.getName().c_str());
}

void XXX::Name::set(System::String ^value) {
   ...
}
To override, in the header of derived class change the definition with an override statement:
virtual property bool DoSomething {
  bool get() override;
  bool set() override;
}

August 19, 2011

FileSystemWatcher

File system watcher hints and tips
Msdn page for it has some useful information on gotchas

Following sample code watches a file and fires events when the file "appears" or "disappears". In this case the file could "appear" when it is created or when it is renamed from an existing file and "disappear" if it is deleted or the file is renamed to something else.

This renaming issue is something to watch out for when using this class! Detecting this is a bit more subtle.
//class fields
FileSystemWatcher fileWatcher = new FileSystemWatcher();
// Target a specific file (in this case)
readonly string targetFileName = "Myfile.name";
string targetDirectory;
string fullTargetFilePath;
...
// Expose some events
public event EventHandler LockFileAppeared;
public event EventHandler LockFileDisappeared;

// Private Firing events
void FireLockFileAppeared(FileSystemEventArgs eargs)
{
  if (LockFileAppeared != null)
    LockFileAppeared(this, eargs);
}

void FireLockFileDisappeared(FileSystemEventArgs eargs)
{
  if (LockFileDisappeared != null)
    LockFileDisappeared(this, eargs);
}
...
// Initialise it
void InitialiseFileWatcher()
{
  if (Directory.Exists(this.targetDirectory))
  {
    this.fullTargetFilePath = System.IO.Path.Combine(
            LockFileDirectory, LockFileName);
    fileWatcher.Path = LockFileDirectory;
    fileWatcher.Filter = LockFileName; 
    fileWatcher.IncludeSubdirectories = false;
    fileWatcher.Renamed += new RenamedEventHandler(fileWatcher_Renamed);
    fileWatcher.Error += new ErrorEventHandler(fileWatcher_Error);
    fileWatcher.Created += new FileSystemEventHandler(fileWatcher_Created);
    fileWatcher.Deleted += new FileSystemEventHandler(fileWatcher_Deleted);
    fileWatcher.EnableRaisingEvents = true;
  }
}

// Implement a IDisposable as FileSystemWatcher is disposable
...
// Add events
void fileWatcher_Deleted(object sender, FileSystemEventArgs e)
{ // FIRED ON ANOTHER THREAD
  if (e.Name == LockFileName)
    FireLockFileDisappeared(e);
}

void fileWatcher_Created(object sender, FileSystemEventArgs e)
{ // FIRED ON ANOTHER THREAD
  if (e.Name == LockFileName)
    FireLockFileAppeared(e);
}

void fileWatcher_Renamed(object sender, RenamedEventArgs e)
{ // FIRED ON ANOTHER THREAD
  // If another file is renamed to our target file 
  if (e.Name == LockFileName)
  {
    FireLockFileAppeared(new FileSystemEventArgs(
      WatcherChangeTypes.Created, LockFileDirectory, LockFileName));
  }
  // If our target file is renamed to something else
  else if (e.OldName == LockFileName)
  {
    FireLockFileDisappeared(new FileSystemEventArgs(
      WatcherChangeTypes.Deleted, LockFileDirectory, LockFileName));
  }
}

// Misc. helpers
public string LockFilePath
{
    get { return this.fullTargetFilePath; }
}

public string LockFileDirectory
{
    get { return this.targetDirectory; }
}

Be aware that the class events are fired on another thread so if you want to update the GUI you will have to marshal any data accross. Also be aware that sometimes the events can be fired multiple times for only 1 real event.

August 12, 2011

C++/CLI Using Keyword


#using <XXX::YYY::ZZZ.dll&gt; <= Add a reference to a particular assembly, goes after precompiled header. Make sure to add the path of the referenced assembly to your C# assembly in VS via your assembly's project properties > C/C++ > General > Resolve #using References

using XXX::YYY::ZZZ::StrategyManager; <= Use a specific type (class, enum, ...) from a referenced assembly

using namespace System::Linq; <= Access all types in a namespace from a referenced assembly

August 11, 2011

Virtual Sealed Method in C++/CLI

example:
 virtual System::String^ DoSomething(...) sealed;
What does the sealed do here?
"sealed" on a function means that you can't override that method in a derived type.

Arrays in C++/CLI

Arrays in C++/CLI
array^ attributes =  enumType->GetCustomAttributes(
  System::FlagsAttribute::typeid, false);

Enum type information in C++/CLI

Testing a generic parameter for enum type information
generic <class TValue>
...MyMethod()
{
  // Testing a generic parameter for enum type information
  
  System::Type^ enumType = TValue::typeid;
  // Only enum types supported
  if (!enumType->IsEnum) 
  {
    throw gcnew System::ArgumentException("...");
  }
  // Only 32 bit integer enum types are supported
  if (System::Enum::GetUnderlyingType(enumType) != System::Int32::typeid) 
  { 
    throw gcnew System::ArgumentException("...");
  }
  // [Flags] type enums not supported
  array<System::Object^>^ attributes = enumType->
    GetCustomAttributes(System::FlagsAttribute::typeid, false);
  if (attributes->Length != 0) 
  {
    throw gcnew System::ArgumentException("...");
  }
}

August 9, 2011

Null-coalescing or ?? operator

Always forgetting the name of this operator!

The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type.
// Set defaultValue to Settings.DefaultValue unless it is null 
// in which case set it to string.Empty
string defaultValue = Settings.DefaultValue ?? string.Empty;

June 29, 2011

Contravariance and Covariance


Good simple MSDN guide
Many definitions here, choose the one that is easiest to understand
Here is the Wikipedia view


Covariant: converting from a broader type (more generic) to a narrower (more specific) type. Can use a more derived type than that specified in the definition in an output (returned type). Covariance means that you can use an object of a specialized class (e.g. String) where the declaration states a more general class (e.g. object).

Contravariant: converting from a narrower (more specific) type to a broader (more generic) type.  Can use a base type of that specified in the definition. Contravariance means that you can use an object of a more general class (e.g. object) where the declaration states a more specific class (e.g. string).

June 28, 2011

Silverlight and WPF relationship

Here is a neat image that succinctly describes the relationship between Silverlight and WPF.
Silverlight versus WPF

I took it from this site but I think it is the best indicator of the relationship between the 2 of them.

Here is another that relates them Windows Phone 7 as well
Silverlight, WPF and Windows Phone 7

C# Protected Internal

In C#, "protected internal" is the UNION of the terms not the intersection! So a "protected internal" object can be accessed by a derived class (derived from the class with the "protected internal" item) or from another class in the same assembly.
see this article

June 14, 2011

Func samples

Some Func<> samples I found on the web
First
Func<string, string> upper = str => str.ToUpper();
Then
Func<int, int> Factorial = null;
Factorial = (n) => n <= 1 ? 1 : n * Factorial(n - 1);

Parent/Child versus Owner/Owned in Windows


In pure Windows terms.
Owner property of a window in .NET

In pure windows terms:
Child windows are rendered within the client area of their parent window (eg: buttons, text boxes, etc.).
A child window has the WS_CHILD style and is confined to the client area of its parent window. An application typically uses child windows to divide the client area of a parent window into functional areas. A child window can have it's parent window changed.

Owned windows are rendered outside the client area of their owner window (dialog boxes, message boxes, etc.)
An owned window is an overlapped or pop-up window (WS_OVERLAPPED or WS_POPUP style style) and are used for rendering outside of a owner window’s client area. Ownership of Owned windows cannot be transferred.
The Owner is responsible for for creating/destroying the owned window.

Do WM_COMMAND messages get sent to the owner window or parent window first? My work colleague strongly argues that the OS first tries to send them to the owner window but if this is not set (NULL[==the desktop window]) then the message is sent to the parent window. However, I can not find any documentation that collaborates this.

This link argues that a window can have eiether an Owner or a Parent but not both.

Volatile

Volatile on Msdn
Keep forgetting to use this. The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread. Volatile means that read/write operations will always target the main memory not a cached copy, it does not imply access to a variable is made thread safe through its usage.
Good explanantion of volatile/non-volatile reads and writes
Understand the Impact of Low-Lock Techniques in Multithreaded Apps

Watch out for warnings when using a volatile variable in an Interlocked operation. Use #pragma to remove it:
#pragma warning disable 420  // Volatile passed as reference to the interlocked API
  System.Threading.Interlocked.Exchange<SomeType>(ref this.somObject, newSomeObject);
#pragma warning restore 420

June 9, 2011

Regex Matches Tester

Can find and list matching regular expressions in a string
internal class TestRegexMatches
{

    public void Test()
    {
        string typeName = typeof(double).ToString().Replace('.', '_');
        string name = "Fudge Factor".Replace(" ", "_");
        string plugin = "Smb.Orca.Theo.Samba.Delta, Version=4.20111.99.0, Culture=neutral, PublicKeyToken=19ae4a476ca5c63x";
        string[] splitStr = plugin.Split(',');
        plugin = splitStr[0].Replace('.', '_');

        string id = typeName + "\t" + name + "\t" + plugin;
        int ix=1;
        MatchCollection matches = Regex.Matches(id, @"[^\t]+");
        foreach (Match match in matches)
        {
            Console.WriteLine("Match " + ix++.ToString() + ": " + match.Value);
        }
    }
}
produces the output
Match 1: System_Double
Match 2: Fudge_Factor
Match 3: Smb_Orca_Theo_Samba_Delta

April 5, 2011

Use TryGetValue instead of ContainsKey

See these pages for more info:
C# TryGetValue
C# TryGetValue Method

Basically, instead of
private Dictionary  xxxCache = new Dictionary ()

Xxx GetEntry(Key key)
{
  Xxx entry = null;
  // if entry found
  if (xxxCache.ContainsKey(key)) 
  { 
    entry = xxxCache[key] as Xxx;
  }
  else // add new entry
  {
    entry = new Xxx(...);
    xxxCache.Add(key, entry);
  }
  return entry;
}
use
Xxx GetEntry(Key key)
{
  Xxx entry = null;
  // if entry not found
  if (!xxxCache.TryGetValue(key, out entry)) 
  { // then add new entry
    entry = new Xxx(...);
    xxxCache.Add(key, entry);
  }
  return entry as Xxx;
}
This is assuming you do NOT want an exception to be thrown if the key is not found. I still find the first implementation as more readable

March 31, 2011

Using Xaml resources in a common assembly

First put the resources in a resource dictioanry xaml file that goes into the shared resource assembly. In this sample the assembly is called Common and the common resources are placed in a subdirectory WPF of this assembly. Their is no ".cs" file associated with this Xaml file. Here is the Xaml file in the "Common" assembly with a shared listbox style called "MyListStyle":
<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:System="clr-namespace:System;assembly=mscorlib">
            <Style x:Key="MyListStyle" TargetType="ListBox">
   ...
            </Style>
</ResourceDictionary>

To reference these resources in another WPF component, do it from the Resources area of the WPF component. For example
<Window ... >
    <Window.Resources>
         <ResourceDictionary Source="/Common;component/WPF/Resources.xaml" />
    </Window.Resources>
 ...
        <ListBox ... Style="{StaticResource MyListStyle}" />
 ...
</Window>

To reference those resources from a WPF Application:
<Application ... >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Common;component/WPF/Resources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Once added to an application's resources they can be accessed anywhere in the normal fashion:
<Window ... >
...
        <ListBox ... Style="{StaticResource MyListStyle}"  />
...  
</Window>

March 11, 2011

Windows Explorer Context Menus

A simple C# function to add context menu items in Explorer
Add a context menu to the Windows Explorer

Use this quick class to add a new menu item to the context menu of folders or file extensions (although I have not tested the latter) in Windows Explorer. Modified from some of the code from the latter article. Could be expanded to add context menu items for different extensions (see first article/link).Have done this but it is not tested.
public class ExplorerContextMenuHelper
{
    private string m_MenuNameSubKey = "MenuName";
    private string m_ExtensionSubkey = "Folder";

    private string m_menuText = "";
    private string m_menuCommand = "";
    private string m_menuCommandLineArgs = "";

    // Some file extension context menu helper
    public ExplorerContextMenuHelper(
            string extension,
            string menuName,
            string menuText,
            string menuCommandLine,
            string menuCommandLineArgs)
        : this(menuName, menuText, menuCommandLine, menuCommandLineArgs)
    {
        Debug.Assert(!string.IsNullOrEmpty(extension));
        m_ExtensionSubkey = extension;
    }

    // Folder context menu helper
    public ExplorerContextMenuHelper(
        string menuName,
        string menuText,
        string menuCommandLine,
        string menuCommandLineArgs)
        : this(menuName, menuText, menuCommandLine)
    {
        Debug.Assert(!string.IsNullOrEmpty(menuCommandLineArgs));
        m_menuCommandLineArgs = menuCommandLineArgs;
    }

    public ExplorerContextMenuHelper(
        string menuName,
        string menuText,
        string menuCommandLine)
    {
        Debug.Assert(!string.IsNullOrEmpty(menuName));
        Debug.Assert(!string.IsNullOrEmpty(menuText));
        Debug.Assert(!string.IsNullOrEmpty(menuCommandLine));
        m_menuText = menuText;
        m_menuCommand = menuCommandLine;
        m_MenuNameSubKey = menuName;
    }


    public ExplorerContextMenuHelper(string menuName)
    {
        Debug.Assert(!string.IsNullOrEmpty(menuName));
        m_MenuNameSubKey = menuName;
    }


    public string ExtensionMenuNameSubKey
    {
        get { return m_ExtensionSubkey + "\\shell\\" + m_MenuNameSubKey; }
    }

    public string ExtensionMenuCommandSubkey
    {
        get { return ExtensionMenuNameSubKey + "\\command"; }
    }

    public string MenuCommand
    {
        get { return m_menuCommand + " " + m_menuCommandLineArgs; }
    }

    public void CheckSecurity()
    {

        //check registry permissions
        RegistryPermission regPerm;
        regPerm = new RegistryPermission(RegistryPermissionAccess.Write,
                    "HKEY_CLASSES_ROOT\\" + ExtensionMenuNameSubKey);
        regPerm.AddPathList(RegistryPermissionAccess.Write,
                    "HKEY_CLASSES_ROOT\\" + ExtensionMenuCommandSubkey);
        regPerm.Demand();

    }

    public bool TryAddMenuItem()
    {
        bool res = false;
        try
        {
            CheckSecurity();
            using (RegistryKey regmenu = Registry.ClassesRoot.
                    CreateSubKey(ExtensionMenuNameSubKey))
            {
                regmenu.SetValue("", m_menuText);
            }
            using (RegistryKey regcmd = Registry.ClassesRoot.
                    CreateSubKey(ExtensionMenuCommandSubkey))
            {
                regcmd.SetValue("", MenuCommand);
            }
            res = true;
        }
        catch (Exception ex)
        {
            LogException(ex.ToString());
        }
        return res;
    }

    public void TryRemoveMenuItem()
    {
        try
        {
            CheckSecurity();
            Registry.ClassesRoot.DeleteSubKey(ExtensionMenuCommandSubkey, false);
            Registry.ClassesRoot.DeleteSubKey(ExtensionMenuNameSubKey, false);
        }
        catch (SecurityException sex)
        {
            LogException(sex.ToString());
        }
        catch (UnauthorizedAccessException uae)
        {
            LogException(uae.ToString());
        }
    }

    private void LogException(string error)
    {
        Debug.WriteLine(error);
    }
}
Here some sample code that uses it:
private void RegisterWithExplorer()
{
  string path = new Uri(Assembly.GetExecutingAssembly().
                        GetName().CodeBase).LocalPath;
  ExplorerContextMenuHelper ecm = new ExplorerContextMenuHelper(
               "PhotoBackupApp", "Backup photos", path, "\"%1\"");
  ecm.TryAddMenuItem();
}

private void UnregisterWithExplorer()
{
  ExplorerContextMenuHelper ecm = new ExplorerContextMenuHelper(
                                                "PhotoBackupApp");
  ecm.TryRemoveMenuItem();
}

March 4, 2011

Immediate/Lazy Execution Terms

Deferred execution and eager evaluation

Immediate Execution - means that the computation/execution is done in the function and finished once the function return. (Fully eager evaluation as most C# code does)
Deferred/Eager Execution (buffering) - means that most of the work will be done on the first MoveNext() or when the IEnumerator instance is created (For IEnumerable it is when GetEnumerator is called)
Deferred/Lazy Exceution (streaming) - means that the work will be done each time GetNext() is called but nothing before.

March 1, 2011

Filtering a Multiline string Line by Line using a Regular Expression

For other regular expression stuff see also this blog
This routine filters a string containing multiple lines using the supplied regular expression filter. Set the invert parameter to true if you want the results inverted
private string Filter(string reportText, string regExFilter, bool invert)
{
    if (regExFilter.Length > 0)
    {
        StringBuilder output = new StringBuilder();
        string[] lines = reportText.Split(
          new string[] { Environment.NewLine }, 
          StringSplitOptions.None);
        foreach (string line in lines)
        {
            if ((line.Length > 0))
            {
                bool matches = Regex.IsMatch(line, regExFilter,
                                             RegexOptions.None);
                if ((matches && !invert) || (!matches && invert))
                    output.AppendLine(line);
            }
        }
        return output.ToString();
    }
    else
    {
        return reportText;
    }
}

February 22, 2011

String Class Extensions

string.Right() method and case insensisitive IndexOf
String Extension Collection for C#
Favorite String Extension Methods in C#

Convert 'string.Right()' to an extension method
static class StringExtensions
{
  static string Right(this string s, int count )
  {
    string newString = String.Empty;
    if (s != null && count > 0)
    {
      int startIndex = s.Length - count;
      if (startIndex > 0)
        newString = s.Substring( startIndex, count );
      else
        newString = s;
    }
    return newString;
  }
}

February 15, 2011

Method to Retrieve a Web Page as A String

Here is some sample code for this:
/// <summary>
/// Synchronously reads the contents of a url and returns it as a string
/// </summary>
/// <param name="url">Url to read</param>
/// <param name="requestOK">Whether the request succeeded of failed</param>
/// <param name="msg">Error message when something went wrong</param>
/// <returns>url contents as a string</returns>
public string TryGetUrlContents(string url, out bool requestOK, out string msg)
{
    string webPage = string.Empty;
    WebRequest webRequest = null;
    requestOK = true;
    msg = "No response to the web request";
    try
    {
        webRequest = WebRequest.Create(url);
        //webRequest.Method = "GET"; // Not necessary, it is GET by default                
        requestOK = (webRequest != null);
    
        if (requestOK)
        {
            using (WebResponse response = webRequest.GetResponse())
            {
                // tries to load as a UTF-8 document by default
                // true parameter here tells it to try and work out 
                // the document format if it is not UTF-8
                using (StreamReader responseStream = new 
                       StreamReader(response.GetResponseStream(), true))
                {
                    webPage = responseStream.ReadToEnd();
                    msg = "";
                }
            }
        }
    }
    catch (WebException we)
    {
        HandleException(we);
        msg = "Exception caught tring to make the request:" + we.ToString();
        requestOK = false;
    }

    return webPage;
}

void HandleException(Exception ex)
{
    Debug.WriteLine("Exception caught: " + ex.ToString());   
}
It has been changed to attempt to encode the returned contents correctly. If you do not care whether the retrieval worked correctly or not then use this:
public string TryGetUrlContents(string url)
{
    bool requestOK;
    string msg;
    return TryGetUrlContents(url, out requestOK, out msg);
}

WPF Databinding to User Settings

Used this website as a reference: Binding to User Settings in WPF

In the Xaml add
xmlns:Properties="clr-namespace:XXX.Properties"
to the window/control attributes section where XXX is the application namespace under which the properties are defined

Then to bind a setting
Text="{Binding Source={x:Static Properties:Settings.Default}, Path=SomeSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

Note without the 'UpdateSourceTrigger' definition the updating did not work when the update was made programmatically. By default the 'UpdateSourceTrigger' is set to 'FocusChanged' so that only when the control lost it's focus would the change be passed on back to the source.
Why this change worked

Weak References

See here for MSDN Description
And here is sample usage
Here is a Tutorial on using Weak References

"Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection."
"Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects."

February 10, 2011

WPF Accessing a resource based control created through Xaml

Here is Xaml:
<Window x:Class="DevHelperWpf.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Development Helper" Height="300" Width="300" ShowInTaskbar="False" 
    WindowState="Minimized" WindowStartupLocation="CenterScreen" Icon="/DevHelperWpf;component/AppIcon.ico" ResizeMode="CanResize" Loaded="Window_Loaded">
    <Window.Resources>        
     <ContextMenu x:Key="NotifierContextMenu" Placement="MousePoint">
            <MenuItem Name="menuEmptyTemp" Header="_Empty Temp" Click="Menu_EmptyTemp" ToolTip="Clean out your Temp directory" />
            <MenuItem Name="menuSaveImage" Header="Save _Clipboard Image To File" Click="Menu_ClipboardToFile" ToolTip="Save an image to the clipboard" />
            <MenuItem Name="menuP4QCC" Header="P4QCC" Click="Menu_P4QCC" ToolTip="Start P4QCC utility" />
....
Now accessing the control through a method on the parent window (note this is the 'Window1' instance):
contextMenu = (ContextMenu)this.FindResource("NotifierContextMenu");
    
MenuItem item = new MenuItem();
foreach (MenuItem mi in contextMenu.Items)
{
  ...
}

February 8, 2011

Finding CommandLines of Other Processes

Add a reference to "System.Management" assembly
using System.Management;
...

static void FindAllProcessNameWithCommandLine()
{
    string wmiQuery = "Select * from Win32_Process";
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
    ManagementObjectCollection retObjectCollection = searcher.Get();
    foreach (ManagementObject retObject in retObjectCollection)
    {
        string exename = retObject["Name"] as string;
        string commandline = retObject["CommandLine"] as string;
        Debug.WriteLine(exename + ": \'" + commandline + "\'");
    }
}

Sample Output:
...
procexp64.exe: '"C:\Program Files (x86)\Tools\ProcessExplorer\procexp.exe" '
explorer.exe: '"C:\Windows\explorer.exe" /n,/select,"C:\Users\RBovilll\AppData\Local\Temp\Kabo.zip"'
SMSCliUI.exe: 'C:\Windows\SysWOW64\CCM\SMSCliUI.exe -Embedding'
devenv.exe: '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" '
splwow64.exe: 'splwow64'
...

January 27, 2011

C++ Declaring A Static Type


In header
class Xxx {
...
  static sometype dict_;
...
In source:
sometype Xxx::dict_;

Windows Message Queues Important Notes

About Messages and Message Queues
PeekMessage
Win32 Message Processing Primer
See also this post on this blog

PostMessage => Asynchronous, message goes into the message queue
SendMessage => Synchronous, message is sent to WinProc immediately and processed immediately.
Note: WM_PAINT, WM_TIMER, WM_QUIT handled differently when posted. They are only processed when there are no other messages in the queue. Multiple WM_PAINT messages for the same window are combined consolidating all invalid parts of the client area into a single area.
GetMessage() - Does not return until message matching the filter criteria is found. Removes message from queue
while (GetMessage (&msg, NULL, 0, 0))
{
  TranslateMessage (&msg) ;
  DispatchMessage (&msg) ;
}
PeekMessage() - Looks for message matching the filter criteria. Returns immediately. Whether the matching message is removed from the queue or not is determined by the last parameter of the method
do
{
  if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
  {
    TranslateMessage (&msg) ;
    DispatchMessage (&msg) ;
  }
} while (msg.message != WM_QUIT);
Neither GetMessage or PeekMessage will remove WM_PAINT messages unless the update area of the message is null!
 

January 12, 2011

Simple Pie Chart using WPF Toolkit

Here is more detail
Also look at WPF Toolkit Tutorial – Part 1

A simple pie chart example in that there only 2 wedges in the pie chart!
Add a reference to the WPFToolkit data visualisation assembly ("...\Program Files\WPF Toolkit\v3.5.50211.1\System.Windows.Controls.DataVisualization.Toolkit.dll")

Add following xaml to the window where the pie chart will be placed:
<Window ...
  <!-- First define the namespace for charting -->
  xmlns:charting="clr-namespace:
  System.Windows.Controls.DataVisualization.Charting;
  assembly=System.Windows.Controls.DataVisualization.Toolkit"

  <charting:Chart Name="pieChart">
    <charting:PieSeries ItemsSource="{Binding}" 
      IndependentValueBinding="{Binding Path=Description}"
   DependentValueBinding="{Binding Path=Percentage}"
    />
  </charting:Chart>
Set the Pie chart wedges
void AssignPieChartWedges()
{
    System.IO.DriveInfo cdrive = new System.IO.DriveInfo("C");
    double availPercentage = Math.Round(100.0d * 
        (double)cdrive.TotalFreeSpace / (double)cdrive.TotalSize);

    List<DrivePercentage> dpList = new List<DrivePercentage>();
    dpList.Add(new DrivePercentage() 
    { Percentage=availPercentage, Description="Free" });
    dpList.Add(new DrivePercentage() 
    { Percentage=100.0d-availPercentage, Description="Used" });
    pieChart.DataContext = dpList;
}