Tag: code

Null Coalescing Operator

In C# 2.0, Microsoft introduced the null coalescing operator (??). The ?? operator is a shorthand notation for returning a default value if a reference or Nullable<T> type is null.

The examples below show how the null coalescing operator achieves the same result as traditional conditional statements but with less lines of code. Both sets of examples use property getter methods with assumed fields.

Reference Examples with Conditional Statements

public MyObject MyObjectProperty
{
    get
    {
        if (this.myObject == null)
        {
            return new MyObject();
        }

        return this.myObject;
    }
}

Reference Examples with Null Coalescing Operator

public MyObject MyObjectProperty
{
    get
    {
        return this.myObject ?? new MyObject();
    }
}

Nullable<T> Example with Conditional Statements

public int Number
{
    get
    {
        if (this.nullableNumber.HasValue)
        {
            return this.nullableNumber.Value;
        }

        return 0;
    }
}

Nullable<T> Example with Null Coalescing Operator

public int Number
{
    get { return this.nullableNumber ?? 0; }
}

The main argument against the ?? operator is that developers don’t understand it so it makes the code less readable and maintainable. This is a poor argument in my opinion. As developers, we should never stop trying to improve both ourselves and our teams. This is something that can be taught over lunch one day.

More reading: ?? Operator (C# Reference) – MSDN

Advertisements

Get a String from a MemoryStream

The MSDN article for MemoryStream has this example of outputting a string to the console.

private static void Main(string[] args)
{
    int count;
    byte[] byteArray;
    char[] charArray;
    UnicodeEncoding uniEncoding = new UnicodeEncoding();

    // Create the data to write to the stream.
    byte[] firstString = uniEncoding.GetBytes("Invalid file path characters are: ");
    byte[] secondString = uniEncoding.GetBytes(Path.GetInvalidPathChars());

    using(MemoryStream memStream = new MemoryStream(100))
    {
        // Write the first string to the stream.
        memStream.Write(firstString, 0 , firstString.Length);

        // Write the second string to the stream, byte by byte.
        count = 0;
        while(count < secondString.Length)
        {
            memStream.WriteByte(secondString[count++]);
        }

        // Write the stream properties to the console.
        Console.WriteLine(
            "Capacity = {0}, Length = {1}, Position = {2}\n",
            memStream.Capacity.ToString(),
            memStream.Length.ToString(),
            memStream.Position.ToString());

        // Set the position to the beginning of the stream.
        memStream.Seek(0, SeekOrigin.Begin);

        // Read the first 20 bytes from the stream.
        byteArray = new byte[memStream.Length];
        count = memStream.Read(byteArray, 0, 20);

        // Read the remaining bytes, byte by byte.
        while(count < memStream.Length)
        {
            byteArray[count++] = Convert.ToByte(memStream.ReadByte());
        }

        // Decode the byte array into a char array
        // and write it to the console.
        charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)];
        uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);
        Console.WriteLine(charArray);
    }
}
I have a problem with code examples that try and do too much. Here is a much less complex example of writing a string to the console from a MemoryStream.
private static void Main(string[] args)
{
    using (var memoryStream = new MemoryStream(100))
    using (var streamWriter = new StreamWriter(memoryStream))
    using (var streamReader = new StreamReader(memoryStream))
    {
        var invalidPath = new string(Path.GetInvalidPathChars());
        streamWriter.WriteLine("Invalid file path characters are:");
        streamWriter.WriteLine(invalidPath);

        streamWriter.Flush();
        memoryStream.Position = 0;

        var stringToOutput = streamReader.ReadToEnd();
        Console.WriteLine(stringToOutput);
    }
}

Calculate Elapsed Time in .NET

I came across this while preparing an upcoming blog entry and felt the need to share. I was looking for a way to calculate the time of an operation. I searched over and over again only to find the following pattern:

DateTime startTime = DateTime.Now;
// do operation
DateTime endTime = DateTime.Now;
TimeSpan runTime = endTime - startTime;

Unfortunately, this pattern isn’t very accurate and rarely outputs anything other than zero on simple operations. I needed to output elapsed time for even these simple operation so I kept searching until finally I came across the System.Diagnostics.Stopwatch class. The code is more readable and (after a bit of testing) is capable of tracking the elapsed time of simple operations.

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// do operations
stopwatch.Stop();
TimeSpan runTime = stopwatch.Elapsed;
long runTimeMilliseconds = stopwatch.ElapsedMilliseconds;
long runTimeTicks = stopwatch.ElapsedTicks;

Hopefully, putting this out there will help people find this method much quicker than I did. And as my mother used to tell me: just because everyone else does it, it doesn’t make it right.

SP 2010 Site Collection PowerShell Script

The following script is what we’ve been using to create site collections with their own database in SharePoint 2010.

Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

## Configure the script
$databaseName = "SP_Content_Database_Name"
$webApplicationUrl = "http://localhost"
$siteCollectionUrl = "http://localhost/sites/siteName"
$siteCollectionName = "Site Collection Name"
$siteCollectionOwner1 = "DOMAIN\user1"
$siteCollectionOwner2 = "DOMAIN\user2"
$siteCollectionTemplate = "STS#1"

## Create the database
New-SPContentDatabase -Name $databaseName -WebApplication $webApplicationUrl

## Create the site collection
New-SPSite -URL $siteCollectionUrl -OwnerAlias $siteCollectionOwner1 -SecondaryOwnerAlias $siteCollectionOwner2 -ContentDatabase $databaseName -Name $siteCollectionName -Template $siteCollectionTemplate

Download the above code at: https://gist.github.com/4488619

If you need a list of site templates available on the machine you can run:

Get-SPWebTemplate | Sort-Object "Title"

jQuery XHTML Strict Target=”_blank” Solution

As many of you know, XHTML Strict does not allow the target attribute within <a> tags. I have been using a JavaScript solution which I found online a few years back. The code was a bit verbose so I decided to update it using jQuery.

$(document).ready(function () {
    $('a[rel="external"]').each(function(i) {
        $(this).attr('target', '_blank');
    });
});

With the above code in place, simply put rel=”external” on any anchor tags that need to open in a new window.