AutoPropertiesToString helper method

I needed in ToString() method for a class to log auto-properties.  Below are two methods that I used

/// <summary>


/// </summary>

/// <param name=”obj”></param>

/// <param name=”declaredOnly”></param>

/// <returns></returns>

/// <remarks> Created to log  DeclaredOnly in the current class using GetType().GetProperties(), for full object dump other methods may be more appropriate

/// See

/// and

///  </remarks>

public static string AutoPropertiesToString( object obj, bool printNulls=false, bool declaredOnly=true)


BindingFlags flags = BindingFlags .Public |  BindingFlags.Instance;

if (declaredOnly) flags |= BindingFlags.DeclaredOnly;

var propertyInfos = obj.GetType().GetProperties(flags);

var sb = new StringBuilder();

foreach ( var info in propertyInfos)


if (info.IsAutoProperty())


var val = info.GetValue(obj, null);

if (printNulls == false && val == null)


var value = val ?? “(null)”;

sb.AppendLine(info.Name + “: ” + value);


return sb.ToString();

/// <summary>

/// It’s not fool proof, quite brittle

/// </summary>

/// <param name=”info”></param>

/// <returns></returns>

/// <remarks> from </remarks>

public static bool IsAutoProperty( this PropertyInfo info)


bool mightBe = info.GetGetMethod().GetCustomAttributes(typeof (CompilerGeneratedAttribute ),true ).Any();

if (!mightBe)


return false;


if (info.DeclaringType == null)

return false;

bool maybe = info.DeclaringType

.GetFields( BindingFlags.NonPublic | BindingFlags.Instance)

.Where(f => f.Name.Contains(info.Name))

.Where(f => f.Name.Contains( “BackingField”))

.Any(f => f.GetCustomAttributes(typeof (CompilerGeneratedAttribute ),true ).Any());
return maybe;


#net, #auto-properties, #tostring

Links for RazorEngine development.

We are using RazorEngine to generate emails based on .cshtml templates.
Below are a few links that I used when develop it

Case insensitive StringHelper.EnsureEndsWith

I’ve created an extension  method for string 
public static string EnsureEndsWith(this string str,string sEndValue,bool ignoreCase=true)
            if (!str.EndsWith(sEndValue, ignoreCase, CultureInfo.InvariantCulture))
                str = str + sEndValue;
            return str;

Read CSV files with multiple lines

I needed to read CSV files with columns, containing strings in double quotes. The problem was that there were new lines within the column. Fortunately I found the article that reads the strings with multiple lines 
Another article that I considered ,but haven’t used is

Methods to verify, are DataTables or DataSets the same.


I wanted to verify, are DataTables in DataSets the same. I found a few similar implementations on StackOverflow, but the one that I’ve selected 

( didn’t work and returned unexpectedly false, when comparing two cells with the same values

          tbl1.Rows[i][c]     2     object {long}
          tbl2.Rows[i][c]     2     object {long}
          tbl1.Rows[i][c] == tbl2.Rows[i][c]     false     
I found, that it should be used Equals instead of ==.
          Equals(tbl1.Rows[i][c], tbl2.Rows[i][c])     true
There are a few articles, explaining the difference and reasons behind it.
‘==’ Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it’ll just call the object version

Below are tested methods to  check, are  DataTables or DataSets the same
/// <summary>
        /// </summary>
        /// <param name=”tbl1″></param>
        /// <param name=”tbl2″></param>
        /// <returns></returns>
         public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2)
            if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)
                return false;

            for ( int i = 0; i < tbl1.Rows.Count; i++)
                for ( int c = 0; c < tbl1.Columns.Count; c++)
                   if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c]))
                        return false;
            return true;
       /// <summary>
        /// Compare content of all rows in the table.
        /// </summary>
        /// <param name=”ds1″> The DS1.</param>
        /// <param name=”ds2″> The DS2.</param>
        /// <returns></returns>
        public static bool  AreTablesTheSame( DataSet ds1, DataSet ds2)
            if (ds1 == null && ds2 == null)
                return true;
            if (ds1 == null || ds2 == null) //only one is null
                return false;
            if (ds1.Tables.Count != ds2.Tables.Count)
                return false;

            for ( int i = 0; i < ds1.Tables.Count; i++)
                if (! DataTableHelper.AreTablesTheSame(ds1.Tables[i] ,ds2.Tables[i]))
                    return false;
            return true;

Number of Unit test projects in Visual Studio solution

Some time ago I have discussion with my co-worker  how to organize test projects. 
Should we have a single test project that does all sorts of things and references every project?
It is good to have one integration test dll, but for unit tests, what is the point merging everything into one.

In ideal world I agree that small independent projects are better. Unfortunately we have  solution size limitations 
However, Visual Studio performance quickly degrades as the number of projects increases. Around the 40 project mark compilation becomes an obstacle to compiling and running the tests, so larger projects may benefit from consolidating test projects.
  • Single solution. If you work on a small system, create a single solution and place all of your projects within it.
  • Partitioned solution. If you work on a large system, use multiple solutions to group related projects together. Create solutions to logically group subsets of projects that a developer would be most likely to modify as a set, and then create one master solution to contain all of your projects. This approach reduces the amount of data that needs to be pulled from source control when you only need to work on specific projects.
  • Multiple solutions. If you are working on a very large system that requires dozens of projects or more, use multiple solutions to work on sub-systems but for dependency mapping and performance reasons do not create a master solution that contains all projects.
