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.

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 http://cache.codeplex.com/ 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(http://support.sharpcrafters.com/discussions/problems/1211-nlog-weaver-version-error).
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.2.1.1.12toolsPostSharp.Toolkit.Diagnostics.Weaver.NLog.dll”/>
  <Using File=”……..packagesPostSharp.Toolkit.Diagnostics.2.1.1.12toolsPostSharp.Toolkit.Diagnostics.Weaver.dll” /> –>
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=”http://support.sharpcrafters.com/discussions/problems/1264/r?go=aHR0cDovL3N1cHBvcnQuc2hhcnBjcmFmdGVycy5jb20vZGlzY3Vzc2lvbnMvcHJvYmxlbXMvMTI2NC9yP2dvPWFIUjBjRG92TDNOMWNIQnZjblF1YzJoaGNuQmpjbUZtZEdWeWN5NWpiMjB2WkdselkzVnpjMmx2Ym5NdmNISnZZbXhsYlhNdk1USTJOQzl5UDJkdlBXRklVakJqUkc5MlRETk9hbUZIVm5SWldFMTFZMGM1ZW1SSVRtOVpXRXAzVEcwNWVWcDVPSGhNYWtGMldUSTVkVnB0Ykc1a1dFcG9aRWRzZG1KcFduaGtWemt3; 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:LoggingProfiles>
    <dg:LoggingProfile Name=”Exceptions” OnExceptionOptions=”IncludeParameterType | IncludeParameterName | IncludeParameterValue | IncludeThisArgument” OnEntryLevel=”None” OnSuccessLevel=”None” />
  </dg:LoggingProfiles>
  <Multicast>

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

   </Multicast>

</Project>

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)
            {
                coll.Add(newItem);
            }
        }

         public static void AddRangeIfNotNullOrEmpty( this List coll, IEnumerable newItems) where T : class
        {
            if (!newItems.IsNullOrEmptySequence())
            {
                coll.AddRange(newItems);
            }
        }
 
  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 https://pikacode.com/Barankin/Fabrika-dveri/file/default/CRM/Common/Extensions/LinqExtensions.cs

EntLIb editor corrupts config files

I’ve tried to use Microsoft Enterprise Library(EntLIb) editor, as it was suggested in http://weblogs.asp.net/sukumarraju/archive/2011/11/07/configuring-wcf-service-to-utilise-enterprise-library-logging-application-to-log-data-to-database.aspx, but after changes all comments in config files were removed.
 
Always consider to move any Enterprise Library configurations to a separate file before editing.