Monday, February 8, 2010

Saving Multiple Files with the Same Name

If you need to save multiple files with the same name in the same directory, a common technique is to construct a file name adding an incremental counter to it, e.g. myfilename(1).txt, myfilename(2).txt, etc.

The method below allows you to create such a file name. It requires 1 parameter: a full file path. The method returns a FileInfo type.
It attempts first to construct a FileInfo object based on a file path, and then checks if such a file already exists. If it does not, the FileInfo object is returned. Otherwise, it constructs a new file name and checks for its existence until such a name no longer exists.

 

private static FileInfo GetFileInfo(string filePath)

{

    FileInfo fInfo = new FileInfo(filePath);

    string fileName = Path.GetFileNameWithoutExtension(filePath);

    string dirName = fInfo.DirectoryName;

    int counter = 1;

 

 

    while (fInfo.Exists)

    {

        string extension = fInfo.Extension;

        string nameProper = fileName + "(" + (counter++) + ")";

        filePath = Path.Combine(dirName, nameProper + extension);

        fInfo = new FileInfo(filePath);

        nameProper = String.Empty;

    }

    return fInfo;

}

Tuesday, February 2, 2010

Have DataGridView Scroll Down Automatically

The trick to having a WinForm DataGridView scroll down automatically to the last row as you populate it is to use the DataGridView CurrentCell property. Just set it to a cell in the last added row.
The DataGridView also has CurrentRow property but that is read-only.

Friday, January 8, 2010

Get TreeNode from Full Path in Winform

This is a recursive method that finds a TreeNode in a .NET TreeView control from its full path.

public TreeNode GetNodeFromPath(TreeNode node, string path)
        {
        TreeNode foundNode = null;
        foreach (TreeNode tn in node.Nodes)
        {
            if (tn.FullPath == path)
            {                 
                return tn;
            }
            else if (tn.Nodes.Count > 0)
            {
                foundNode = GetNodeFromPath(tn, path);
            }
            if (foundNode != null)
                return foundNode;
        }
        return null;
        }


Thursday, January 7, 2010

List and ForEach

Let's say you have a List of strings in C# and you add each element of the List to a StringBuilder.

StringBuilder sb = new StringBuilder();
List  <string> list = new List <string>();
list.add("one");
list.add("two");
list.add("three");

You could do the following loop:

foreach(var item in list){
  sb.Append(item); 
}
An alternative method to achieve the same functionality would go like this:
list.ForEach(item =>sb.Append(item));

With this method you save 2 lines of code and improve readability.

Tuesday, December 22, 2009

Get User Permissions on TFS team project

This code is based on the listing in http://social.msdn.microsoft.com/Forums/en/tfsadmin/thread/9f977d37-23d8-4b07-a5dd-6cdc6d9dc6a6

Requires 2 parameters: windows user id, and team project name
Returns a List of groups in the team project that the user has permissions for


public static List <string> GetAccountPermissions(string account, string projectName)
{
    List <string> groupList = new List <string>();
    String serverUri = @"http://serverName:8080/";
    // connect to the server
    TeamFoundationServer server = new TeamFoundationServer(serverUri);
    // get ICommonStructureService (later to be used to list all team projects)
    ICommonStructureService iss = (ICommonStructureService)server.GetService(typeof(ICommonStructureService));
    // get IGroupSecurityService (later to be used to retrieve identity information)
    IGroupSecurityService2 gss = (IGroupSecurityService2)server.GetService(typeof(IGroupSecurityService2));
    ProjectInfo[] allTeamProjects = iss.ListProjects();
    // iterate thru the team project list
    foreach (ProjectInfo pi in allTeamProjects)
    {
    // ProjectInfo gives you the team project's name, status, and URI.
        String teamProjectName = pi.Name;
        if (pi.Name == projectName)
        {
            Identity[] allProjectGroups = gss.ListApplicationGroups(pi.Uri);
            // iterate thru the project group list and get a list of direct members for each project group
            foreach (Identity projectGroup in allProjectGroups)
            {
                Identity pg = gss.ReadIdentity(SearchFactor.Sid, projectGroup.Sid, QueryMembership.Direct);
                foreach (String groupMemberSid in pg.Members)
                {
                    Identity m = gss.ReadIdentity(SearchFactor.Sid, groupMemberSid, QueryMembership.None);
                    if (m.AccountName == account)
                    {
                        groupList.Add(pg.DisplayName);
                    }
                }
            }
        }
    }
    return groupList;
}

Thursday, December 17, 2009

Check String For Null

It's easy to forget but C# has a handy method to check if a string is null or empty:

If(!String.IsNullOrEmpty(str))
...do something

Wednesday, December 9, 2009

Get List of Allowed Values in TFS Work Item Field

This is how you can obtain programmatically a list of allowed values in a TFS Work Item field (in the example below, in Priority field in Bug template):

TeamFoundationServer tfs = new TeamFoundationServer("myTFServer");

WorkItemStore wis = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));

Project teamProject = wis.Projects["myTeamProjectName"];

WorkItemType wit = teamProject.WorkItemTypes["Bug"];

 

FieldDefinition fd = wit.FieldDefinitions["Microsoft.VSTS.Common.Priority"];

AllowedValuesCollection avc = fd.AllowedValues;

 

foreach (var row in avc)

{

Console.WriteLine(row);

}