Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, January 4, 2014

TFS API: Get Project Collection Team Members

I have been working extensively with TFS (Team Foundation Service) API, and enjoying the miscellaneous challenges therein. One such challenge was to display a list of valid team members to assign work items to. And following the TFS online experience, the Assign To field must display all the user oat the collection level.

I saw a couple of approaches using the IGroupSecurityService interface that is a part of the Microsoft.TeamFoundation.Server but it has been marked as obsolete and instead a hint is provided to use the better alternative which is IIdentityManagementService. So here is a simple code snippet on how to get a list of team members ordered alphabetically.

Please note that the collection variable is simply an instance of  the team project collection class

new TfsTeamProjectCollection(collectionUrl, credentials)

Also note that when developing using the TFS API, you will need the following assemblies and namespaces referenced:
using Microsoft.TeamFoundation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;

among others..

Here is the snippet::


Friday, October 5, 2012

A little recognition goes a long way

Blogging is an ambivalent activity. It is simultaneously the source of both gratifying sense of achievement, and at the same time, the source of the dreadful to-do chore that looms undone on your ever growing to-do list. It's an ugly sensation, being weighed down by your own device.. those evil to-do's.

But this post is not about that. It is more related to, or more precisely, due to one of those rare moments of recognition, that come unsolicited and utterly unexpected. That simple act of being recognized or thanked for your humble work and contribution to the infinitude of collective consciousness and knowledge base of the human civilization.

In this context, my humble work is an article I wrote for CodeProject almost 4 years ago, about implementing a custom Provider using the Workflow Foundation, which at the time was still fresh out of the oven of the Microsoft kitchen. It seems that it still serves some use after all:



So stay motivated and always B#!

Sunday, August 7, 2011

Custom Assembly Versioning with VS 2010 and MSBUILD

There is a plethora of resources that deal with auto incrementing build numbers and a wealth of plugins and other gizmos that manage assembly versioning. So why yet another article. The truth is that none of those option solved my problem. I needed something simple, easy to maintain and most importantly flexible with a local .NET flavour. So naturally I had to write my own humble solution.

One of the daunting tasks we often face when deploying assemblies, is managing assembly and product versions. In any “decent” .NET solution, there is a need to auto-increment the version with every successful build. For example, incrementing the duild part of the assembly version in this default scheme

Major.Minor.Build.Revision

Sometime, versioning requirements are more elaborate and demanding, we might want to append the build date as well as incrementing the build number, the version scheme might look like

Major.Minor.Build.DDMMYYYY

For that purpose I prefer using the AssemblyFileVersion instead of the AssemblyVersion. The former has an open format and can accommodate virtually any data, whereas the later, AssmeblyVersion is intended for use by the .NET framework and enforces a strict numbering scheme that yields compiler errors if infracted.

[assembly: AssemblyVersion("4.0.*")] //Strict Format, for framework use
[assembly: AssemblyFileVersion("4.0.20.110708")] //Flexible Format more suitable for product versions

This post describes how to leverage MSBUILD to automate this process and include it in the continuous integration pipeline.

Tips for managing multiple assembly.cs files

In a solution with multiple projects and corresponding multiple assembly.cs files where AssemblyVersion and AssemblyFileVersion are kept, it is better to have one such file shared amongst all assemblies. To achieve this, we use a very useful visual studio feature which is Adding Existing Items as Links

Add as Link in VS2010

We use this technique to create one shared assembly info file to be shared amongst all the projects in the solution. This shared file will contain the AssemblyVersion and AssemblyFileVersion assembly attributes are well as any solution wide values, whereas the individual project level assembly.cs will contain project specific information such as:

using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("POC.AssemblyVersioning.Common")]
[assembly: AssemblyCulture("")]

[assembly: Guid("bdf2e8b4-41aa-4569-b093-987439090dea")]

And here is how the solution structure will look like with implementing this scheme.. all for the sole purpose of facilitating modifying assembly version automatically.

solution view

And now to the more interesting part

Building custom MSBUILD tasks

The reason why I prefer to use custom tasks in build automation as opposed to other scripting solution, is the glaring fact that Build Tasks are plain C# classes, where you can use the goodies that the .NET framework offers. To create a Build Tasks all you have to do is:

  • Add references to the required .NET assemblies

references

  • Create a class that extends Microsoft.Build.Utilities.Task
  1. public class MyTask : Task
  2. {
  3.     // The only behaviour that need be overridden
  4.     public override bool Execute()
  5.     {
  6.         throw new NotImplementedException();
  7.     }
  8. }

<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="4.0" DefaultTargets="AutoIncrement" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask AssemblyFile="POC.AssemblyVersioning.BuildTask.dll" TaskName="BuildIncrementTask" />
  <Target Name="AutoIncrement">
    <BuildIncrementTask />
  </Target>
