rulururu

post Code nested inside a namespace?

April 11th, 2008

Filed under: .NET — Kai @ 7:38 am

Recently I wondered if code should be always nested in a namespace or not.

The question actually shouldn’t be which is “better” rather which is better for a particular case.

using bar;
namespace Foo {
  // etc
}

or

namespace Foo {
  using foo;
  // etc
}

I don’t know how to answer the question “which is better?” because I do not know the intended purpose of the code. I therefore tried to think of ways that these could be different, and answer the question “how do these differ?”

The answer is that if there is only one namespace in the file, it hardly matters. If there are two or more namespaces in the file, then put the directives you want shared amongst them at the top of the file, and the ones you do not want shared inside each the namespace. I further noted that having multiple top-level namespaces in the same file is a little weird, so maybe don’t even go there and make it a moot point.

My first statement was not right. There is a way that these could be different that I forgot about. The first version is equivalent to

using global::bar;
namespace Foo {
  // etc
}

The second version is equivalent to

namespace Foo {
  using global::bar;
  // etc
}

unless Foo contains a namespace called bar. In that case, it is equivalent to

namespace Foo {
  using global::Foo.Blah;
  // etc
}

So there are at least two ways that things can get broken here. First, moving a not-fully-qualified directive from outside to inside (or vice versa) may cause a semantic change in the program. And second, if there is a not-fully-qualified directive inside the namespace which refers to a top-level namespace then adding a child namespace that collides with that name can introduce a semantic change in the program.

Therefore my advice is:

  • have only one top-level namespace per file
  • if you choose to put using directives inside your namespaces then fully qualify them with the global alias qualifier

If you take this advice then it really does not matter whether the directives go inside the namespace or outside; either way you will not accidentally break yourself by introducing a name collision.

post Monitor class: Thread Safety

April 10th, 2008

Filed under: .NET — Kai @ 7:57 am

The Monitor class controls access to objects by granting a single thread a lock for an object. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object no other thread can acquire the lock for the object. Additionally, the Monitor class can be used to ensure that no other thread can access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

I ever wondered what the difference between using a lock statement, versus using a Montior.Enter / Monitor.Exit clause is? Actually there’s a few, but the main one is that a lock statement is inherently thread safe, where-as a Montior is not. So -

try {
Monitor.Enter(_lock);
DoThreadSafeCode();
} finally {
Monitor.Exit(_lock);
}

is essentially the same as -

lock (_lock) {
DoThreadSafeCode();
}

post Linq Querys and Joins

March 31st, 2008

Filed under: .NET, Database — Kai @ 8:20 pm

I have been playing with LINQ just a few times but I can say I am impressed with it. It does nearly everything out of box. In This post I will illustrate how to use Joins in LINQ queries.

Many a times we want a query where by we retrieve the data from one table and some the related data from the other table. Let says we have a category table and a posts table. Now when I retrieve all the records of the posts I also want to have the related category name (which is there in the category table). So I need to make a join between three tables to get the records.

Here is the LINQ Query to do the job:

var t = from p in Blog.Posts
            join cp in Blog.CategoryPosts on p.PostId equals cp.PostId
            join c in Blog.Categories on cp.CategoryID equals c.CategoryID
            select new
            {
                PostId = p.PostId,
                CategoryName = c.CategoryName,
                PostName = p.PostName,
                PostSubName = p.PostSubName           
            };

So basically to make a join between two tables we use the join keyword. After specifying the join keyword we need to provide the column name on which the join will be made. And then we need to provide the condition on which the join will be made. Hence the on keyword with the condition.

It’s so simple. If you know a little bit of SQL then this syntax shouldn’t be a problem. LINQ makes working with data in its various guises easier.

By intergating it into the language, we have rich integrated support for working with data.

However, there are times where the syntax is slighly different from what you would typically expect with TSQL. Once case where this occurs is when trying to join two data sources that are related by more than one field (also know as a composite key). This differs from standard joins where one table has a primary key and the other table has a foreign key id.

post Long Pathes

March 25th, 2008

Filed under: .NET, Windows — Kai @ 2:10 am

Just a short snipped I’d like to not forget about.

The maximal possible pathlength on Windows is, as you probably know, 255 chars. For that reason you can use the following:

Convert short path to long:

String s = Short2Long(@"D:\MYTEMP~1\RESOUR~1\sql.txt");
 
public static String Short2Long(String sShortPath) {
    StringBuilder sLongPath = new StringBuilder(255);
    GetLongPathName(sShortPath, sLongPath, sLongPath.Capacity);
    return sLongPath.ToString();
}

Vice versa:

String s = Long2Short(@"D:\My Temp\ResourseProvider\sql.txt");
 
public static String Long2Short(String sLongPath) {
    StringBuilder sShortPath = new StringBuilder(255);
    GetShortPathName(sLongPath, sShortPath, sShortPath.Capacity);
    return sShortPath.ToString();
}

Hope it might help you somewhere along the way ;)

post Sorting Strings containing Numbers

March 24th, 2008

Filed under: .NET, General Programming — Kai @ 6:20 pm

It’s often necessary to sort lists. The Sort method of ArrayList class shows that it can’t be difficult. Also some other classes can be sorted unless they are type IComparable.
The sort method of ArrayList class has several overloads, some can be given to a Comparer, which implements the IComparer interface.

