A Simple Way to Check for a Table in Access

As I worked on another project today, I came across a simple dilemma. The project reads in a small Microsoft Access database (also known as a .mdb file) into memory. It then queries said database with a simple ‘SELECT foo FROM bar…‘ statement and pulls the results into the program. However, if you load an Access database that does not follow the expected schema, the program throws a nasty error and causes some logic interruption. I needed a simple way to check for a few table names before proceeding, so I whipped up a simple C# method.

It basically checks to see if the file path to the Access database is available. If it is available it checks the schema inside the database for the given table name. If found, the boolean variable will be set to true. If not, the method will return false.

See if you can follow along with comments in the code:

public bool DoesTableExist(string TableName)
{
    // Variables availbe to the method, but not defined here are:
    // SomeFilePath (string)

    // Variable to return that defines if the table exists or not.
    bool TableExists = false;

	// If the file path is empty, no way a table could exist!
    if (SomeFilePath.Equals(String.Empty))
    {
        return TableExists;
    }

    // Using the Access Db connection...
    using (OleDbConnection DbConnection
           = new OleDbConnection(GetConnString(SomeFilePath)))
    {
        // Try the database logic
        try
        {
            // Make the Database Connection
            DbConnection.Open();

            // Get the datatable information
            DataTable dt = DbConnection.GetSchema("Tables");

            // Loop throw the rows in the datatable
            foreach (DataRow row in dt.Rows)
            {
                // If we have a table name match, make our return true
                // and break the looop
                if (row.ItemArray[2].ToString() == TableName)
                {
                    TableExists = true;
                    break;
                }
            }
        }
        catch (Exception e)
        {
            // Handle your ERRORS!
        }
        finally
        {
            // Always remeber to close your database connections!
            DbConnection.Close();
        }
    }

    // Return the results!
    return TableExists;
}

Feel free to integrate this into your project, this may come in handy with one of your future projects!

Read More
Add Descriptions to Enumerations

Enumerations in C# allow you to group common constants together inside a piece of code. They are often used for determining a system state, flag state, or other constant conditions throughout the program. Usually enums are not formatted for “pretty” displaying to the end user. However you can use a little C# magic to make them behave better with descriptions!

In order to add descriptions to the desired enum, you’ll need to declare using System.ComponentModel; at the top of your source file. This will help with simplifying the definitions later on. So first let’s lay out an enum:

enum MyColors
{
    White,
    Gray,
    Black
}

Now we just add the description parameter before each portion of the enum:

enum MyColors
{
    [Description("Eggshell White")]
    White,

    [Description("Granite Gray")]
    Gray,

    [Description("Midnight Black")]
    Black
}

Now we will need to construct an extension method for accessing these new descriptions.

public static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        var type = value.GetType();
        var field = type.GetField(value.ToString());
        var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length == 0 ? value.ToString() : ((DescriptionAttribute)attributes[0]).Description;
    }
}

Basically, this method has the following workflow:

  • Grab the enum type
  • Get the actual field value
  • Grab our custom attribute “Description”
  • Finally, check to make sure we got a value.
  • If we didn’t, just return the string of the enum value
  • If we did, return the Description attribute.

All you have to do now is loop through the enum to prove the code:

for (MyColors i = MyColors.White; i <= MyColors.Black; i++)
    Console.WriteLine(i.GetDescription());

/*
Eggshell White
Granite Gray
Midnight Black
*/

This could be very useful if you want to pull something for a XAML binding, and not try to format an enum at runtime! You also will only have to keep the description in one place, and that is with the actual enum value itself.

Read More
Access Common Methods Using Extensions

There will be times when you are using a third-party library or some other “black box” software in your project. During those times you may need to add functionality to objects or classes, but that addition does not necessarily call for employing inheritance or some other subclass. In fact, you might not have access to the library’s source code if it is proprietary. There is a wonderful feature of C# though that allows you to add-on commonly used methods to any type of object, and that feature is called Extension Methods

Extension methods are a simple way of adding common functionality to a given object in C#. It is usually faster than trying to build a new subclass from the original class and it makes your code a lot more readable. MSDN has a wonderful explanation of extension methods:

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Source: MSDN

