Adding PostSharp to new projects, when it’s installed for some projects in solution.

Once PostSharp  is installed in  solution’s packages folder for some project(s), I often need to add PostSharp to another project in the same solutionSection “Adding PostSharp to your project using PostSharp HQ” of documentation described the process quite well.

[solution root ]packagesPostSharp.

Also you need to ensure that the project is checked out,i.e. not readOnly.

Helper method to Replace/Remove characters that do not match the Regular Expression

I have a few fields, that use regEx for validation. In case if provided field has unaccepted characters, I don’t want to reject the whole field, as most of validators do, but just remove invalid characters.
 I am expecting to keep only Character Classes for allowed characters and created a helper method to strip unaccepted characters.
The allowed pattern should be in Regex format, expect them wrapped in square brackets. function will insert a tilde after opening squere bracket , according to
[^ ] at the start of a character class negates it – it matches characters not in the class.
I anticipate that it could work not for all RegEx describing valid characters sets,but it works for relatively simple sets, that we are using.

        /// <summary>
               /// Replaces  not expected characters.
               /// </summary>
               /// <param name=”text”> The text.</param>
               /// <param name=”allowedPattern”> The allowed pattern in Regex format, expect them wrapped in brackets</param>
               /// <param name=”replacement”> The replacement.</param>
               /// <returns></returns>
               /// //
               //[^ ] at the start of a character class negates it – it matches characters not in the class.
               //Replace/Remove characters that do not match the Regular Expression
               static public string ReplaceNotExpectedCharacters( this string text, string allowedPattern,string replacement )
                     allowedPattern = allowedPattern.StripBrackets( “[“, “]” );
                      //[^ ] at the start of a character class negates it – it matches characters not in the class.
                      var result = Regex .Replace(text, @”[^” + allowedPattern + “]”, replacement);
                      return result;

static public string RemoveNonAlphanumericCharacters( this string text)
                      var result = text.ReplaceNotExpectedCharacters(NonAlphaNumericCharacters, “” );
                      return result;
        public const string NonAlphaNumericCharacters = “[a-zA-Z0-9]”;

There are a couple of functions from my StringHelper class ,
 that are used here.
               /// <summary>
               /// ‘StripBrackets checks that starts from sStart and ends with sEnd (case sensitive).
               ///           ‘If yes, than removes sStart and sEnd.
               ///           ‘Otherwise returns full string unchanges
               ///           ‘See also MidBetween
               /// </summary>
               /// <param name=”str”></param>
               /// <param name=”sStart”></param>
               /// <param name=”sEnd”></param>
               /// <returns></returns>
               public static string StripBrackets( this string str, string sStart, string sEnd)
                      if (CheckBrackets(str, sStart, sEnd))
                           str = str.Substring(sStart.Length, (str.Length – sStart.Length) – sEnd.Length);
                      return str;
               public static bool CheckBrackets( string str, string sStart, string sEnd)
                      bool flag1 = (str != null ) && (str.StartsWith(sStart) && str.EndsWith(sEnd));
                      return flag1;

               public static string WrapBrackets( string str, string sStartBracket, string sEndBracket)
                      StringBuilder builder1 = new StringBuilder(sStartBracket);
                      return builder1.ToString();

PostSharp deployment to build machine- use Setup installation, not NuGet package.

PostSharp has well documented different methods of installation. I’ve chosen installing NuGet packages, because according to 
NuGet is the easiest way to add PostSharp to a project without installing the product on every machine.
However it didn’t work well for me. I’ve added PostSharp NuGet package to one project in the solution.
 When I wanted to use PostSharp in other project, Visual Studio tab showed that PostSharp is not enabled for this project
I’ve added the NuGet package to the new project, which installed a new version of the package in the new Packages subfolder.
When I wanted to refer PostSharp from the third project, I’ve ended up with another version of PostSharp installed.
Additionally multiple versions of Diagnostics were created. It definitely causes confusion and errors.
More problems we experienced on build server. According to Using PostSharp on a Build Server
“If you chose to deploy PostSharp in the source repository, it does not need to be installed specifically on the build server. “
It didn’t work on our build server.
I kept getting errors “The “AddIns” parameter is not supported by the “PostSharp21″ task.” and “The “DisableSystemBindingPolicies” parameter is not supported by the “PostSharp21″ task.”

