Extension Methods In C#

C# extension methods allow developers to extend the capability of  controls  by providing a method which associates itself with the particular control; and provides functionality not built into that control. We can view extension methods as a kind of decorator or dependency injection depending on your inclination. Even though extension methods have been around a while now I rarely see use of it in the code produced by my colleagues even though it would greatly improve readability.

Lets see how we can go about creating an extension method for a popular UI control in Visual Studio the textbox.

First:
Create a new Visual Studio Win. forms project called demoExtension, to that project add a class and name it extensions.cls.

Second:
Rename Form1 -> frmDemo and drag a Textbox and Button control unto the form, rename them txtInput and btnSubmit respectively. Set the btnSubmit.Text property to “Submit”.

Third:
Replace the code in extensions.cls with the code below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace demoExtension
{
    static class extensions
    {
        static public bool IsEmailValid(this TextBox emailTextBox)
        {
            if (emailTextBox.Text.Length > 0)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(emailTextBox.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
                {
                    return true;
                }
                return false;
            }
            return true;
        }
    }
}

Fourth:
In the click event for btnSubmit enter code.

private void btnSubmit_Click(object sender, EventArgs e)
{
     if (txtInput.IsEmailValid())
          txtInput.BackColor = Color.Green;
     else
          txtInput.BackColor = Color.Red;
}

Next:
Run the application and enter a malformed email address then hit the submit button.

Retype the email using correct standard then hit submit.

Have fun coding ūüôā

Advertisements

Returning Multiple Result Sets from a SQL Stored Procedure for use in a C# Application.

With much frustration and trial and error I have recently discovered that I can not return all results of a multi-result set stored procedure using the generated fill method of a dataset. It appears that typed datasets are only allowed to return a single result set as per the dataset architecture. However, thankfully there is a workaround, if the dataset is a non-typed dataset then it is possible to access the result sets by means of the DataSet.Tables collection.

If you already have a stored procedure which returns multiple result sets then here is the code for accessing each result set that the dataset contains.

Code:

using System.Data;
using System.Data.SqlClient;

public DataSet GetDataFor(int param1, int param2)
{
      SqlConnection sqlConnection;
      dataSet = new DataSet();
      SqlDataAdapter sqlDataAdapter;

      sqlConnection = new SqlConnection(Properties.Settings.Default.AEORIONSMSConnectionString);
      sqlConnection.Open();

      sqlDataAdapter = new SqlDataAdapter([Replace with your sp name], sqlConnection);
      sqlDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;

      sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@param1", param1);
      sqlDataAdapter.SelectCommand.Parameters.AddWithValue("@param2", param2);

      sqlDataAdapter.Fill(dataSet);
      sqlDataAdapter.Dispose();

      return dataSet;
}

Using the returned DataSet:

void GetColumns()
{
     var dataSet = GetDataFor(1, 3);

     string[] columnNames1 = dataSet.Tables[0].Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
     string[] columnNames2 = dataSet.Tables[1].Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
     string[] columnNames3 = dataSet.Tables[2].Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
}

C++ AMP In Visual Studio 11 For GPGPU Programming

So Visual Studio 2011 Beta is finally here, along with the snazzy new look and other “must have” niceties there is the new ¬†AMP (Accelerated Massive Parallelism) extension to C++. I must admit this was the feature that caught my eye, having been interested in parallelism for a while with lambda expressions in c# and Haskell with its built in parallelism. However, I wanted a means of coding those solutions my self; my first thought was to go with CUDA¬†this got me in trouble with my laptop which started to behave strangely once I had installed the SDK.

Then came OpenCL, my challenge with OpenCL is it use of a subset of the C language which I was not prepared to learn at the time. OpenCL is pretty low level and requires the programmer to do more work in terms of dynamically switching between available CPU and¬†Capable¬†GPU. However, one of the biggest advantages with OpenCL is that its an open source framework and its features are very mature and numerous. Microsoft does have a¬†promissory licence¬†¬†on C++ AMP but we will see what happens in the future in terms of its openness and Microsoft’s willingness to conform to industry standards.

Microsoft TPL (Task Parallel Library) was also another consideration. This library makes it relatively easy for .NET developers to add parallelism to their applications, however I have not seen any mention of running tasks on the GPU. There are lots of new features coming in .NET 4.5 so TPL GPGPU may be one of them.