</Project>

And to simply invoke this task from a command line, we use this familiar syntax, assuming that the msbuild file was saved as sample.proj

msbuild sample.proj /t:AutoIncrement

Putting it all together!

After having acquainted ourselves with MSBUILD tasks and thought about having one shared assembly file info that hosts the AssemblyVersion and AssemblyFileVersion attributes, I introduce here a simple way to go about updating those attributes through this simple custom task. The task is based on file I/O where the contents of the shared assembly info will be parsed, the attributes update and incremented (or transformed to the desired format) and the content re-written back to the file. Here is the source code for the simple build tasks that will perform the file manipulation. This is for illustration purposes and intended only as a guide to creating your own build task. I encourage you to.

 

  1. public class AutoIncrementTask : Task
  2. {
  3.     private const string VersionPattern = @"\[assembly: AssemblyFileVersion\(\""(\d{1}).(\d{1}).(\d{1,}).(\d{6})""\)\]";
  4.     public string AssemblyInfoPath { get; set; }
  5.         
  6.     public override bool Execute()
  7.     {
  8.         try
  9.         {
  10.             if (String.IsNullOrEmpty(AssemblyInfoPath))
  11.                 throw new ArgumentException("AssemblyInfoPath must have a value");
  12.  
  13.             string[] content = File.ReadAllLines(AssemblyInfoPath, Encoding.Default);
  14.             var rx = new Regex(VersionPattern);
  15.  
  16.             var newContent = new List<string>();
  17.             content.ToList().ForEach(line =>
  18.                                             {
  19.                                                 if (rx.IsMatch(line))
  20.                                                     line = VersionMatcher(rx.Match(line));
  21.                                                 newContent.Add(line);
  22.                                             });
  23.  
  24.             File.WriteAllLines(AssemblyInfoPath, newContent);
  25.  
  26.         }
  27.         catch(Exception ex)
  28.         {
  29.             Console.Out.WriteLine(ex);
  30.             return false;
  31.         }
  32.  
  33.         return true;
  34.     }
  35.  
  36.     private string VersionMatcher(Match match)
  37.     {            
  38.         int major = int.Parse(match.Groups[1].Value);
  39.         int minor = int.Parse(match.Groups[2].Value);
  40.         int build = int.Parse(match.Groups[3].Value);
  41.         string revision = match.Groups[4].Value;
  42.  
  43.         Console.WriteLine("AutoIncrement Assembly {0}", Path.GetFileName(AssemblyInfoPath));
  44.         Console.WriteLine("Current matched version: {0}.{1}.{2}.{3}", major, minor, build, revision);
  45.  
  46.         ++build;
  47.         revision = String.Format("{0}{1}{2}", DateTime.Now.Year.ToString().Substring(2), String.Format("{0:d2}", DateTime.Today.Month), String.Format("{0:d2}", DateTime.Today.Day));
  48.         Console.WriteLine("Incremented to version: {0}.{1}.{2}.{3}", major, minor, build, revision);
  49.  
  50.         string result = match.Result("[assembly: AssemblyFileVersion(\"$1.$2.{0}.{1}\")]");
  51.         return String.Format(result, build, revision);
  52.     }
  53. }

And here is the corresponding xml MSBUILD file:

<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="4.0" DefaultTargets="IncrementBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask AssemblyFile="PATH_TO_TASK_DLL" TaskName="AutoIncrementTask" />
  <Target Name="IncrementBuild">
    <AutoIncrementTask AssemblyInfoPath="..\SharedAssemblyInfo.cs" />
  </Target>
</Project>

As you can see, I chose the AssemblyFileVersion as the target for custom product and assembly versioning because there are no compile time checks on the the format of the version and because a product version is more end-user and business stakeholder friendly than the automatic build numbers used internally by the .NET framework.

You can include the previous build task as a step in the build process capitalizing on the MSBUILD command line capabilities.

Hope this helped…

Stay #

Saturday, July 9, 2011

You “Try”… and what do you “Catch”… A TryCatchException!

This is posted without much ranting, hoping that the humour and the pun is evident and the code snippet self-explanatory. This code was written by someone who apparently regarded the try{} catch {} construct itself error prone and decided to catch a TryCatchException.

try
{
    //Some Magic Code here
}
catch (Exception ex)
{
    var exceptionEntry = new TryCatchException("Method error", ex);
    throw exceptionEntry;
}

I have to admit this one is an original. I particularly like the additional detail (that is completely useless) “Method error”


Code Responsibly.

Tuesday, June 28, 2011

When 55 arguments are just about enough!!