To create an extension method, you must use this syntax:

public static return-type MethodName(this ObjectType TheObject, ParamType1 param1, ..., ParamTypeN paramN)
{
    /* Your actual method code here */
}

Notice the all important this ObjectType TheObject inside the parameter list? Well this needs to match what object is actually calling it. So if you are making an extension method for a string, your first parameter will read this string YourDesiredStringName. In short: ObjectType is the name of the type that you are creating the extension method and will be stored inside TheObject property for use in the method. Any extra parameters such as param1 and so on are optional and can be used inside your method also.

So take a look at the simple sample I have created. Notice I am calling in the namespace that contains the extensions in my main namespace, and thanks to that my int object can call all the methods naturally:

using System;

namespace MainProgram
{
    // Call in UrdaExtensions namespace so we can access the extension methods
    using UrdaExtensions;

    class MainProgram
    {
        public static void Main()
        {
            int MyNum = 21;
            Console.WriteLine("MyNum = {0}\n", MyNum);
            Console.WriteLine("MyNum.Cube()     : " + MyNum.Cube());
            Console.WriteLine("MyNum.FlipInt()  : " + MyNum.FlipInt());
            Console.WriteLine("MyNum.ShiftTwo() : " + MyNum.ShiftTwo());
        }
    }
}

namespace UrdaExtensions
{
    public static class UrdaExtensionClass
    {
        #region Extension Methods

        public static int Cube(this int value)
        {
            return value * value * value;
        }

        public static int FlipInt(this int value)
        {
            char[] CharArray = value.ToString().ToCharArray();
            Array.Reverse(CharArray);
            return int.Parse(new string(CharArray));
        }

        public static int ShiftTwo(this int value)
        {
            return value + 2;
        }

        #endregion
    }
}

/*
Program prints this to screen at runtime:

MyNum = 21

MyNum.Cube()     : 9261
MyNum.FlipInt()  : 12
MyNum.ShiftTwo() : 23
Press any key to continue . . .
*/

Thanks to extension methods, I do not have to make a call that looks something like MyUtilityObject.Cube(MyNum). Instead I can make a better method call straight from the int object. This makes life easier for all involved since the code will be much simpler to read and it allows for better code re-usability.

Read More
How To: Create a Visual Studio 2010 Code Snippet

As you work through various projects in Visual Studio 2010 you will find yourself reusing a lot of code. In fact, you may find yourself reusing a lot of the same static code, or code that follows a basic pattern. Visual Studio 2010 lets you cut out a lot of this wasted time by employing code snippets. Code snippets can generate basic code patterns or layouts on the fly inside your project. Today I will walk you through creating a basic code snippet for generating a C# class with specific section stubs.

You will need to start with a generic XML file. You’ll want to keep the XML declaration line inside the file once you create it and change the file extension from .xml to .snippet. For reference I store my stubs inside “C:\Users\Urda\Documents\Visual Studio 2010\Code Snippets\Visual C#\Custom”

Now we can go ahead our XML stub! We will first fill out the required schema information:

<?xml version="1.0" encoding="utf-8"?>

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">

    <!-- Come with me, and you'll be... -->

  </CodeSnippet>
</CodeSnippets>

Now we are ready to fill out our header information. The header is used to define things such as the title of the snippet, the author, the shortcut for IntelliSense , and a description. The header will also define the snippet type (you can read all about the options of snippet type here) that the snippet will act as. So we will fill out our header now:

<?xml version="1.0" encoding="utf-8"?>

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Build Class With #regions</Title>
      <Author>Urda</Author>
      <Shortcut>BuildClassWithRegions</Shortcut>
      <Description>Creates a Class With Common #region Sections</Description>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>

    <!-- ...in a world of pure imagination... -->

  </CodeSnippet>
</CodeSnippets>

Our next element, which will also be a child of the CodeSnippet element, will define the properties of the actual snippet to be inserted. Now for this example I wanted to be able to replace a single chunk of the snippet when I call the snippet from Visual Studio. This will require the addition of a Declarations section that will control this behavior.