The interface has just one method called Compare which returns equal, greater or smaller depending on the two values it compares.

If you’d make your own comparer you’d simply do that like this:

public class MySpecialComparer : object, System.Collections.IComparer
{
 
    /// <summary>
    /// Default constructor - initializes all fields to default values
    /// </summary>
    public MySpecialComparer()
    {
    }
}

There’s also a difference in ascending and descending sort order. Mention the following code which compares String descending:

public class DescendingComparer : IComparer
{
  public int Compare(object objA, object objB)
  {
    return String.Compare(objB.ToString(), objA.ToString());
  }
}

The trick is just to compare B to A and not the way round.

To sort a simplest one dimensional array in alphabetical order, we’ll leverage the static “Sort” method in the Array class to sort the array. The Array.Sort method will sort the array in place, meaning we don’t have to create another array to contain the resulting array. Here is how:

String[] myAnimals = {"Zebra","Elephant","Snake"};
Array.Sort(myAnimals);

As expected this will result in the array getting sorted in the ascending order i.e. iterating the elements of this array will cause the output in the following manner:

Elephant, Snake, Zebra

Computer string sorting algorithms generally don’t order strings containing numbers in the same way that a human would do. Consider:

rfc1.txt, rfc2086.txt, rfc822.txt

It would be more friendly if the program listed the files as

rfc1.txt, rfc822.txt, rfc2086.txt

Filenames sort properly if people insert leading zeros, but they don’t always do that.
It’s kinda tricky when strings that contain numbers are sorted ’cause they’ve to be sorted numerically.

Imagine an array of values like this:

string[] Items = { "z4", "z2", "z15", "z1" };

The idea is to write a Comparer (implements IComparer) which extracts the numeric part e.g. by RegEx: [0-9]*
Then sort as already familiar with a Collections.Sort method that uses the comparator.

Generally you’d “invent” an algorithm that breaks strings into chunks, where a chunk contains either all alphabetic characters, or all numeric characters. These chunks are then compared against each other. If both chunks contain numbers, a numerical comparison is used. If either chunk contains characters, the ASCII comparison is used.

Ian Griffith offered a code sample that helps to handle string sorting with numbers:

/// <summary>
/// Compares two sequences.
/// </summary>
/// <typeparam name="T">Type of item in the sequences.</typeparam>
/// <remarks>
/// Compares elements from the two input sequences in turn. If we
/// run out of list before finding unequal elements, then the shorter
/// list is deemed to be the lesser list.
/// </remarks>
public class EnumerableComparer<T> : IComparer<IEnumerable<T>>
{
    /// <summary>
    /// Create a sequence comparer using the default comparer for T.
    /// </summary>
    public EnumerableComparer()
    {
        comp = Comparer<T>.Default;
    }
 
    /// <summary>
    /// Create a sequence comparer, using the specified item comparer
    /// for T.
    /// </summary>
    /// <param name="comparer">Comparer for comparing each pair of
    /// items from the sequences.</param>
    public EnumerableComparer(IComparer<T> comparer)
    {
        comp = comparer;
    }
 
    /// <summary>
    /// Object used for comparing each element.
    /// </summary>
    private IComparer<T> comp;
 
 
    /// <summary>
    /// Compare two sequences of T.
    /// </summary>
    /// <param name="x">First sequence.</param>
    /// <param name="y">Second sequence.</param>
    public int Compare(IEnumerable<T> x, IEnumerable<T> y)
    {
        using (IEnumerator<T> leftIt = x.GetEnumerator())
        using (IEnumerator<T> rightIt = y.GetEnumerator())
        {
            while (true)
            {
                bool left = leftIt.MoveNext();
                bool right = rightIt.MoveNext();
 
                if (!(left || right)) return 0;
 
                if (!left) return -1;
                if (!right) return 1;
 
                int itemResult = comp.Compare(leftIt.Current, rightIt.Current);
                if (itemResult != 0) return itemResult;
            }
        }
    }
}

When using it a regular expression for the numbers is needed.
Using C# 3.0 it can be used that way:

Func<string, object> convert = str =>
{   try { return int.Parse(str); }
    catch { return str; } };
 
var sorted = testItems.OrderBy(
    str => Regex.Split(str.Replace(" ", ""), "([0-9]+)").Select(convert),
    new EnumerableComparer<object>());

Again the lambda expression can help a lot. sorted is an untyped listed that can be iterated with foreach.

When sorting / comparing strings that contain numbers you always should consider to sort them the way a human would do.

post Short type names

March 24th, 2008

Filed under: .NET — Kai @ 2:10 pm

One nice tidbit is how to create new short type names without having to specify the full name of every non-primitive type, especially inside of generic type names.

Normally, using “using” to create a new type name, even in the presence of the appropriate namespace import, one has to fully qualify every type name that is not a keyword.

using System.Collections.Generic;
using T = System.Collections.Generic.List<string>

However, if the “using” is inside a namespace, then it will utilize any imports located in an outer namespace.

using System.Collections.Generic;
 
namespace MyCompany
{
    using T = List<string>;
}
ruldrurd
« Previous PageNext Page »
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)