In Robert Martin’s “a.k.a Uncle Bob” Clean Code book, he classifies Niladic functions (that have Zero arguments) as the best well behaved functions that are ideal to write and deal with; Monadic and Dyadic functions (that have 1 and 2 arguments respectively) comes as a second best. Anything Polyadic (with more than three arguments) is just pure evil and requires justification.

I wonder though how he would feel about a function with 55 arguments!! The following is just the signature of this function

(Int32,Int32,String,Int32,Int32,String,Int32,Int32,String,Int32 ,String,String,String,Int32,Int32,String,Int32,String,Int32,String ,Int32,String,Int32,Int32,Int32,DateTime,DateTime,String,String ,DateTime,DateTime,String,String,DateTime,DateTime,String,String ,String,String,String,Decimal,Decimal,Decimal,Decimal,Decimal,Decimal ,Int32,Int32,Int32,Int32,Int32,Int32,String,Int32,String)

If I were to meet that developer who wrote that function, I would simply ask, WTF were you thinking!?

May we survive the coding horrors yet another day!

Stay#

Wednesday, June 23, 2010

Design Patterns Part I :: Composed LINQ queries using the Decorator Pattern

This Blogs series will explore practical uses and applications of design patterns in day to day development practices, using practical examples in C#. The first Blog (one of hopefully many more to come) will cover the Decorator Pattern.

Introduction and Concepts

Let’s kick off this post with some theory. According to the GoF, the intent of the decorator design pattern is to
“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality”
That was quoted from their seminal work Design Patterns: Elements of Reusable Object-Oriented Software

In my humble opinion, one of the greatest pleasures working in software development is when we can successfully implement a pattern, not through a premeditated intent but through natural and organic development of the code at hand. We spot the variation and try to encapsulate it and then lo and behold we end up using one pattern or another fulfilling its intent and purpose. I think a the holy grail of OO software developers (a slightly conceited statement perhaps) is to identify the what is common and what varies in any given requirement and then find a way to encapsulate that change making future (and almost inevitable requirement changes) relatively easy to implement.

After that brief techno-rant. We can go back to our main topic. The Decorator Design Pattern. Conceptually, here is how the pattern looks like:


The decorator pattern allows me to create a chain of objects (trail of decorator objects) namely, the decorators that are responsible for the new functionality, and ends with the original object. And the call chain looks like:



This is not to be confused with a linked list. Rather it should be regarded as a collection of optional decorating objects.

One classic example of this pattern is the stream I/O library. For any particular stream there is only one input, but there can zero or more actions to perform on the input stream. For instance, as in the example below, I can read from a memory stream, filter the stream and then read it using a custom stream reader. All these components (the later two are custom objects) implement the stream abstract class and accept a stream object in their constructors. the chain of calls looks like this:


Stream filteredMemoryStream =
                new StreamReader(new StreamFilter(new MemoryStream()));

Query Decorators


Personally, I use the decorator pattern to solve the problem of decomposing LINQ queries into more granular and reusable parts. A client can call several LINQ queries that are similar but only have minor variations. The direct result of this is LINQ code duplicated in every query. Another side effect is the tight coupling between the calling client and query composition.

The fictitious example I use here assumes we're querying an Employees repository and there are multitude of queries that might contain the same expressions and clauses. Say, we need to get all employees who are managers. Another requirement is what we get all employees who are managers and of certain age. We may then need to get the top %20 of those managers. All these extra queries are transformed into reusable decorators as follows:



As a direct result of this design, the query composition can be chained inside a factory that instantiates the desired query based on simple conditional logic of perhaps some configuration file:


public class EmployeeQueryFactory
{
    public static QueryComponent<Employee> GetQuery()
    {
        /*
         * We decouple the calling client from the query component instantiation
         * by using this factory method where we encapsulate all conditional
         * logic that determines which query component to instantiate
         * */

        //Get all employees who are contractees
        return new ContracteesQuery(new EmployeeQuery());

        //Get all managers older than 50
        return new AgeLimitQuery(new ManagersQuery(new EmployeeQuery()), 50);

        //Get top %20 of all contractees older than 30
        return new Top20PercentQuery(new AgeLimitQuery(new ContracteesQuery(new EmployeeQuery()), 30));
    }
}


And just to add more clarity to the example at hand, I add a simple implementation of the QueryComponent and QueryWrapper respectively, along with a concrete implementation of each.

public abstract class QueryComponent<T>
{
    public abstract IQueryable<T> Query();
}


public class EmployeeQuery : QueryComponent<Employee>
{
    public override IQueryable<Employee> Query()
    {
        return new EmployeesRepository().GetAllEmployess().AsQueryable();
    }
}


public abstract class QueryWrapper<T> : QueryComponent<T>
{
    protected readonly QueryComponent<T> QueryComponent;

    protected QueryWrapper(QueryComponent<T> queryComponent)
    {
        QueryComponent = queryComponent;
    }


