Standing on the shoulders of giants.
 Saturday, July 26, 2008

When you mark a class as obsolete, you should also mark your class with the EditorBrowsable attribute to prevent it from showing up in IntelliSense.

[Obsolete("Old class no longer supported.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class OldClass
{
    //....
}
26 Jul 2008 11:32 W. Europe Daylight Time  #    Comments [0] - Trackback
Codesnippet

 Tuesday, June 17, 2008

One of my coworkers was struggling with an XML document with a default namespace, none of his attempts returned any nodes. The main reason for this was that his document contained a default namespace which he didn’t include in the query.

As a reminder here a sample how to query an XML document with a default namespace.

Sample XML document:

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns="urn:paulvanbrenk.com/2008/06">
  <book>
    <author>C. Sells</author>
    <title>Programming WPF</title>
  </book>
  <book>
    <author>C. Petzold</author>
    <title>Application = Code + Markup</title>
  </book>
  <book>
    <author>C. Anderson</author>
    <title>Essential WPF</title>
  </book>
</root> 

This doesn’t work:

// load sample document
XmlDocument doc = new XmlDocument();
doc.Load("../../sample.xml");

// try query without namespace
var node1 = doc.SelectNodes("/root/book/title");

Console.WriteLine("node1.Count == 0 {0}", node1.Count == 0);

If you add an XmlNamespaceManager the call to select nodes is able to resolve the nodes:

// load sample document
XmlDocument doc = new XmlDocument();
doc.Load("../../sample.xml");

// add namespace manager
XmlNamespaceManager xnManager = new XmlNamespaceManager(doc.NameTable);
xnManager.AddNamespace(/* prefix */ "x", /* uri */ @"urn:paulvanbrenk.com/2008/06");

var node2 = doc.SelectNodes("/x:root/x:book/x:title", xnManager);

Console.WriteLine("node2.Count != 0 {0}", node2.Count != 0);

And using XLinq makes it a little more readable:

XDocument xDoc = XDocument.Load("../../sample.xml");
XNamespace x = "urn:paulvanbrenk.com/2008/06";

var node3 = from item
                in xDoc.Elements(x + "root").Elements(x + "book")
            select item.Element(x + "title");

Console.WriteLine("node3.Count() != 0 {0}", node3.Count() != 0);

Note how you query the nodes by combining the XNameSpace and the node name.

sample: sample.zip (2.6 KB)

17 Jun 2008 17:59 W. Europe Daylight Time  #    Comments [0] - Trackback
Codesnippet

 Tuesday, June 10, 2008

When hashing a password, you usually use a salt to to make it harder for an attacker to attack the password (see [0]), since the salt is needed to calculate the hash, the same salt is needed to verify a password.

The submitted Hash( Salt + Password ) must be equal to the stored Hash( Salt + Password ).

The common place to store the salt is in a separate field alongside the hash, but this may cause either one to get out-of-sync with the other. A better solution is to concatenate the salt and the hash and store both in one byte array.

static void Main(string[] args)
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

    byte[] salt = new byte[0x10];
    rng.GetBytes(salt);

    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes("the password", salt, /*iterations*/ 5);

    byte[] passHash = deriveBytes.GetBytes(0x100);

    byte[] result = Merge(passHash, salt);
}

private static byte[] Merge(byte[] first, byte[] second)
{
    byte[] result = new byte[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, result, 0, first.Length);

    Buffer.BlockCopy(second, 0, result, first.Length, second.Length);

    return result;
}

Extracting the salt from the hash is relatively simple:

private static byte[] ExtractSalt(byte[] hash, int length)
{
    byte[] salt = new byte[length];

    Buffer.BlockCopy(hash, hash.Length - length, salt, 0, length);

    return salt;
}

You use this salt to generate the hash for the password you want to check and after adding the salt to the end both byte arrays must be equal.

[0] See p.350-352 in Practical Cryptography by Niels Ferguson and Bruce Schneier why salting a password is a good idea.

Sample: HashSample.cs.txt (1.78 KB)

10 Jun 2008 13:39 W. Europe Daylight Time  #    Comments [4] - Trackback
Codesnippet | Security

 Tuesday, April 29, 2008

Sample code to get the first day of the week given a date and a DateTimeFormatInfo.

public static DateTime StartOfWeek(DateTime date, DateTimeFormatInfo dateTimeFormat) {

    Debug.Assert(dateTimeFormat != null, "dateTimeFormat != null");
    if (dateTimeFormat == null) {
        throw new ArgumentNullException("dateTimeFormat");
    }

    DayOfWeek currentDay = date.DayOfWeek;
    DayOfWeek firstDay = dateTimeFormat.FirstDayOfWeek;

    int difference = (int)firstDay - (int)currentDay;

    // we always have to move back, 
    // since we're interested in the first day of the week
    if (difference > 0) { difference -= 7; }

    return date.AddDays(difference);
}

 

The attached sourcefile contains the testcases. StartOfCurrentWeek.cs.txt

29 Apr 2008 09:47 W. Europe Daylight Time  #    Comments [0] - Trackback
Codesnippet

 Monday, April 07, 2008
class Program {
    static void Main(string[] args) {

        string[] strings = { "aa", "bb", "c", "dddd", "eeee", "f" };

        // use a class which implements IComparer
        // This works best when you want to re-use sorting logic
        //  or need to store state between using the comparer.
        Array.Sort(strings, new StringLengthComparer());

        // The following two methods only differ in syntax, both use a delegate.

        // use an anonymous method
        Array.Sort(strings, delegate(string x, string y) { return x.Length - y.Length; });

        // use a lambda expression
        Array.Sort(strings, (x, y) => x.Length - y.Length);

    }

    class StringLengthComparer : IComparer<string> {

        public int Compare(string x, string y) {
            return x.Length - y.Length;
        }
    }
}

Note: The array is sorted on the length of the strings, if you want to sort the strings in the array based on the content use an instance of the StringComparer class.

07 Apr 2008 09:42 W. Europe Daylight Time  #    Comments [0] - Trackback
C# | Codesnippet

 Tuesday, November 20, 2007

Nice, you can use any IEnumerable as the source for you LINQ queries.

 

class Program {
    static void Main(string[] args) {

         var result = from x in GetSequence(12) where (x%2) == 0 select x;

         foreach (var x in result) {
             Console.WriteLine(x);
         }

        Console.ReadLine();

    }

    static IEnumerable<int> GetSequence(int max) {

        for (int i = 0; i < max; i++) yield return i;

    }
}
20 Nov 2007 14:20 W. Europe Standard Time  #    Comments [0] - Trackback
Codesnippet

 Wednesday, August 29, 2007
int[] source = new int[]{1,2,3,4,5,6};

List<int> list = new List<int>( source );

Debug.Assert( ((IList<int>)list).IsReadOnly == false ); // false

Collection<int> collection = new Collection<int>( source );

Debug.Assert(  ((IList<int>)collection).IsReadOnly == true ); // true!!
When the documentation says 'wrapper' they really mean it.

29 Aug 2007 10:33 W. Europe Daylight Time  #    Comments [0] - Trackback
BCL | Codesnippet

 Tuesday, August 28, 2007

After reading post about List Predicates at the very informative BCL Team Blog, I did some research to see how flexible the predicates actually are.

I found out that none of the methods taking a Predicate as a parameter support chained delegates (more info about combining delegates), only the delegate added last to the chain is executed in my experience.

Example:

 

// Prepare collection
List<int> list = new List<int>( new int[]{1,2,3,4,5,6} );
        
// function to determine if the int is less than 5
Predicate<int> LT5 = delegate(int x){ return x < 5; };
        
// function to determine if the int is greater than 2
Predicate<int> GT2 = delegate(int x){ return x > 2; };
        
// combine the predicates:
// return true for 2 < x < 5
Predicate<int> GT2LT5 = null;
GT2LT5 += GT2;
GT2LT5 += LT5;
        
List<int> result = list.FindAll(GT2LT5);

// writes 1,2,3,4
result.ForEach( delegate( int x) { Console.WriteLine( x ); });

A work around would be to use the second delegate on the result collection after calling the FindAll method with the first delegate, but this doesn't scale with more delegates.

 

// first use the first delegate
List<int> intermediate = list.FindAll(LT5);
// now use the second delegate on the intermediate result
List<int> result = intermediate.FindAll(GT2);

// writes 3,4
result.ForEach( delegate( int x) {
    Console.WriteLine( x );
});
 

Another solution is to enumerate through the collection and call each delegate in the invocation list.

 

// Prepare collection
List<int> list = new List<int>( new int[]{1,2,3,4,5,6} );

// function to determine if the int is less than 5
Predicate<int> LT5 = delegate(int x){
return x < 5;
};

// function to determine if the int is greater than 2
Predicate<int> GT2 = delegate(int x){
return x > 2;
};
        
// combine the predicates:
// return true for 2 < x < 5
Predicate<int> GT2LT5 = null;
GT2LT5 += GT2;
GT2LT5 += LT5;

// prepare result
List<int> result = new List<int>();

foreach(int i in list ){
    
    bool valid = true;
    
    // GetInvocationList returns all combined delegates
    foreach( Predicate<int> match in GT2LT5.GetInvocationList() ){
        valid = valid & match(i);            
    }

    if( valid ){
        result.Add(i);
    }
}

// writes 3,4
result.ForEach( delegate( int x) {
    Console.WriteLine( x );
});

Both solutions are less than ideal.

28 Aug 2007 22:26 W. Europe Daylight Time  #    Comments [0] - Trackback
Codesnippet | BCL

 Tuesday, June 26, 2007

The week number depends on 4 variables:

  1. The date you're interested in,
  2. The calendar you use (e.g. Gregorian, Julian, Hebrew etc.)
  3. The first day of the week
  4. The week you count as 1 (e.g. the week containing Jan 1, the first 4 day week etc.)

 

All these parameters are included in the Calendar.GetWeekOfYear method, as shown in the following code snippet:

// instantiate the calendar used in the Netherlands
Calendar calendar = new GregorianCalendar();

// get the current week for the Netherlands
calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);


// and for the USA
calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
26 Jun 2007 15:31 W. Europe Daylight Time  #    Comments [0] - Trackback
Codesnippet

Subscribe
About
newtelligence dasBlog 2.1.7309.765
Admin
All Content © Copyright 2008, Paul van Brenk
DasBlog theme 'Business' created by Christoph De Baene (delarou)