Harri's profilePainKiller´s C# CornerBlogListsNetworkMore Tools Help

PainKiller´s C# Corner

I Like To Inspire Just As Much I Like To Be Inspired

Harri Klingsten

Occupation
Location
This person's network is empty (or maybe they're keeping it private).

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

Problem with gridview or any other asp control events

In my current project I had problem with the execution orders on a ASP.NET page, I use a databound gridview, that databinds in PageLoad. But when I then hit the select row and that event fires I dont want to databind on PageLoad of course, but how to I do that? The Execution order is first PageLoad then SelectedRowChange on the gridview. This is my solution:
 

if (Request.Form["__EVENTTARGET"] != GridView1.UniqueID)

{
    GridView1.DataSource = GetTransactionData(

"", false);
    GridView1.DataBind();
}

Note that I can do a check of what triggered the page reoload, and then skip the databinding if the gridview populated this, because i know that the row index change event on the gridview will take care of the databinding. Time for lunch now :-)

Grouping partial classes in Solution Explorer

I found a great tool today that I could recomend, I was looking for a tool to easily group partial classes without manually edit the project file. Why do I want this feature then? Well I like organizing things and since the partial classes feature is such a good thing doing just that I like it.

But the bad thing is that the nice group layout of partial classes that Visual Studio it self uses when it separates for example a Winform in three files like form1.cs, form1.Designer.cs and form1.resx is something you dont can do in a simple way.

But thanks to Jarek Kardas this problem is solved with his nice tool VsCommands, take a look at it and download it from here

http://mokosh.co.uk/page/VsCommands.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

Truncate log on SQL 2008

Some times old tricks just dies, thats what happend with "BACKUP LOG WITH TRUNCATE_ONLY"
When you run that on a SQL 2008 server you will read: "truncate_only' is not a recognized BACKUP option"
It´s gone deprecated because of misuse (what?), anywhay this the new style of doing the same thing wich is to clear the logfile.
 
USE dbname;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE dbname
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (2, 1);  -- here 2 is the file ID for trasaction log file,you can also mention the log file name (dbname_log)
GO
-- Reset the database recovery model.
ALTER DATABASE dbname
SET RECOVERY FULL;
GO

MS SQL 2008 Express a good start (pay when you really need it)

Express is the name of Microsofts “free” tools, to met the competition with the open source alternatives. I realy like SQL 2008 Express it is basically the full (and very expensive) version with som limitiations, wich are:

  • CPUs: Only 1 CPU. If a system has more than 1 SQL Express 2008 will still run but limit itself to 1 CPU.
  • RAM: 1 GB. More RAM can exist, but again SQL Express 2008 will only make use of a maximum 1 GB.
  • Database Size: 4 GB. This limitation provides for the storage of a considerable amount of data while protecting the domain of the higher-end SQL Server versions.
  • Many solution could live with this limitations it´s saves a lot of license money, and when the day comes there is no problem to change to MS SQL Server 2008, just install it and restore a backup file (it´s no differance between the database files).

    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

    More Lambda syntax, replacing grouping method or anonymous methods

    It´s been a long while since I posted something, I have som cool Lambda syntax that I coded today that I would like to share with my readers.

    The problem

    I have a helper metod that takes a method delegate as parameter, the delegate looks like this.

    delegate void MethodDelegate(TParam param)

    I´m using this with some other stuff to create thread call´s in my winform applications. It could be calls like CreateUser(User user), the method always takes one parameter. Anyway my Crud classes have some method that uses two parameters like UpdateUser(User user, string key).

    Now how do I use this easily with my Delegate, I could write a method that looks like this (I have left out the generic stuff to don´t make this to complex):

    private void UpdateUser(User user)
    {
        CrudService.UpdateUser(user, user.UserId);
    }

    And use that method with the delagete call (PassMethod), or you could use a anonymous method like this:

    PassMethod(delegate { crudService.UpdateUser(user, user.UserId.ToString()); });

    For some reason I prefer a nice Lambda syntax instead like this:

    PassMethod(user, param => crudService.UpdateUser(user, user.UserId.ToString()));

    MS SQL 2008 Store Blobs with FILESTREAM

    Today I digged in myself in the new MS SQL function Filestream that was shipped with MS Sql 2008. The problem this function is trying to solve is to store images and other binary files in the database preserving speed and security. To get the maximum performance many developers stores files in the NTFS filesystem and just the path in the database, drawback is that these files dont get backed up along with an ordinary databasebackup. You can restore the paths to the files but the files are gone if the disked has crashed. You could of course backup the files also, but then you have two backup plans to maintain and worrying about. The other solution was to store the files as BLOB objects in the database, MS SQL is´nt realy built for these kind of storage it has a performance hit, here you can se som comparsion of the methods http://msdn.microsoft.com/en-us/library/cc949109.aspx

    Now with Filestream you could use a combinatin of SQL and NTFS storage, thats what it´s all about a filestorage handled by the MS SQL Server engine, when you do a Database backup the files also are backed up I dont go in to details just google around and read about it. When you are ready for try this out I have made a very simple Sample project feel free to download it, I have ripped most of the code from Guy Bersteins site (links below)

    My sample project is here: http://cid-e0d0e097982463fd.skydrive.live.com/self.aspx/CodeSamples/MsSqlFileStreamSample.zip

    Some configuratin is needed for your MS SQL 2008 databse (Filestream must be enabled), read more about this here: http://blogs.microsoft.co.il/blogs/bursteg/archive/2008/05/09/sql-server-2008-filestream-part-1.aspx

    Words of Wisdom

    When there is potential for input of crap in the database, there will be crap in the database.

    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);
            }

    Select instead of foreach

    A quick sample demonstrating the power of Lambda. A realy stupid one I want to append all Account name in to a StringBuilder object and show the result in a MessageBox.

    The foreach way

    var accounts = crudClient.Read<Account>();
    var message = new StringBuilder();
    foreach (var account in accounts)
        message.Append(account.Name);
    MessageBox.Show(string.Format("Property values:{0}", message));

     

    The Lambda way

    var accounts = crudClient.Read<Account>();
    var message = new StringBuilder();
    accounts.Select(a => message.Append(a.Name)).ToList();
    MessageBox.Show(string.Format("Property values:{0}", message));

    It is realy a stupid example, but it should give you a hint of the Lambda/Linq power. Observe that I have to call the ToList() method otherwise the projection on accounts never fires.

    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