Monday, June 7, 2010

Open a Text File If It Is Used by Another Process

Use the FileStream class's Open method to open a file with FileShare.ReadWrite as a parameter. Then use StreamReader class supplying the FileStream object as a constructor argument:
FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);

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.