Thursday, June 3, 2010

Set Instance Property Value through Reflection

This is how you can set object property value using reflection:

Employee emp = new Employee();
PropertyInfo pi = emp.GetType().GetProperty("myPropertyName");
pi.SetValue(emp, "myValue", null);

This is how you read a value:

string value = pi.GetValue(emp, null);

To access all properties of an object:

foreach (PropertyInfo info in emp.GetType().GetProperties()){
    ....
}
Using reflection you can automatically populate a transfer object from a database record if the object property names and types are the same as the record names and types.

An example using a DataReader:

List <employee>list = new List <employee>();
while (dataReader.Read())
{
Employee emp = new Employee();
foreach (PropertyInfo info in emp.GetType().GetProperties())
{
   if (!DBNull.Value.Equals(dr[info.Name]))
      info.SetValue(emp, dr[info.Name], null);
}
list.Add(emp);
}
 
The resulting list will hold Employee records.





Wednesday, June 2, 2010

Object Class Names of the The Authorization Service

The IAuthorizationService interface exposes two methods you can use to obtain object class names available in TFS.

The first one is ListObjectClasses. It returns a string array of IDs of all defined object classes :

CSS_NODE
EVENT_SUBSCRIPTION
ITERATION_NODE
NAMESPACE
PROJECT

The other one is ListObjectClassActions. You need to supply an object class id as a string parameter to the method. It will return a string array of actions defined for a specified class. For example, if you supply CSS_NODE as a parameter, it will return the following action ids:

GENERIC_READ
GENERIC_WRITE
CREATE_CHILDREN
DELETE
WORK_ITEM_READ
WORK_ITEM_WRITE

Tuesday, June 1, 2010

Query Operator First

Let's say you have the following method that returns a FileInfo object from an array if the Name property equals a certain value:
public static FileInfo FindFile(FileInfo[] fileInfoArray, string name)
{           
    foreach (FileInfo fi in fileInfoArray)
    {
        if (fi.Name == name)
            return fi;
    }
    return null;
}
You can replace this method with a call to the query operator First :

FileInfo fileInfo = fileInfoArray.First(fi => fi.Name =="myFileName.txt");
Since the query operator First returns a single value, it forces immediate query evaluation.

Thursday, May 20, 2010

Get TFS Team Project Names

Here is a method that returns a List of names of team projects available at Team Foundation Server

public static List<string> GetProjects(TeamFoundationServer tfsServer)
        {
            List <string> listProjects = new List<string>();      

            ICommonStructureService iss = (ICommonStructureService)tfsServer.GetService(typeof(ICommonStructureService));           
            ProjectInfo[] projectInfo = iss.ListProjects();

            foreach (ProjectInfo pi in projectInfo)
            {
                listProjects.Add (pi.Name);
            }                                                

            return listProjects;
        }

Thursday, May 13, 2010

Some Registry Methods

Here are a couple of helper methods to work with Windows Registry:
The first method makes sure you get a reference to a registry subkey. If it does not exist it creates one first. The second one is a preferred way to read a registry value.



 public static RegistryKey GetKey(string RegKey)
 {
     RegistryKey Key = Registry.CurrentUser.OpenSubKey(RegKey, true);

     if (Key == null)
     {
         Key = Registry.CurrentUser.CreateSubKey(RegKey);
     }
     return Key;
}

public static string ReadRegistryValue(RegistryKey key, string regValName)
{
     string[] values = key.GetValueNames();
     if (values.Contains(regValName))
          return key.GetValue(regValName).ToString();
     else
          return String.Empty;
}

Thursday, February 25, 2010

Header Cell with CheckBox in DataGridView

This is my version of a class that displays a check box in a DataGridView Header cell.
This is based on the code from http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/827907ea-c529-4254-9b15-2e6d571f5c5b

It assumes that the check box is located in the first DataGridView column. It allows for column caption and provides built-in check/uncheck functionality. Play with x and y parameters to place the checkbox where you want in the header cell.

Here is a usage example:

DataGridViewColumn column = new DataGridViewCheckBoxColumn();
CheckBox ckBoxMaster = CheckBoxInHeader.CreateCheckBoxInHeader(column, 12, 4, "     Select All");
DataGridView1.Controls.Add(ckBoxMaster);


The class listing:

  class CheckBoxInHeader
    {
    public static CheckBox CreateCheckBoxInHeader(DataGridViewColumn column, int x, int y, string caption)
    {
        CheckBoxInHeader cbInHeader = new CheckBoxInHeader();
        CheckBox ckBox = cbInHeader.CreateCheckBox(column, x, y, caption);
        ckBox.CheckedChanged += new EventHandler(cbInHeader.ckBox_CheckedChanged);
        return ckBox;
    }

    private CheckBox CreateCheckBox(DataGridViewColumn column, int x, int y, string caption)
    {
        CheckBox ckBox = new CheckBox();
        //Get the column header cell bounds          
        Rectangle rect = column.DataGridView.GetCellDisplayRectangle(0, -1, true);
        ckBox.Size = new Size(18, 18);
        //play with check box position
        rect.Offset(x, y);
        //Change the location of the CheckBox to make it stay on the header
        ckBox.Location = rect.Location;
        column.Name = caption;
        return ckBox;
    }

    private void ckBox_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        DataGridView dgv = (DataGridView)cb.Parent;

        foreach (DataGridViewRow row in dgv.Rows)
        {

            row.Cells[0].Value = cb.Checked;
        }
    }

Thursday, February 18, 2010

Double-Click to Close WinForm ListBox

If you have a ListBox on a WinForm, and you want the double-click on a selected item to close the form, you need to create a handler for the ListBox double click event.
In the handling method, use the following code:
 private void listBox1_DoubleClick(object sender, EventArgs e)
        {
        if (listBox1.SelectedItem != null)
        {
            listBox1.FindForm().DialogResult = DialogResult.OK;
        }
        }
or, you could use a generic version of the above code:
 ListBox listBox = sender as ListBox ;
       if (listBox.SelectedItem != null)
       {
       listBox.FindForm().DialogResult = DialogResult.OK;
       }