The declaration section can either contain an Object type or a Literal type. We will be covering the Literal type in this example. The literal has an ID, ToolTip, and a Default value. The ID is used by the snippet for where the actual replacement occurs. The ToolTip tag will be used by IntelliSense to give the end-user a hint as to the purpose of the code section that is being worked on. Finally, a default value is declared to be displayed before the user makes the change.

We will go ahead and fill the section out now:

<?xml version="1.0" encoding="utf-8"?>

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Build Class With #regions</Title>
      <Author>Urda</Author>
      <Shortcut>BuildClassWithRegions</Shortcut>
      <Description>Creates a Class With Common #region Sections</Description>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>

    <Snippet>
      <Declarations>
        <Literal>
          <ID>ClassName</ID>
          <ToolTip>Replace with the desired class name.</ToolTip>
          <Default>ClassName</Default>
        </Literal>
      </Declarations>

      <!-- ...take a look and you'll see into your imagination... -->

    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Now we can fill out the final section that will contain the actual code generated by the snippet. We will go ahead and declare that this code is for C#, and create the required tags before we start entering in our code:

<?xml version="1.0" encoding="utf-8"?>

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Build Class With #regions</Title>
      <Author>Urda</Author>
      <Shortcut>BuildClassWithRegions</Shortcut>
      <Description>Creates a Class With Common #region Sections</Description>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>

    <Snippet>
      <Declarations>
        <Literal>
          <ID>ClassName</ID>
          <ToolTip>Replace with the desired class name.</ToolTip>
          <Default>ClassName</Default>
        </Literal>
      </Declarations>

      <Code Language="CSharp">
        <![CDATA[
        /*
        ...we'll begin with a spin traveling in the world of my creation...
        */
        ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

We will being to enter the code our snippet will generate inside this last section. All the code to be generated by the snippet needs to be placed between the <![CDATA[ and

]]> tags. If you fail to do so, your snippet will not work. We also want to call back to the literal declaration we made inside the code. To do this we simply surround the name of the literal with the $ symbol. You should be able to deduce what the snippet will generate from the complete snippet file below:

<?xml version="1.0" encoding="utf-8"?>

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Build Class With #regions</Title>
      <Author>Urda</Author>
      <Shortcut>BuildClassWithRegions</Shortcut>
      <Description>Creates a Class With Common #region Sections</Description>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>

    <Snippet>
      <Declarations>
        <Literal>
          <ID>ClassName</ID>
          <ToolTip>Replace with the desired class name.</ToolTip>
          <Default>ClassName</Default>
        </Literal>
      </Declarations>

      <Code Language="CSharp">
        <![CDATA[class $ClassName$
        {
            #region Public Properties

            #endregion

            #region Private Properties

            #endregion

            #region Constructors

            #endregion

            #region Public Methods

            #endregion

            #region Private Methods

            #endregion
        }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

<!-- ...what we'll see will defy explanation. -->

So after all this work we still need to tell Visual Studio 2010 where to find this snippet file. To do this we will need to open the Code Snippets Manager from Tools -> Code Snippets Manager… or with the default keyboard shortcut CTRL+K, CTRL+B inside Visual Studio. Once that is open you may need to reference your custom folder (Mine was at “C:\Users\Urda\Documents\Visual Studio 2010\Code Snippets\Visual C#\Custom” for reference) using the “Add..” button. You can then click do the following:

  • Click “Import…”
  • Browse to the location of your snippet
  • Select the folder you would like Visual Studio to store said snippet (I used my “Custom” folder)
  • ..and your done!

So now just jump back to your C# project and you should be able to just type ‘b’ or ‘B’ for IntelliSense to prompt you with the following:

Code snippet prompt

Like any other snippet (such as prop) a double tab after that point will fill out the code and jump your cursor to the class name for you to rename:

Code snippet used

For further reading MSDN has plenty of information on creating advanced snippets. You can find said information by visiting this link. So what are you waiting for? Go make your coding life easier!

Read More
A XAML DataGrid Quirk

Everyone knows how amazing XAML is to create flexible and beautiful GUI’s for various applications. XAML provides a wonderful interface to building a simple grid of data (much like an Excel spreadsheet) with the DataGrid namespace. I was working on a DataGrid object in one of my projects today, and chose to re-work the XAML into a better form for easier reading and code re-use. I however stumbled into a strange characteristic of the Datagrid, and I wanted to share with you that issue and the fix I came up with.

So here is the XAML I came up with to display a simple grid in my application:

<DataGrid x:Name="SomeDataGrid" ItemsSource="{Binding}"
                DataContext="{Binding}" AutoGenerateColumns="False"
                CanUserAddRows="False" CanUserDeleteRows="False"
                HeadersVisibility="Column"
                AlternatingRowBackground="LightGray" >
    <data:DataGrid.Columns>
		<data:DataGridCheckBoxColumn
            Header="Include?"
            Width="55"
            CanUserResize="False"
            Binding="{Binding Path=IsIncluded, Mode=TwoWay}" />
        <data:DataGridTextColumn
            Header="ID"
            MinWidth="22"
            Width="SizeToCells"
            Binding="{Binding Path=SystemNumber, Mode=OneWay}" />
        <data:DataGridTextColumn
            Header="Question Text"
            MinWidth="85"
            Width="SizeToCells"
            Binding="{Binding Path=Text, Mode=OneWay}" />
    </data:DataGrid.Columns>
</data:DataGrid>

The issue that arose was centered around the checkbox column. The new checkbox column required the user to first make a row active (by clicking on it) to then have to click a second time to enable or disable the desired checkbox. Obviously this is not the desired action, since a user expects to be able to just check a box without having to select the row first.

So how do we correct the issue. Well instead of just using a plain DataGridCheckBoxColumn we will declare a template column instead. We can then define within this template the actions and styling of this column. Below is my updated XAML section for the first column:

<!-- XAML Omitted -->

<data:DataGridTemplateColumn
	Header="Include?"
	Width="55"
	CanUserResize="False">
	<data:DataGridTemplateColumn.CellTemplate>
		<DataTemplate>
			<Grid>
				<CheckBox
					IsChecked="{Binding Path=IsIncluded, Mode=TwoWay}"
					ClickMode="Press"
					HorizontalAlignment="Center"
					VerticalAlignment="Center" />
			</Grid>
		</DataTemplate>
	</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>

<!-- XAML Omitted -->

The ClickMode=”Press” will allow the box to be checked when the mouse is hovered over it and a click event is caught. This allows for our desired action, while still keeping clean and organized XAML!

Hopefully this may come in handy if you are pulling your hair out over DataGrid columns. I know I’ll end up referring back to this note sometime in the future.

Read More
Using #region Effectively

The #region preprocessor directive can make your C# code very organized. It is a shame that so many coders do not learn to use #region early and often. Sure #region allows Visual Studio 2010 to collapse your code block down into one-line, but better yet it can be used to sort code by common sections. This provides a framework for other source files throughout your project to mimic. Today I wanted to cover how I like to sort my code in my projects.

Many of your C# classes, interfaces, and other source files will have common logical groupings. For example many classes will contain one or more of the following:

  • Public Variables
  • Private Variables
  • Constructors
  • Public Methods
  • Private Methods

So using that as our #region framework we can develop a skeleton C# class file that follows that concept:

using System;

namespace SomeConsoleApp
{
    class ConsoleClass
    {
        #region Public Variables

        /* ...Here Be Dragons... */

        #endregion

        #region Private Variables

        /* ...Here Be Secret Dragons... */

        #endregion

        #region Constructors

        /* ...Here Be Dragon Eggs... */

        #endregion

        #region Public Methods

        public void BreatheFire()
        {
            /* ...Magic Goes Here... */
        }

        // ...other public methods...

        #endregion

        #region Private Methods

        private void RebuildFireBreath()
        {
            /* ...Some Secret Magic Goes Here... */
        }

        // ...other private methods...

        #endregion
    }
}

So if you were to plug-in the C# example from above, you could collapse your sections down so your editor looks like this:

Collapsed Code Sections

If you are good about keeping your code clean a system like this can be invaluable to you. A system like my example will let you quickly move from file to file knowing where all the important chunks of code are, and allow you to “ignore” other sections since they will be collapsed already.

This is just one way to structure your project. You can of course re-order your blocks into however you see fit, and if you do you should leave a comment and tell me how you prefer to organize your source files.

So go ahead and give it a try in your next project!

Read More
Visual Studio 2010 Document Previews

If you have used Visual Studio 2008 or the Visual Studio 2010 Betas you should remember a distinct feature. When you moved through documents inside the IDE with CTRL + TAB you would get a nice little preview of the documents you were flipping through. If you have used the latest version of Visual Studio 2010, you may have noticed that this feature has been pulled. Well you can restore it with a simple registry change!

If you use CTRL + TAB in Visual Studio 2010 today, you’ll get a dialog that looks something like the following:

VS2010 - No Preview

So in order to restore the thumbnail previews we will run this simple command from an elevated command prompt in Windows:

reg ADD HKCU\Software\Microsoft\VisualStudio\10.0\General /v ShowThumbnailsOnNavigation /t REG_DWORD /d 1

Now all you have to do is start up or restart Visual Studio 2010, get your documents open again, and then try to cycle through them. You should get a much more useful display like so:

VS2010 - Preview

Isn’t that fantastic?

Read More
Simple C# Threading and Thread Safety

A few days ago I compared and contrasted Asynchronous and Parallel Programming. Today I would like to walk you through a very simple threading example in C#, and why the concept of “thread safety” is important to know before you start writing parallel applications.

Since we already know what exactly parallel programming is, and how it is different from asynchronous calls we can go ahead and drill down to some more aspects of parallel programming. So here is an application that will start a new thread from the main, and both threads will call the same method:

using System;
using System.Threading;

class Threading101
{
    static bool fire;

    static void Main()
    {
        new Thread(FireMethod).Start();  // Call FireMethod() on new thread
        FireMethod();                    // Call FireMethod() on main thread
    }

    static void FireMethod()
    {
        if (!fire)
        {
            Console.WriteLine("Method Fired");
            fire = true;
        }
    }
}

Now at first glance you might say that we will only see “Method Fired” shown on screen, however when we run the program we will see this output:

Program Output

Well we have obviously called the method on both threads, but we got an undesired output! This example shows the clear issues you will encounter when working with threads in C#. This method is defined as thread unsafe and does not work correctly (in its current state) when used in threading applications.

So what can we do about this? Well we need some method of preventing a thread from entering a method when another thread is entering a critical part of the method. So we just have to update our code to account for some type of locking functionality and then re-work our application:

using System;
using System.Threading;

class Threading101
{
    static bool fire;

    static readonly object locker = new object();

    static void Main()
    {
        new Thread(FireMethod).Start();  // Call FireMethod() on new thread
        FireMethod();                    // Call FireMethod() on main thread
    }

    static void FireMethod()
    {
        // Use Monitor.TryEnter to attempt an exclusive lock.
        // Returns true if lock is gained
        if (Monitor.TryEnter(locker))
        {
            lock (locker)
            {
                if (!fire)
                {
                    Console.WriteLine("Method Fired");
                    fire = true;
                }
            }
        }
        else
        {
            Console.WriteLine("Method is in use by another thread!");
        }
    }
}

Running the code above now produces a better threading result:

Program Output

Now that looks better! We made sure that only a single thread could enter a critical section of the code, and prevent other threads from stepping in. We first use Monitor.TryEnter(locker) to check for a lock, and if there is no lock we step in and run our code. If there is already a lock, we have added the logic to print that result to screen.

Pretty simple huh? So this little app spawns an extra thread, and both threads fire the same method. However, the variable is only changed once, and the message from the method is only printed once. The first snippet is a perfect example of a method that is not thread safe, and the second one is a great way to protect that same method.

Read More
C# Preprocessor Directives

If you have ever worked with an application that bounces from your workstation, to QA, then to production the odds are high you have dealt with C# preprocessor directives. While C# does not have a preprocessing engine, these directives are treated as such. They have been named as such to be consistent with C and C++ for familiarity. Directives can be used to build classes based on the environment they will be deployed in, to grouping chunks of your source code together for collapsing inside the Visual Studio code editor. This article will go over each C# preprocessor directive.

C# has the following directives, all of which will be covered in this article:

  • #if
  • #else
  • #elif
  • #endif
  • #define
  • #undef
  • #warning
  • #error
  • #line
  • #region
  • #endregion

Let’s start with #define and #undef. These directives are used to define and undefine symbols that evaluate to true (if using #define) when used in other logical directives. As you could imagine, #undef will undefine a given symbol (such that it yields false).

// Set Debug Mode
#define DEBUG_MODE
// Kill SQL Logger
#undef SQL_LOG

With those two directives down, we can move on to #if, #else, #elif, and #endif directives. These directives let you step into or over chunks of code depending on the condition that is checked. As you can imagine, they behave like if, else if, and else statements in C#. The #endif directive must be used to finish off any statement or statements starting with the #if directive. You may use the ==, !=, &&, || operators to check various conditions. You can also group symbols and operators by using parentheses.

#define DEBUG_MODE
#undef SQL_LOG
using System;

public class SomeClass
{
    public static void Main()
    {
        #if (DEBUG_MODE && !SQL_LOG)
            Console.WriteLine("DEBUG_MODE is defined!");
        #elif (!DEBUG && SQL_LOG)
            Console.WriteLine("SQL_LOG is defined!");
        #elif (DEBUG && SQL_LOG)
            Console.WriteLine("DEBUG_MODE and SQL_LOG are defined!");
        #else
            Console.WriteLine("No symbols defined");
        #endif
    }
}

/*
Prints to screen:
DEBUG_MODE is defined!
*/

In just these two examples I have already covered 6 of the 11 possible C# preprocessor directives. The next few will help you add messages to your compiler output.

Now let’s cover the #warning and #error directives. Both of these directives will throw Warnings or Errors respectively when you compile your application in Visual Studio. For example, you may want to throw a warning that you left debug mode on so you don’t accidentally deploy your application to production while it is running in a debug state:

#define DEBUG_MODE
using System;

public class SomeClass
{
    public static void Main()
    {
        #if DEBUG_MODE
        #warning DEBUG_MODE is defined
        #endif
    }
}

…and of course #error will cause an error to be displayed in the compiler output:

#define DEBUG_MODE
using System;

public class SomeClass
{
    public static void Main()
    {
        #if DEBUG_MODE
        #error DEBUG_MODE is defined
        #endif
    }
}

The #line directive is more strange than the other preprocessor directives. Specifically, #line allows you to modify the compiler’s line number and optionally change the file name that is used for warning and error outputs. The syntax is as follows:

#line [ number ["file_name"] | hidden | default ]

Hidden will remove successive lines from the debugger until another #line directive is hit. Usually the #line directive is used in automated build process or code creators. But for an example if I use this chunk of code:

using system

class SomeClass
{
    static void Main()
    {
        #line 208
        int i;
        #line default
        char c;
    }
}

Will produce this error output inside Visual Studio:

C:\Path\To\File.cs(208,13): warning CS0168: The variable 'i' is declared but never used
C:\Path\To\File.cs(10,13): warning CS0168: The variable 'c' is declared but never used

Finally, we have the #region and #endregion. Every #region block must end with a #endregion block. When you define a block it allows you to expand and collapse code inside Visual Studio for easier reading and reference. There are some important points to note though: A #region block cannot overlap an #if block and vice versa . You can nest an #if block inside a #region block or a #region block inside an #if block though. So for example:

using System;

class MainBox
{
    static void Main(string[] args)
    {
        #region Secrets
        /*
         * ...here be dragons!
         */
        #endregion
    }
}

I can expand and collapse the section inside Visual Studio as pictured:

Collapsing region

…and that is all the possible C# preprocessor directives you can use! I love the #region one, since it allows you to lump your code together for easier reading.

Read More
Asynchronous Versus Parallel Programming

The last decade has brought about the age of multi-core processors to many homes and businesses around the globe. In fact, you would be more hard-pressed to find a computer with no multi-core (either physical, or virtual) support for sale on the market today. Software Engineers and Architects have already started designing and developing applications that use multiple cores. This leads to extended use of Asynchronous and Parallel programming patterns and techniques.

Before we begin it would help to review a key difference in Asynchronous and Parallel programming. The two perform similar tasks and functions in most modern languages, but they have conceptual differences.

Asynchronous calls are used to prevent “blocking” within an application. For instance, if you need to run a query against a database or pull a file from a local disk you will want to use an asynchronous call. This call will spin-off in an already existing thread (such as an I/O thread) and do its task when it can. Asynchronous calls can occur on the same machine or be used on another machine somewhere else (such as a computer in the LAN or a webserver exposing an API on the internet). This is used to keep the user interface from appearing to “freeze” or act unresponsively.

In parallel programming you still break up work or tasks, but the key differences is that you spin up new threads for each chunk of work and each thread can reach a common variable pool. In most cases parallel programming only takes place on the local machine, and is never sent out to other computers. Again, this is because each call to a parallel task spins up a brand new thread for execution. Parallel programming can also be used to keep an interface snappy and not feel “frozen” when running a challenging task on the CPU.

So you might ask yourself “Well these sound like the same deal!” In reality they are not by any means. With an asynchronous call you have no control over threads or a thread pool (which is a collection of threads) and are dependent on the system to handle the requests. With parallel programming you have much more control over the tasks chunks, and can even create a number of threads to be handled by a given number of cores in a processor. However each call to spin up or tear down a thread is very system intensive so extra care must be taken into account when creating your programming.

Imagine this use case: I have an array of 1,000,000 int values. I have requested that you, the programmer, make an addition to each of these people objects to contain an internal id equal to the object’s array index. I also tell you about how the latest buzzword on the street is “multi-core processing” so I want to see patterns on that used for this assignment. Assuming you have already defined the original “person” class and wrote a “NewPerson” class with the added dimension, which pattern (asynchronous or parallel) would be preferred to break the work up and why?

The correct answer of course would be the parallel pattern. Since each object is not dependent on another object from somewhere else (from something like a remote API) we can split the million objects into smaller chunks and perform the object copy and addition of the new parameter. We can then break send those chunks to different processors to conduct the execution of our code. Our code can even be designed to account for n processors in any computer, and evenly spread the work across CPU cores.

Now here at Mercer I am working on a .NET web product. Our tech leads and developers have created a “Commons” library that contains factories and objects that are useful to all the sub-projects that exist in this very large .NET product. Exposed services or factories are hosted via IIS and are accessible by other projects in the product by simply referring to the “Commons” namespace. Basically the “Commons” library prevents all developers from re-inventing the wheel if they need things such as a log writer, methods to extract objects from a MSSQL database, or even methods for interoperability between projects.

When it comes to the “Commons” library we are using Asynchronous calls between the server and client. We do this since a user could potentially hit one server in the cluster, then make another request that is picked up by a separate server in the cluster. It would not be helpful if we spun up a processing thread on Server A, only for the client to hit Server B (which then would have to spin up its own thread) if the cluster load balancer redirects them to Server B. Since our services are built to be asynchronous calls, all the client end has to do is pass in some session information to the server and the server can pull up the requested objects or data. If we were to use parallel processing in regards to the .NET pattern, we would be creating a ton of overhead with the constant setup and tear-down of threads within the webserver. There is also a chance the client might be redirected to another server completely by the forward facing load balancer. For our “Commons” it makes much, much more sense to just let the operating system handle sending off and receiving asynchronous calls.

So this should have served as a basic compare and contrast of asynchronous and parallel programming. If you remember anything, remember this: While both patterns are used to prevent blocking within, say a User Interface, keep in mind that an asynchronous calls will use threads already in use by the system and parallel programming requires the developer to break the work up, spinup, and teardown threads needed.

Read More