Enter C++ AMP, this new extension allows developers in C++ the capability to run parallel tasks on their CPU or Enabled GPU; however, its only currently on the windows platform. In my case the use of C++ AMP was a no-brainer since I am already familiar with VC++.

Example code:

#include <amp.h>
#include <iostream>
using namespace concurrency;

void CampMethod() {
    int aCPP[] = {1, 2, 3, 4, 5};
    int bCPP[] = {6, 7, 8, 9, 10};
    int sumCPP[5] = {0, 0, 0, 0, 0};

    // Create C++ AMP objects.
    array_view a(5, aCPP);
    array_view b(5, bCPP);
    array_view sum(5, sumCPP);

    parallel_for_each(
        // Define the compute domain, which is the set of threads that are created.
        sum.extent,
        // Define the code to run on each thread on the accelerator.
        [=](index<1> idx) restrict(amp)
        {
            sum[idx] = a[idx] + b[idx];
        }
    );

    // Print the results. The expected output is "7, 9, 11, 13, 15".
    for (int i = 0; i < 5; i++) {
        std::cout << sum[i] << "\n";
    }
}

It should be noted that this code can be contained in a DLL and called from any .NET language using PInvoke or any other equivalent method. Also, a performance overhead will be incurred because of the set-up and transfer of data to the GPU, there is also a penalty for setting up and calling the DLL with PInvoke. Overall the C++ AMP extension looks like a definite contender in the sphere of parallelism.

References:
Task Parallel Library
C++ AMP
Using C++ AMP from a DLL

Using Haskell With Leksah IDE

Hi there, if you have been interested in Haskell and are not sure of what the IMHO best IDE for Haskell development is then you have come to the right place. For some time now I have doodled around with Haskell because of Microsoft F# which I want to learn at some later stage. F# is a functional language with capacity for the imperative and OOP style of programming, which most people are accustomed to. However, I decided to learn Haskell for the simple reason that it only does functional style programming, and would give a better foundation to functional programming than its F# counterpart.

So, to get started I went to Haskell.org and downloaded the latest version of Haskell for Windows. Once installed it provided a command line interface for working with Haskell in an interpretive way. It is possible to use this interface along with your favourite text editor to create programs; however, a dedicated IDE would be better. At this point my search for the best Haskell IDE begun. My first choice was Eclipse with a Haskell Add-In, the most vexing problem with this set-up is that auto-complete templates have to be created for Haskell and there is no support for intelli-sense with Haskell.

My search went on to Lecksah and concluded with Leksah, this IDE provided debugging, testing, and source control options for my Haskell programs. It also had auto-complete and intelli-sense out of the box; being a noob to Haskell means I will constantly need help with keywords and library references which are provided by the Leksah interface.

That said lets move on to the good stuff :-).This will be the beginning of a series of articles documenting my progression into this weird and wonderful world of functional programming, stay tuned for more.

Setting Up Visual Studio 10 for MASM32 Programming

If you are like me and want the comfort and support that Microsoft’s Visual Studio 10 provides, then you will defiantly want that support in your MASM programming tasks. Visual studio makes this quite easy, with a couple of project property changes you will be on your way to MASM programming bliss.

Steps

  1. Create new Visual C++ Empty Project
  2. Right click on the newly created project and select Build Customizations; select masm option, press ok then save the project.
  3. Go to project properties and select linker->system then change subsystem to Windows (/SUBSYSTEM:CONSOLE)
  4. Download and install masm32 libraries then add them to your linker settings.
  5. Go to linker->Advanced and change Entry Point to main [this is what the linker will look for when mapping the entry point for your app.]
  6. Go to Linker->Input  and add masm32.lib to Additional Dependencies.
  7. Go to Microsoft Macro Assembler->General and add the masm32 libraries.
  8. Download and paste usertype.dat into C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE
  9. Go to Visual Studio Options->Text Editor->File Extensions: Type asm in the extension box then select Microsoft Visual  C++ from the list.
  10. Right click on project and select Add->New Item: Select Text File and save with *.asm
  11. Create, run and enjoy your code ūüôā

In a future post I will show how to turn this project into a Visual Studio project template.