    protected IQueryable<T> CallTrailer()
    {
        return null != QueryComponent ? QueryComponent.Query() : null;
    }
}


public class ContracteesQuery : QueryWrapper<Employee>
{
    public ContracteesQuery(QueryComponent<Employee> queryComponent)
        : base(queryComponent)
    {
    }


    public override IQueryable<Employee> Query()
    {
        return CallTrailer().Where(p => p.IsContractee);
    }
}

Lastly, as with every post. I leave you with this quote by Christopher Alexander
"We are searching for some kind of harmony between two intangibles: a form which we have not yet designed and a context which we cannot properly describe."

Code well and Stay#!

Friday, May 21, 2010

Developer Tunnel Vision Syndrome

I wanted my very first post to be on a rather happier note that celebrates the beauty of learning functional programming with F#, or touts a technical triumph or a breakthrough of mine. But the post is going to be more sombre and talk about Developer Tunnel Vision; a syndrome I have been suffering from over the past couple of days until the eventual breakthrough this morning.

I say Tunnel Vision, because developers often spend inordinate amounts of time working exclusively in one technology or one programming language (C# for argument’s sake) and forget to touch on some neglected skills like thinking in T-SQL and finding solutions using solely set algebra and set operations.

To give you a concrete example, I present the problem I had (with contrived data for demonstration purposes): given a list of values (say, velocities) with start/end time range for each velocity; in tabular form the input data looks like:

Velocity    StartTime               EndTime     
--------    -------------------     -------------------
40
         2009-11-24 05:45:43     2009-11-25 04:23:18
0           2009-11-25 04:23:18     2009-11-26 07:00:00
0           2009-11-26 07:00:00     2009-11-27 06:23:18
40          2009-11-27 06:23:18     2009-11-27 23:57:22
0           2009-11-27 23:57:22     2009-11-28 09:00:00
0           2009-11-28 09:00:00     2009-11-30 01:57:22
0           2009-11-30 01:57:22     2009-11-30 11:00:00
0           2009-11-30 11:00:00     2009-12-02 03:57:22
0           2009-12-02 03:57:22     2009-12-04 05:57:22
40          2009-12-04 05:57:22     2009-12-04 15:45:43


Using only plain set operations in T-SQL, collapse date ranges for matching velocities, to produce the following:

Velocity    StartTime               EndTime       
--------    -------------------     -------------------
40          2009-11-24 05:45:43     2009-11-25 04:23:18
0           2009-11-25 04:23:18     2009-11-27 06:23:18
40          2009-11-27 06:23:18     2009-11-27 23:57:22
0           2009-11-27 23:57:22     2009-12-04 05:57:22
40          2009-12-04 05:57:22     2009-12-04 15:45:43

Simple at the first glance! So I went forward equipped with what I considered a solid knowledge in SQL and set algebra and started working on the solution.

I was amazed at how difficult it was, because I recently had spent the good part of the past year or so thinking exclusively in Object Oriented way and I felt my mind struggled to rid itself of inheritance and polymorphism and to think in joins and unions. I eventually got to the answer, not the most elegant or succinct, but a good answer nonetheless (it is irrelevant to post the solution here).

This morning however, I recanted yesterday’s solution and came up with a 3-line C# LINQ query that produced exactly the desired result.

var collapsedRecords = records
                .Aggregate(new List<Record>(), groupingFunctor)
                .GroupBy(dco => dco.GroupId, (k, v) => v)
                .Select(v => new Record
                                 {
                                     Velocity = v.First().Velocity,
                                     ST = v.Min(_ => _.ST),
                                     ET = v.Max(_ => _.ET)
                                 });

Along with the following simple plumbing:




Func<List<Record>, Record, List<Record>> groupingFunctor =
                (list, record) =>
                    {
                        record.GroupId = !list.Any() ? 1 :
                                        ((list.Last().Velocity == record.Velocity)
                                                 ? list.Last().GroupId
                                                 : list.Last().GroupId + 1);
                        list.Add(record);
                        return list;
                    };

And

    //simple model for the records
    internal class Record
    {
        public int Velocity { get; set; }
        public int GroupId { get; set; } //helper property
        public DateTime ST { get; set; }
        public DateTime ET { get; set; }
    }

Now we can digress and start raving about the accumulator pattern in the LINQ Aggregate extension method, or we can get to the point of this post:

Most of us juggle more than one language and/or technology. And in order to stay sharp (no pun intended!) we must practice, practice and then practice some more lest time and negligence dulls the edge of our skills.

Finally, I leave you with a bit of Charles Darwin:
"I have steadily endeavored to keep my mind free so as to give up any hypothesis, however much beloved (and I cannot resist forming one on every subject), as soon as the facts are shown to be opposed to it."