Harri's profilePainKiller´s C# CornerBlogListsNetworkMore Tools Help

Blog


    Usefull stuff unsorted

    I have a very bad memory, this blogg helps med remember som tips and tricks that will make my life as a system developer easier. Today I have this tips:

    XML Documentation Comments

    This was erlier integrated in Visual Studio now it´s a hidden and for many new developers maby unknown. If you compile with the switch /doc you will have nice documentation of all you comments added with ///

    Like this for example:

    /// <summary> /// This class performs an important function. /// </summary>
    public class MyClass{}

    Read more about this feature: http://msdn.microsoft.com/en-us/library/b2s063f7(VS.80).aspx

    C# Preprocessor Directives

    A nice feature, today I want to mark a class with the preprocessor directive #warning because I want this to be there until we investigated if the class should be deleted or not. Add a //TODO is not enough a warning is stronger and forces us to dont miss this before deployment.

    Read more about this here: http://msdn.microsoft.com/en-us/library/ed8yd1ha(VS.71).aspx

    Guidlines

    Running FxCop on your assemblys is a good practice to keep your code clean and efficient. FxCop not only finds code that break “best practice” rules it also suggest´s how to correct them.

    Some tips:

    Properties should not return arrays

    "Properties that return arrays are prone to code inefficiencies.
    Consider using a collection or making this a method.
    See the design guidelines for more information."

    Specify format provider

    "If an overload exists that takes an IFormatProvider
    argument, it should always be called in favor of an
    overload that does not. Some methods in the runtime
    convert a value to or from a string representation
    and take a string parameter that contains one or more
    characters, called format specifiers, which indicate
    how the value is to be converted. If the meaning of
    the format specifier varies by culture, a formatting
    object supplies the actual characters used in the string
    representation. In scenarios where sorting and comparison
    behavior should never change between cultures, specify
    CultureInfo.InvariantCulture, otherwise, specify CultureInfo.CurrentCulture."

    Example:
    LastRefresh = Convert.ToInt64(marketFields[10], CultureInfo.InvariantCulture)

    Download FxCop : http://www.microsoft.com/downloads/details.aspx?familyid=3389F7E4-0E55-4A4D-BC74-4AEABB17997B&displaylang=en

    Enum ToString not obsolete (thank god)

    I have wondered why intellisense in Visual Studio marks the ToString method on a Enum type as obsolete. Should we not use it? I personallyl thinks that ToString is much easier then Enum.GetName method. I found this on MSDN, the Empty ToString() is not obsolete and could safely be used it won´t dissapear in the future (should be strange since object class has it and every datatype is derived from object). Why the strange behaviour in Visual Studio then, well it´s the overloaded methods ToString(IFormatProvider) and ToString(String, IFormatProvider) that are obsolte and therefore not recomended to use.

    http://msdn.microsoft.com/en-us/library/system.enum.tostring.aspx

    A very simple object dumper

    static void Write<T>(T item) where T : class, new()
            {
                if (item == null) { item = new T(); }
                var t = item.GetType();
                Console.WriteLine(string.Format("Class name:{0}{2}Namespace:{1}{2}", t.Name, t.Namespace, Environment.NewLine));
                foreach (var propInfo in t.GetProperties())
                {
                    if (propInfo.PropertyType.IsPublic && propInfo.PropertyType.IsPrimitive)
                    {
                        var propValue = t.GetProperty(propInfo.Name).GetValue(item, null);
                        Console.WriteLine(string.Format("Property name:{0} Value:{1}", propInfo.Name, propValue));
                    }
                }
                Console.WriteLine(Environment.NewLine);
            }

    A DataTable helper

    public class DBHelper
        {
            public static T RowToInstance<T>(DataRow row) where T : new()
            {
                T item = new T();
                Type t = item.GetType();
                foreach (PropertyInfo propInfo in t.GetProperties())
                {
                    object temp = t.GetProperty(propInfo.Name).GetValue(item, null);
                    System.Diagnostics.Debug.WriteLine(propInfo.Name);
                    try { propInfo.SetValue(item, row[propInfo.Name], null); }
                    catch { }
                }
                return item;
            }

            public static void LoadRowWithInstanceValues<T>(T item, ref DataRow row) where T : new()
            {           
                Type t = item.GetType();
                foreach (PropertyInfo propInfo in t.GetProperties())
                {
                    object temp = t.GetProperty(propInfo.Name).GetValue(item, null);
                    try { row[propInfo.Name] = propInfo.GetValue(item, null); }
                    catch { }
                }           
            }  
        }

     

    This handy piece of code helps you load a DataRow from a object or vice versa, Load a object with a DataRow. I use the get and setters in try catch block, it just loads propertys that have a matching column (name and datatype) in the DataTable the rest is simply ignored.

    Convert / Parse a string to an enumerated (enum) value

    Today I learned something, the issue I want to solve is using a enumeration property as a kind of wrapper property against a string property (thats mapped as a DataColumn with SqlToLinq). This means a want to cast a string to a enum value and vice versa. This how I do it.

    public SettingDataType DataType
    {
        get
        {
            return (SettingDataType)Enum.Parse(typeof(SettingDataType), PreferedDatatype);
        }
        set
        {
            PreferedDatatype = value.ToString();
        }
    }

    The string property has the name PreferedDatatype

    Singleton Vs Static classes

    What advantages does the singleton have?

    Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects.

    One more time : "we can use singletons as parameters or objects."

    Tree ways to do the samething

    double sumOfAccountSaldo = 0;
    Account[] accounts = new Account[] {new Account() {Saldo = 100}, new Account() {Saldo = 2300}};
    //Traditional syntax
    foreach (Account account in accounts)
        sumOfAccountSaldo += account.Saldo;

    //Query syntax
    var query = from a in accounts
                      select a.Saldo;
    sumOfAccountSaldo = query.Sum();

    //Lambda syntax
    sumOfAccountSaldo = accounts.Sum(a => a.Saldo);

    History of C# and some confusion added by Microsoft

    A little history to clear up the version mess that Microsoft created when releasing .NET Framework 3.0, they should have named it 2.5 but because of this the C# language version and the Framework version is not the same. The list below describes the diffrent releases of .NET Framework and the C# language version (only major releases).
     
    • .NET Framework 1.0 C# Language Version 1 released 2002 with "Visual Studio NET"
    • .NET Framework 1.1 C# Language Version 1 released 2003 with "Visual Studio 2003"
      No bigger changes in this release just som improvements and fixes
    • .NET Framework 2.0 C# Language Version 2 released 2005 with "Visual Studio 2005"
      Generics and anonymous methods inplemented in the C# language this is a major improvement, the "Visual Studio 2005" is also much better, huge of ASP.NET improvments.
    • .NET Framework 3.0 Language C# Version 2.0
      No new version of Visual studio released, this version is a big addon for the 2.0 Framework but the name implies something else (my opinion). The new stuff that´s added is Windows communication foundation, Windows Presenation Foundation, Windows Workflow Foundation and something called Windows Cardspace. 
    • .NET Framework 3.5 Language C# Version 3.0 released 2007 with "Visual Studio 2008"
      Linq is introduced and with it a lot of new cool stuff that I will show later on in this blog, Linq is a little revolution of it´s own. I´v have dreamed about writing querys in SQL style against collections, Arrays, XML, SQL databases or DataSets but use the full potential of the C# language and now it´s reality.