From my experience the only way to have the latest version of PostSharp working on the build server is to install it using Setup as described in Deploying PostSharp with the Setup Program
Gael acknowledged the issues with possible version conflicts. see

Convert collections of enums to collection of strings and vice versa

Recently I needed to convert collections of  strings, that represent enum names, to collection of enums, and opposite,  to convert collections of   enums  to collection of  
strings. I didn’t find standard LINQ extensions.
However, in our big collection of helper extensions I found what I needed – just with different names:
/// <summary>
/// Safe conversion, ignore any unexpected strings

/// Consider to name as Convert extension
/// </summary>
/// <typeparam name=”EnumType”></typeparam>
/// <param name=”stringsList”></param>
/// <returns></returns>
public static
List<EnumType> StringsListAsEnumList<EnumType>(this List<string> stringsList) where EnumType : struct, IComparable, IConvertible, IFormattable
List<EnumType> enumsList = new List<EnumType>();
foreach (string sProvider in stringsList)
    EnumType provider;
    if (
EnumHelper.TryParse<EnumType>(sProvider, out provider))
    return enumsList;

/// <summary>
/// Convert each element of collection to string
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <param name=”objects”></param>
/// <returns></returns>
public static
IEnumerable<string> ToStrings<T>(this IEnumerable<T> objects)
return objects.Select(en => en.ToString());

C# tip: do not use “is” type, if you will need cast “as” later


We have a debate with one of my collegues, is it agood style to check, if the object of particular style, and then cast  as this  type. The perfect answer of Jon Skeet   and answers in Cast then check or check then cast? confirmed my point.

    var coke = cola as CocaCola;
    if (coke != null)
        // some unique coca-cola only code
    if (cola is CocaCola)
        var coke =  cola as CocaCola;
        // some unique coca-cola only code here.

Code review recommendations and Code Smells

Some time ago Twitter told that I am similar to Boris Lipschitz . Indeed he is also .Net programmer from Russia living in Australia.
I‘ve read his list of Code Review points and found them quite comprehensive. A few points  were not clear for me, and it forced me for a further reading.

In particular the statement “Exception should not be used to return a status or an error code.” wasn’t fully clear for me, because sometimes we store an exception as an object with all error details and I believe it’s a valid approach. However I agree that throwing exceptions should be avoided, if you expect to return error as a part of a normal flow.
Related link:

Another point slightly puzzled me
If Thread.Sleep() is used, can it be replaced with something else, ei Timer, AutoResetEvent, etc” . I believe, that there are very rare cases, when anyone using Thread.Sleep in any production code. Usually it is used in mocks and prototypes.

I had to look further to clarify “Dependency injection is used instead of Service Location pattern”.
Even most of articles has some preferences to Dependency injection, there are also advantages to use Service Location. E.g see  refers to Concluding Thoughts of Martin Fowler
The choice between Service Locator and Dependency Injection is less important than the principle of separating service configuration from the use of services within an application

The post had a link to excellent article Code Smells of Jeff Atwood, but the statement, that “code should not pass a review if it violates any of the  code smells” sound too strict for my environment.

In particular, I disagree with “Dead Code” recommendation “Ruthlessly delete code that isn’t being used. That’s why we have source control systems!”. If there is a chance that not used code will be required in a future, it is convenient to keep it as commented or #if/#endif blocks with appropriate explanation, why it could be required in the future. TFS is a good source control system, but context search in source code of current solution is much easier than finding something in the previous versions of the code.

Related links:



IsNullOrEmpty generic method for Array to avoid Re-Sharper warning

I’ve used the following extension method in many places.

public static bool IsNullOrEmpty(this Object[] myArr)
return (myArr == null || myArr.Length == 0);

Recently I’ve noticed that Resharper shows warning covariant array conversion to object[] may cause an exception for the following code


I’ve resolved the issue by creating generic extension method

public static bool IsNullOrEmpty<T>(this T[] myArr)
return (myArr == null || myArr.Length == 0);

Related links
   public static bool IsNullOrEmpty(this System.Collections.IEnumerable source)
           if (source == null)
               return true;
               return !source.GetEnumerator().MoveNext();