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  http://stackoverflow.com/questions/4023462/how-do-i-automatically-display-all-properties-of-a-class-and-their-values-in-a-s

/// and  http://stackoverflow.com/questions/852181/c-printing-all-properties-of-an-object?lq=1

///  </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)

continue;

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 http://stackoverflow.com/questions/2210309/how-to-find-out-if-a-property-is-an-auto-implemented-property-with-reflection </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



http://weblog.west-wind.com/posts/2010/Dec/27/Hosting-the-Razor-Engine-for-Templating-in-NonWeb-Applications

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 

(http://stackoverflow.com/questions/7517968/how-to-compare-2-datatables/7518025%237518025) 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:http://schemas.datacontract.org/myNamespace’ 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=4.0.0.0, 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.

    [KnownType(typeof(MyclassType))]
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.