Sina Iravanian

I blog about software development

Code Snippet for Dealing With Windows Forms ListView Control in Details Mode

| Comments

I needed a piece of code to manage list-view controllers. I needed to use ListView controls in the details mode, which automatically sort its contents when I click on the header, and also pastes the content in a tabular format when I press Ctrl+C or Ctrl+Insert on it. So I created the following classes. The code that carries out the sorting stuff when the header is clicked is taken from this following MSDN article.

So these are the contributions of these pieces of code: 1) Sort ListView items when the column header is clicked, 2) Paste the contents of the ListView control to clipboard in a tabular format, and 3) Provide an easy to use API to append data to a ListView control.

The following gist contains the code to accomplish this. It consists of 3 files. The ListViewColumnSorter.cs file is responsible for the sorting stuff. The ListViewUtils.cs file provides the utility methods for a ListView control. The main methods that perform the job are located in the ListViewUtils class. The two needed methods are InitListView and AppendToListView. And finally the Usage.cs file provides a small demo of the utility methods.

Enabling Middle Click in Synaptics Touchpad Drivers

| Comments

Recently I upgraded my currently installed Synaptics touchpad driver to version 15.x, and I found that I cannot emulate the middle-click effect by pressing both right and left click buttons. I found no options in the settings to enable that functionality. Finally after searching the web I found a workaround here [+]:

  1. Run the registry editor (regedit)
  2. Go to key: HKEY_LOCAL_MACHINE\Software\Synaptics\SynTP\Defaults\
  3. Here create a new key as a DWORD and name it HasBothButtonFeature and set the value to 1.
  4. Log off and Log on again

It worked fine for me.

Code Snippet for Determining How Two Intervals Overlap

| Comments

The following pieces of code help figure out how two intervals overlap, and provides helper methods to represent them in a way that is useful for debugging purposes. This job is quite easy to accomplish, but since I’ve written it too many times from scratch, I put them in the following gist.

The IntervalOverlapKinds.cs file defines the IntervalOverlapKinds enumeration. The interval detection is carried out in the static methods of the IntervalOverlap class.

A Code Snippet for Searching and Highlighting a Token or String in a RichTextBox

| Comments

Suppose that you intend to find a string or a token (i.e., whole word, instead of a substring) and change their color in some Windows Forms RichTextBox. The following code snippets will help. The FindStringAndSetColor method looks for instances of an arbitrary string in the contents of the RichTextBox, while the FindTokenAndSetColor method looks for whole words (tokens).

How to Explore Special Folders (Like GAC) in Windows Explorer

| Comments

In normal situations you cannot view the content of special folders, such as Windows/assembly or Windows/fonts, and so on. The way these folders are shown are set through the desktop.ini file in each of these folders, which is normally hidden and protected. One trick that I learned from here [+] is described below. Open a command prompt and type:

1
2
3
cd /d %windows%\assembly
attrib -r -h -s desktop.ini
ren desktop.ini desktop.bak

Using the above commands, we kill the desktop.ini file, which will cause Windows Explorer to successfully open and explore the real contents of the folder.

One Reason to Prefer Readonly to Const in C#

| Comments

First off, let’s talk about what’s going on in C# compiler when you use const or readonly in your field definitions. The const qualifier can be used with primitive data types, and strings only. When used, the value assigned to a const field, is inserted directly in all its references in the generated IL code. This is true about other assemblies too. Other assemblies that refer to that const field, are compiled as if they have used directly the value itself. This can be the source of problem that I’m going to talk about soon. readonly fields are run-time constants. They occupy some space in memory, and references to them are resolved at run-time, as if we have referred to an ordinary variable. Actually they are variables that resemble constants.

Imagine that you have created and released a project to public. Your project contains several assemblies in form of .dll files. They make use of some constant value in one of the .dll files, e.g., SomeLibrary.dll stores a constant value in one of its classes, e.g.,

1
2
3
4
5
6
public class Options
{
   ...
   public const int NetworkTimeout = 2000;
   ...
}

You realize that the value assigned to NetworkTimeout is less than expected, so you decide to update SomeLibrary.dll files in all your customer machines with a new one in which NetworkTimeout is set to 3000. But it will not work. Because all references to NetworkTimeout in other assemblies have been replaced with the constant 2000, and the new value will not be fetched any more. In this case the problem will be solved only when all other assemblies are rebuilt. No other update scenarios will do.

But if we have used readonly instead of const the problem would have been solved with updating SomeLibrary.dll only.

1
2
3
4
5
6
public class Options
{
    ...
    public static readonly int NetworkTimeout = 2000;
    ...
}

The static modifier has been added only to make the two codes above compatible. Note that all const fields are also static, but readonly fields can be either static or an instance field.

Assigning Values to Private Fields Using Reflection

| Comments

Suppose that you have a class with various non-public fields, e.g., the class named ClassToTest below servers as a good example.

1
2
3
4
5
6
7
8
9
public class ClassToTest
{
    public int SomeNumber { get; set; }

    private int m_somePrivateProperty { get; set; }
    private int m_somePrivateVar;

    private static int s_someStaticNumber;
}

And suppose that we desire to assign some value to the private variable m_somePrivateVar, and the private property m_somePrivateProperty. The approach is to iterate through the fields of the ClassToTest type to find the desired field. If it is a variable we should type-cast it to FieldInfo, and if it is a property we should type-cast it to PropertyInfo. Then we should call the SetValue method appropriately. This is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ClassToTest c = new ClassToTest();

Type t = typeof(ClassToTest);
foreach (var member in t.GetMembers(BindingFlags.Instance |
                                    BindingFlags.NonPublic |
                                    BindingFlags.Public))
{
    if (member.Name == "m_somePrivateVar")
    {
        // changing the variable
        FieldInfo fi = (FieldInfo)member;
        fi.SetValue(c, 18);
    }
    else if (member.Name == "m_somePrivateProperty")
    {
        // changing the property
        PropertyInfo pi = (PropertyInfo)member;
        pi.SetValue(c, 13, null);
    }
}

Here we have successfully assigned values to selected private fields of our class.