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

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

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 http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.
 
[^ ] 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>
               /// //        http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.
               //[^ ] 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  http://geekswithblogs.net/mnf/archive/2006/07/13/84942.aspx ,
 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);
                     builder1.Append(str);
                     builder1.Append(sEndBracket);
                      return builder1.ToString();
              }v

DataContractSerializer truncated string when used with MemoryStream,but works with StringWriter

We’ve used the following DataContractSerializeToXml method for a long time, but recently noticed, that it doesn’t return full XML for a long object, but  truncated it and returns XML string with the length of  multiple-of-1024 , but the reminder is not included.


 internal static string DataContractSerializeToXml<T>(T obj)
{
string strXml =
“”;
Type type= obj.GetType();//typeof(T)
DataContractSerializer serializer = new DataContractSerializer(type);
System.IO.
MemoryStream aMemStr = new System.IO.MemoryStream();
System.Xml.
XmlTextWriter writer = new System.Xml.XmlTextWriter(aMemStr, null);
serializer.WriteObject(writer, obj);
strXml = System.Text.
Encoding.UTF8.GetString(aMemStr.ToArray());
return strXml;


  
I tried to debug and searched Google for similar problems, but didn’t find explanation of the error. The most closed http://forums.codeguru.com/showthread.php?309479-MemoryStream-allocates-size-multiple-of-1024-( talking about incorrect length, but not about truncated string.

fortunately replacing MemoryStream to StringWriter according to

http://billrob.com/archive/2010/02/09/datacontractserializer-converting-objects-to-xml-string.aspx
fixed the issue.

  1: var serializer = new DataContractSerializer(tempData.GetType());
  2: using (var backing = new System.IO.StringWriter())
  3: using (var writer = new System.Xml.XmlTextWriter(backing))
  4: {
  5:     serializer.WriteObject(writer, tempData);
  6:     data.XmlData = backing.ToString();
  7: }

v

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

ObjectsOfMyClass.IsNullOrEmpty()


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

http://connect.microsoft.com/VisualStudio/feedback/details/94089/add-isnullorempty-to-array-class
   public static bool IsNullOrEmpty(this System.Collections.IEnumerable source)
       {
           if (source == null)
               return true;
           else
           {
               return !source.GetEnumerator().MoveNext();
           }
       }

http://stackoverflow.com/questions/8560106/isnullorempty-equivalent-for-array-c-sharp

Case-insensitive Contains extension for list of strings

I wanted to have case-insensitive Contains method for list of strings.
Overload Enumerable.Contains<TSource> Method (IEnumerable<TSource>, TSource, IEqualityComparer<TSource>) expects custom IEqualityComparer class.I was about to create my own class IgnoreCaseEqualityComparer : IEqualityComparer<string>,
but then found StringComparer.Create Method, that allow to use standard class.

public static bool ContainsString(this IEnumerable<string> collection, string toFind, bool ignoreCase = true)
{
return collection.Contains(toFind,
StringComparer.Create(CultureInfo.InvariantCulture, ignoreCase));
}