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 );
        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";
        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)
        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
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"
    Title="Development Helper" Height="300" Width="300" ShowInTaskbar="False" 
    WindowState="Minimized" WindowStartupLocation="CenterScreen" Icon="/DevHelperWpf;component/AppIcon.ico" ResizeMode="CanResize" Loaded="Window_Loaded">
     <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'