At the moment we decided to go with one huge integration test and one huge unit test projects.
And we constantly trying to keep reasonable (not too many) number of projects in the main solution. Unfortunately this number is quite big – 70+. 

Serialization error when property is declared as base class, but populated by derived class

I’ve receive  quite generic error Message :
 Type ‘MyclassType’ with data contract name ‘MyclassType:’ is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Type : System.Runtime.Serialization.SerializationException, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089

After investigation I found that the class that I tried to serialize, had a property declared of the base class, but at runtime derived class was assigned, and serialization was unable to resolve it.
The fix was simple- to add KnownType property to container class.

public class Mycontainer 
 MyBaseclass PropertyOfmyClass { get; set;}

public class  MyclassType : MyBaseclass
{ ….}

Unfortunately, the serialization time error message didn’t specify the name of container class , not the name of property. it makes harder to fix the error.

Upgrading PostSharp from ver 2.1 to new version 3.0

I was upgrading our solutions from PostSharp 2 to PostSharp 3. The small solution based on cache attribute from was upgraded without any problems.

Upgrading my main solution by installing nuget package PostSharp also was quite well. 
The only annoying thing was that installer added 
RequiresPostsharp.cs file to all projects, that already had SkipPostSharp=true setting and I had manually remove them
The issue was reported at
but Gael unfortunately  considers this behavior “by design“.
More work was to convert   psproj files PostSharp.Toolkit.Diagnostics ver 2.1 to new PostSharp.Patterns.Diagnostics.3.0.
There was no documentation.I’ve only found a short notice at the bottom of 

PostSharp Toolkits 2.1 need to be uninstalled using NuGet. Instead, you can install PostSharp Pattern Libraries 3 from NuGet. 
Namespaces and some type names have changed. 
Uninstall for 2.1 suggested to remove NLog nuget package, which we are using regardless of PostSharp.
I’ve run 
Install-Package PostSharp.Patterns.Diagnostics.NLog

The install of PostSharp.Patterns.Diagnostics.NLog didn’t like the latest version of Nlog, but Gael 
fixed it recently(
The installs haven't changed the content of PSPROJ files and I had  to manually update them.
1. Deleted old references to DLL and inserted dg:LoggingProfiles profile element
 <!–<Using File=”……..packagesPostSharp.Toolkit.Diagnostics.NLog.”/>
  <Using File=”……..packagesPostSharp.Toolkit.Diagnostics.” /> –>
2. After advise from Gael  I’ve  removed the Task element and change <Data Name="XmlMulticast">into simply <Multicast>.
3. I’ve also replaced namespace and DLL names in LogAttribute xmlns properties to be “clr-namespace:PostSharp.Patterns.Diagnostics;assembly:PostSharp.Patterns.Diagnostics”
The psproj file becomes similar to the following and seemed to work.
<?xml version=”1.0″ encoding=”utf-8″?>
< Project xmlns=”; xmlns:dg=”clr-namespace:PostSharp.Patterns.Diagnostics;assembly:PostSharp.Patterns.Diagnostics”>
  <Property Name=”LoggingBackEnd” Value=”nlog” />
  <Using File=”..packagesPostSharp.Patterns.Diagnostics.3.0.26toolsPostSharp.Patterns.Diagnostics.Weaver.dll” />
  <Using File=”..packagesPostSharp.Patterns.Diagnostics.NLog.3.0.26toolsPostSharp.Patterns.Diagnostics.Weaver.NLog.dll” />
    <dg:LoggingProfile Name=”Exceptions” OnExceptionOptions=”IncludeParameterType | IncludeParameterName | IncludeParameterValue | IncludeThisArgument” OnEntryLevel=”None” OnSuccessLevel=”None” />

      <LogAttribute xmlns=”clr-namespace:PostSharp.Toolkit.Diagnostics;assembly:PostSharp.Toolkit.Diagnostics” AttributeTargetAssemblies=”Applications.MyApp” AttributeTargetTypes=” Applications.MyApp.MyCustomer” AttributeTargetMembers=”*” OnExceptionLevel=”Warning” OnExceptionOptions=”IncludeParameterValue” />



It was deployed to CI test environment, where we noticed delays and timeouts. I found that despite that only  OnExceptionLevel and  OnExceptionOptions were specified, the new LogAttribute generated verbose trace information, which caused severe performance hit.

4. I had to change LogAttribute to LogExceptionAttribute and remove OnExceptionLevel and OnExceptionOption properties.

AddIfNotNull collection extensions

I want to post a few recently created collection extensions to write in one line, what otherwise takes 2 or more
     public static void AddIfNotNull( this IList coll, T newItem) where T : class
            if (newItem != null)

         public static void AddRangeIfNotNullOrEmpty( this List coll, IEnumerable newItems) where T : class
            if (!newItems.IsNullOrEmptySequence())
  public static void AddIfNotContains( this Dictionary dictionary,  TKey key, TValue value)
            if (!dictionary.ContainsKey(key))
                dictionary.Add(key, value);
The methods use
public static bool IsNullOrEmptySequence(this IEnumerable c)
                      return (c == null || !c.Any() );

I’ve also found a few extensions, that could be useful in

EntLIb editor corrupts config files

I’ve tried to use Microsoft Enterprise Library(EntLIb) editor, as it was suggested in, but after changes all comments in config files were removed.
Always consider to move any Enterprise Library configurations to a separate file before editing.