Standing on the shoulders of giants. RSS 2.0
Page 1 of 2 in the DevelopmentCodesnippet category Next Page
# Thursday, January 22, 2009

This is not new, but something that helped me today.

When debugging, you can see the types in scope in the auto’s window:

Default debugger

This shows only the relevant information after expanding the view. One way of improving the experience is by implementing the ToString() method.

ToString method

While this helps a lot, this means you can’t use the ToString method for something else. Luckily in VS 2008 the DebuggerDisplayAttribute was introduced, this allows you to achieve the same effect and more.

DebuggerDisplayAttribute

And the code:

[System.Diagnostics.DebuggerDisplay("Date:{Date}, Value:{Value}", Name="{Name}")]
class Item
{
    public string Name { get; set; }

    public DateTime Date { get; set; }

    public int Value { get; set; }
}
Thursday, January 22, 2009 8:31:28 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0] - Trackback
C# | Codesnippet
# Tuesday, September 16, 2008

A nice method I discovered today:

System.Globalization.TextInfo.ToTitleCase(string)

This capitalizes the first letter of each word in the string, e.g. "hello world" becomes "Hello World".

Tuesday, September 16, 2008 7:30:19 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [1] - Trackback
Codesnippet
# Monday, September 15, 2008
public class Foo : IComparable<Foo>
{
    public Foo() { }

    public int Value { get; set; }

    public int CompareTo(Foo other)
    {
        if (other == null) { return 1; }

        return this.Value.CompareTo(other.Value);
    }
}

The trick is the line, which checks for the null comparison. Since null is always less than this, the method must return a value greater than zero (0).

Also see the remarks in the documentation:

Greater than zero: This object is greater than other.
...
By definition, any object compares greater than null (Nothing in Visual Basic), and two null references compare equal to each other.

Monday, September 15, 2008 8:55:47 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [0] - Trackback
Codesnippet
# Saturday, September 06, 2008

A simple example to show how to use the SyndicationFeed class to load a feed and how to handle the items.

using System;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        string feedUrl = "http://feeds.delicious.com/v2/rss/tags/paul.van.brenk";

        SyndicationFeed feed;

        using (XmlTextReader xReader = new XmlTextReader(feedUrl))
        {
            feed = SyndicationFeed.Load(xReader);
        }

        // max is more appropriate
        //var sum = feed.Items.Aggregate(0m, (x, y) => x += Decimal.Parse(y.Summary.Text));

        var max = feed.Items.Max(x => Decimal.Parse(x.Summary.Text));

        // select item title and relative weight for items with a relative weight > 0.1 
        var normItems = from i in feed.Items
                        where (Decimal.Parse(i.Summary.Text) / max) > 0.1m
                        select new { Title = i.Title.Text, Weight = Decimal.Parse(i.Summary.Text) / max };

        foreach (var item in normItems)
        {
            // 15 = highest possible value for consolecoler (Magic Number)
            Console.ForegroundColor = (ConsoleColor)(15 * item.Weight);
            Console.Write("{0} ", item.Title);
        }

        Console.ReadLine();
    }
}

Download code: ConsoleTagCloud.txt (1.22 KB)

Saturday, September 06, 2008 4:15:16 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [0] - Trackback
Codesnippet | Services
# 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
{
    //....
}
Saturday, July 26, 2008 2:32:53 AM (Pacific Daylight Time, UTC-07:00)  #    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)

Tuesday, June 17, 2008 8:59:37 AM (Pacific Daylight Time, UTC-07:00)  #    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)

Tuesday, June 10, 2008 4:39:06 AM (Pacific Daylight Time, UTC-07:00)  #    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

Tuesday, April 29, 2008 12:47:31 AM (Pacific Daylight Time, UTC-07:00)  #    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.

Monday, April 07, 2008 12:42:29 AM (Pacific Daylight Time, UTC-07:00)  #    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;

    }
}
Tuesday, November 20, 2007 5:20:10 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0] - Trackback
Codesnippet
Ads
About
© Copyright 2012
Paul van Brenk
Sign In
newtelligence dasBlog 2.3.2011.0
All Content © 2012, Paul van Brenk
DasBlog theme 'Business' created by Christoph De Baene (delarou)