Category: Dev

Running SQL Files in C# with SMO

I have used SMO, older versions of SMO, to run SQL in C#, but I wanted to do it a new application I’m writing to help with seeding database for tests. Actually, it was pretty easy and you may ask why not just use ADO or sqlcmd. Well the SQL I want to run has TSQL statements that ADO can’t work with. The sqlcmd tool is awesome from the command line, but I wanted a C# solution and SMO allowed me to have less ceremony to get everything up and running.

First you have to get the SMO DLLs necessary to connect with SQL Server and execute the scripts. I am using the files for SQL Server 2012 and I found the DLLs in C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\. You will need 3 of them:

  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Management.Sdk.Sfc.dll
  • Microsoft.SqlServer.Smo.dll

You can copy them to a common folder in your solution and reference them in the project you will use to code up your SQL file runner. If you are into all the Ninja code stuff, you will probably host them on a private NuGet server. Next, all you need is a little code:

using System;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

public class ExcuteSqlScript
{
	public void FromFile(string filePath, string connectionString)
	{
		FileInfo file = new FileInfo(filePath);
		string script = file.OpenText().ReadToEnd();
		this.FromString(script, connectionString);
		file.OpenText().Close();
	}

	public void FromString(string script, string connectionString)
	{
		SqlConnection connection = new SqlConnection(connectionString);
		Server server = new Server(new ServerConnection(connection));
		server.ConnectionContext.ExecuteNonQuery(script);
	}

	//Finally figured out how to display formatted code, yay!
}

I basically have two methods. One loads the SQL from a file path to the SQL file and the other accepts a string with the SQL you want to run. They are both pretty self explanatory. You just need to supply the file path or SQL string and a connection string and it will execute. You should add some error handling and perhaps tweak the file read security and performance for your situation (see refs below). One thing I will be adding is a method to run all SQL files in a directory or iterate over a config file containing the paths to SQL files that need to be ran.

Anyway, this gives a basis to create a more robust solution. If you need more advanced interaction, like transactions, take a closer look at the API for ServerConnection and read the docs, it wasn’t too hard to get through it as the API is simple.

References

SQL Server Management Objects (SMO) Programming Guide – http://technet.microsoft.com/en-us/library/ms162169.aspx

C# .Net: Fastest Way to Read Text Files – http://blogs.davelozinski.com/curiousconsultant/csharp-net-fastest-way-to-read-text-files

Happy Coding!

Caching in on .Net

Just a quick post about a new feature I wasn’t aware of. If you need to cache objects in .Net, before you run off and write a custom cache abstraction to divorce your code from System.Web or to scale out your cache, check out the abstract class System.Runtime.Caching.ObjectCache. It’s based on a mature cache model and is part of the .Net framework. I haven’t researched it, but there are probably implementations for you favorite distribute cache platforms already and if there isn’t one I bet its not too difficult to roll your own with ObjectCache as the base.

Also, if you need a simple in-memory cache without the System.Web headache, try System.Runtime.Caching.MemoryCache. MemoryCache.Default gives you an in-memory cache similar to the cache in ASP.NET, but for use in any .Net project without the System.Web dependency. It also provides ways to override and modify cache behavior.

So, you get a default cache with mature implementation of caching with the ability to add your own customizations, what more could you ask for. How about a thread safe dictionary? I stumbled upon MemoryCache as I was researching new ways to make a thread safe dictionary. Well I guess I will go back to learning about System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>. Wish me luck and if you have any advice, please let me know.

Local WordPress Development on Windows

I decided to set up a local development server to help make my WordPress Theme development easier. Let’s just say it was a pain in the butt. I will record some of what I had trouble with. You can view the mountain of tuts and help sites that can guide you through the details. This is the site I followed, http://sixrevisions.com/tutorials/web-development-tutorials/using-xampp-for-local-wordpress-theme-development/.

I wanted to be able to work on multiple sites so I had to do some configuration. The first thing was to set up virtual directories for the sites I wanted to work with. I am using XAMPP for my server management and in this tool I stopped the Apache server. To setup up multiple sites in Apache I am using the virtual host configuration file. This file is located at [install directory]\apache\conf\extra\httpd-vhosts.conf. This took me a while to get this config right and it may not be optimal for your box, but here it is:

<VirtualHost *:80>
                ServerAdmin postmaster@yourdomain.com
#This is the path to your website files and they can be located anywhere on your drive                 
DocumentRoot " C:/inetpub/wwwroot/yourdomain.com "
                ServerName yourdomain.com
                 ServerAlias www. yourdomain.com
                ErrorLog "logs/ yourdomain.com -error.log"
                CustomLog "logs/ yourdomain.com -access.log" combined
                #I had to add this to get around 403 errors
                <Directory "C:/inetpub/wwwroot/yourdomain.com /">
Options Indexes FollowSymLinks Includes ExecCGI
                                AllowOverride All
                                Require all granted
                </Directory>
</VirtualHost>

As you probably figured out yourdomain.com can be any domain you want: dev.yourdomain.com, google.com, mysite.net…

Next, I had to tell Windows to map the domain name to the local IP. This is done in the host file. You can probably find the host file at C:\Windows\System32\drivers\etc\hosts. The file does not have an extension and you should edit it in a simple text editor like Notepad. To configure the site I just added to Apache, I added:

127.0.0.1 yourdomain.com

After this was done for each site I wanted to configure I could access each one of them and develop locally without having to mess with the live production server.

Gottcha

If you have a problem starting Apache with a message stating that port 80 is unavailable you may need to stop IIS and Web Deployment Agent. In my situation, these were the services that had port 80 tied up for me.

Good Luck!!!

Setup Zurb Foundation for .Net Development

Zurb Foundation

My wife wanted a new website built for a project she is working on. Being the good developer husband I am I decided to implement the site with a responsive design. I could research and build the CSS and javaScript from scratch, but I was sure there was a project already developed to help get me started. Well I landed on a project named Foundation. Here is what they have to say about themselves,

Foundation is the most advanced responsive front-end framework in the world. You can quickly prototype and build sites or apps that work on any kind of device with Foundation, which includes layout constructs (like a fully responsive grid), elements and best practices.

Is it the most advanced? I have no idea, but it seems simple and has a decent community and is in use on some major sites. Why not Bootstrap you ask. Well some respected front end designers said Foundation is cool. I’m a developer, so I respect what the design community has to say about design. This is not to say that designers don’t like Bootstrap, from what I can tell they love it too. I just wanted to learn some of the dark arts and Foundation is closer to the metal and Bootstrap hands everything to you on a platter. I am not qualified to compare them, but you can read about some differences between the two that Felippe Nardi posted on his blog, https://medium.com/frontend-and-beyond/8b3812c7007c. Actually, his post pushed me to Foundation. Even though he said I will have to get my hands dirty to use it I think I will enjoy the control and absence of unnecessary or accidental complexity.

Install

First, in Visual Studio, I create an empty MVC project. I recently upgraded my VS 2012 to Web Tools 2013.1 for Visual Studio 2012 so I am using ASP.NET MVC 5.

Side note, this VS 2012 update includes some nice new features including the concept of round tripping so you can work with your MVC 5 projects in both VS 2012 and VS 2013 without having to change anything (sweet).

OK, I have gotten into the habit of checking NuGet before I attempt to bring new toys into my projects because it makes things so much easier. There is a NuGet to setup Foundation, Foundation5.MVC.Sass so pulling in the files I needed was a breeze. Setup on the other hand was a bear. For some reason I could not get the files to install correctly. Oh well, they downloaded to the solution package folder so I just had to manually copy them.

Manual Setup

First I created a Content folder in the root of my project. Then I opened the folder for the Foundation.Core.Sass package and copied the files from content/sass and dropped them in the Content folder in my project. This framework uses SASS. To compile the SASS files I install the Mindscape Web Workbench. This allows me to compile CSS files by just saving the scss file. So, I open and save the site.scss file to get the site.css created (you will see it directly under the .scss file.

Next, I set up the JavaScript. I open the conent folder in the Foundation.Core.Sass package and copied the Script folder to the root of my project. There are quite a few JavaScript files in there so I have to get them combined and minified to improve performance.

Bundling

To do this, I used NuGet to install Microsoft.AspNet.Web.Optimization that provides JS and CSS bundling features to ASP.NET. Next, I create a BundleConfig.cs in the App_Start folder and add my bundles. Something like this

using System.Web;
using System.Web.Optimization;

namespace ZurbFoundationDotNetBase
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle(“~/Content/css”).Include(“~/Content/site.css”));

bundles.Add(new ScriptBundle(“~/bundles/jquery”).Include(
“~/Scripts/jquery-{version}.js”));

bundles.Add(new ScriptBundle(“~/bundles/modernizr”).Include(
“~/Scripts/modernizr-*”));

bundles.Add(new ScriptBundle(“~/bundles/foundation”).Include(
“~/Scripts/foundation/foundation.js”,
“~/Scripts/foundation/foundation.*”));
}
}
}

Next, I have to bootstrap this file by telling our Global.config to load it. I add this line under the RouteConfig line in the Global.asax.cs file

BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles);

Views and Controllers

Since the MVC 5 update for VS 2012 only allows us to create empty MVC 5 projects, so I have to manually create the controllers and views. The NuGet install for Foundation also missed my MVC files so I have to move them from the package to the project. I open the content folder in the Foundation5.MVC.Sass package and copy the Views folder to the root of our project. The package doesn’t include a _ViewStart.cshtml so I create one and point the layout to the Shared/_Foundation.cshtml file.

@{
 Layout = "~/Views/Shared/_Foundation.cshtml";
}

Next, I rename the Foundation_Index.cshtml to Index.cshtml. Then the last change in the View folder is to update the web.config so that the pages section looks something like this

<pages pageBaseType="System.Web.Mvc.WebViewPage">
 <namespaces>
 <add namespace="System.Web.Helpers" />
 <add namespace="System.Web.Mvc" />
 <add namespace="System.Web.Mvc.Ajax" />
 <add namespace="System.Web.Mvc.Html" />
 <add namespace="System.Web.Optimization" />
 <add namespace="System.Web.Routing" />
 <add namespace="System.Web.WebPages" />
 <add namespace="ZurbFoundationDotNetBase" />
 </namespaces>
 </pages>

Since there are no controllers I have to add one to manage the Home/Index view. In the Controllers folder I create an empty MVC 5 controller named HomeController.cs.

Conclusion

Well, that’s it. I was able to build and run the project and see the response index page. Now I have a base project for responsive web design using a less opinionated framework than Twitter Bootstrap. Although I will still advocate the use of Bootstrap, I believe Foundation will fit my personality and style of development a little better. If any of this interests you, I posted the solution on GitHub.

A Case for Small Distinct Method Conserns

For me, one of the biggest reasons for breaking a method up into distinct tasks or concerns is rooted in the expressiveness of exception messages. Below is an exception message on an actual production website. I am not going to show the code, but I had to answer the question, “Where did the exception below get called in the Page_Load method?” This particular method is a monster that is over 300 lines of code with multiple points where multiple reference objects could be the reason for the null. If the method was broken down into distinct concerns, I would have a fighting chance of finding the source of the error in less than an hour. Hell, with distinct methods I can probably find the null as soon as I expand the method.

Target: Void Page_Load(System.Object, System.EventArgs)
 Type: System.NullReferenceException
 Exception Message:
 Object reference not set to an instance of an object.
Exception StackTrace: at Page_Load(Object sender, EventArgs e)
 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
 at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
 at System.Web.UI.Control.OnLoad(EventArgs e)
 at System.Web.UI.Control.LoadRecursive()
 at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Do your code a favor, do the people that will be maintaining your code a favor, break up your god classes and methods into bite sized chunks of related functionality.

A .Net Developer’s Adventure in Minecraft Modding

Why Mod Minecraft

My kids love Minecraft. Actually, love is too weak a word. They are always asking me to get this mod and that skin and they are just sooo passionate about this game. They watch YouTube videos of mod developers showing off their new mods and it occurred to me that I could probably make a mod. I mean I am a software engineer. It’s just Java. Mind you, I haven’t touched Java in many years, but its object oriented programming, how different is it from C#. So, I told my kids what I wanted to do and that I would need there help and they were very excited. This gives me a chance to discover something they are into and I get to introduce them to programming… win-win. And the adventure begins.

Java Development Environment

The first order of business is to get a Java Development environment up and running. I decided on Eclipse as my IDE as it comes highly recommended and has an awesome community. Below is what I installed.

Java JDK (Java Development Kit) – I downloaded JDK 7 – http://www.oracle.com/technetwork/java/javase/downloads/index.html

Java JRE (Java Runtime Environment) – this actually came with the JDK and I already had it installed.

Eclipse – I downloaded the standard – http://www.eclipse.org/downloads/

While at it I decided to round out my Dev Rig with JUnit for testing and a private GitHub account for source control (I will open it up to the public when I have something that won’t crash and burn). You will also see later in this post that I also added a build server, Gradle, and some JAVA functional programming goodness with Scala. If I’m going to do this I’m going all out.

Minecraft Loader

The Minecraft loader is the program that launches the Minecraft game. You purchase the loader on minecraft.net.

Minecraft Forge

Minecraft Forge is a Minecraft Mod Loader and API. As I understand it right now, it is a wrapper around the official Minecraft game that allows you to load mods (modifications). Forge provides a simplified API for working with the Minecraft source code to make mods. The Forge Mod Loader allows you to load mods made with the Forge API.

I decided on Minecraft Forge as it seemed to have a good community. I wanted to use something called MCP, which from what I understand, Forge actually uses MCP for decompilation of the Minecraft source. Although, I also read that Forge is working on their own decompiler. I didn’t use MCP because I got frustrated as I am a noob and couldn’t figure some things out in the install process. Plus, the kids tell me that Forge has the cool mods.

Anyway you download the latest version of Forge for your version of Minecraft, but I was told by a community member that version 1.6.4 had the most mods at the time I wrote this. Minecraft.exe currently defaults the game version to 1.7.4 and Forge is at 1.7.2 and this gave me the biggest headache trying to get the two to work together until I figured out you can edit your Minecraft profile in the loader and select the version you want to play (this would have fixed my MCP issue too). So let’s get Minecraft 1.6.4 working with Forge 1.6.4. So here is how I got the Forge loader working:

  1. Launch Minecraft
  2. Update  profile to use the 1.6.4 version and save it
  3. Click the Play button (this sets up the 1.6.4 files that are needed for Forge)
  4. Then download the recommended Forge 1.6.4 installer from http://files.minecraftforge.net/
  5. Run the installer
  6. Click windows start key plus R to open the run dialog and type %appdata% and click OK (you can also type this in Windows explorer)
  7. Open .minecraft folder, this holds all of the Minecraft assests
  8. Open the version folder
  9. Open the Forge folder for the Forge version you downloaded and copy the two files
  10. Go back to the version folder and create a new folder and name it whatever you want (remember this name you will need it)
  11. Open the folder and paste the files you copied
  12. Rename both files to the same name you used for the folder
  13. Open the file with extension .json and find the ID field and change it to the name you used for the folder and save
  14. Launch Minecraft
  15. Update profile to use the version that matches the name of the new version folder and save it
  16. Click the Play button
  17. You will be running the new Forge mod loader you just installed and you can add new Forge based mods to it by copying the mod zip files to the mod folder in the .minecraft folder (make sure your mods match the version you are running or it will crash and burn)

Mod Development Setup

Now we will continue with our Development Environment setup to get it ready for mod development.

  1. Download the recommended Forge 1.6.4 src from http://files.minecraftforge.net/ (you can get whatever version of Minecraft you want to develop for)
  2. Extract the zip to a folder any where you want
  3. Then open the folder and run the install.cmd
  4. After the install completes, open Eclipse
  5. Select a workspace by browsing to your Forge install, mcp/eclipse folder and click OK

This will import the Minecraft source code into the IDE and you can get to work modding your Minecraft world.The install took awhile so you can take a break when you start the install.

Other Goodies

Scala

During the Forge install I noticed in the command window that it is working with MCP and it does a lot of decompiling, updating, and recompiling of the Mincecraft source code. I also noticed a message: “scalac” is not found on the PATH. Scala files will not be recompiled. I am not sure if I will need to use Scala, but I always wanted to use Scala so this is a good a time as any to get it set up in my Java Environment. I downloaded the Scala installer from http://www.scala-lang.org/ and I allowed the setup to update my system path variables. I didn’t feel like reruning the Forge installer so hopefully I won’t need the recompiled Scala files for basic learning.

Gradle

In earlier versions of Forge you had to use the Gradle Build Server to setup your source code and Eclipse for development. Even though it isn’t necessary in the version I am using I still setup Gradle because it seems very cool, well Geek Cool. I really need to look into Gradle more for my .Net environment as they have some very interesting concepts for build environments. Anyway, you can install Gradle from http://www.gradle.org/downloads. You can just unzip to some location on your machine. Then copy the path to the Gradle bin folder and add it to your system path environment variable. That’s it, you have a Java build server.

Minecraft Server

I want to host our mods in our own Minecraft server, but I ran into the version issue again. I have 1.7.4 server, but my mods will be 1.6.4. Well with a little URL hacking you can download the 1.6.4 version of the server from the Minecraft download server. This is the same server jar URL as the latest release, I just change the release from 1.7.4 to 1.6.4. https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar

Conlusion

That’s if for now, I will try to post some of my modding experience later. I am in a very strange land, but I think it will be great doing something both constructive and fun with my kids.

Calling Overridden Virtual Method from Base Class in C#

I had a serious brain freeze today. I forgot polymorphism 101. I couldn’t remember if a virtual method defined in a base class and called in the constructor of the base class would call the overriden virtual method in a derived class. Instead of ol’reliable (Google Search), I decided to do a quick test because doing beats searching as it kind of burns in a lesson learned for me. Hopefully, I won’t forget this one for awhile. Anyway, the answer is yes, it will call the override and here is a test if you are having a brain freeze too and want to prove it (this is implemented with MSTest).

namespace BrainFreeze
{
	using System;
	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public class PolymorphismTest
	{
		[TestMethod]
		public void BaseClassVirtualMethodWhenCalledFromBaseContructorShouldCallDerivedVirtualOverride()
		{
			string expected = "ImpCallVirtual";

			Imp imp = new Imp();
			string actual = imp.Result;

			Assert.AreEqual(expected, actual);
		}

		public class Base
		{
			public Base()
			{
				CallVirtual();
			}

			public string Result { get; set; }

			public virtual void CallVirtual()
			{
				this.Result = "BaseCallVirtual";
			}
		}

		public class Imp : Base
		{
			public Imp()
				: base()
			{
			}

			public override void CallVirtual()
			{
				this.Result = "ImpCallVirtual";
			}
		}
	}
}

Typing Git Username and Password is Lame

I set up a local Git server to serve as a central repository. Every time I push changes I have to submit my username and password and it got old real quick. I discovered that it is very easy to get around this, although what I am about to share is a little insecure as I am storing my credentials in plain text, but there are ways to secure this.

First a little background. I am using TortoiseGit as my Git client, I am on Windows 7, and my Git server is not exposed to the public internet.

To allow my credentials to be found I first ran this command:

setx HOME %USERPROFILE%

This sets up a Home environment variable on my system that points to my user profile (see this for more info http://technet.microsoft.com/en-us/library/cc755104.aspx).

Then I create a text file named  _netrc in the root of my user profile folder (C:\Users\{yourusername}\_netrc). In the text file I list the machine name, login, and password for each Git server I want to interact with. I assume this could also work for any server that accepts HTTP credentials.

machine mycoolserver
login mysecretlogin
password mysecretpassword
machine someotherhost.com
login mysecretlogin2
password mysecretpassword2

Machine is the root name of the server you are connecting to. In my case I have a local server without a top level domain (no .com). Then you add your credentials. Like I said this is saved in plain text, so you have to be careful with this and make sure you use credentials that you don’t use on any other accounts (e.g. your bank account).

Thanks to StackOverflow and VonC for help on this:

http://stackoverflow.com/questions/6031214/git-how-to-use-netrc-file-on-windows-to-save-user-and-password

Have You Heard about Event Sourcing?

I cut my teeth in programming in the BASIC language on a computer that had a tape recorder as the persistent memory store (if you don’t know what a tape recorder is Google it). From there I transitioned to VBA and VBScript which wasn’t a stretch because it was all procedural, chaining a bunch of instructions to make the computer do what I want.

During my VB scripting days I was exposed to ASP and relational databases through Access then SQL Server. Cobb’s third normal form was not that much of a stretch for me to grasp. When .Net 1.0 came along as soon as it was released I jumped from ASP to ASP.NET and I took all of my procedural habits along with me to VisualBasic.NET.

Then as I barely got started with .Net I heard all the buzz around C# and object orientation and I just didn’t get it. I tried to force my procedural understanding into an OOP hole. In ASP I would create separate scripts for little pieces of functionality I wanted to reuse. I thought I was getting the same benefit of reuse and object composition that everyone was raving about with C#. How little I knew.

Today I find myself in the same boat trying to understand Event Sourcing. I am trying to fit Event Sourcing into a relational hole, but this time I won’t spend a couple years just doing it absolutely wrong. My boss asked me to talk about Event Sourcing and I took it as an opportunity to learn more about it, even though I will likely never give the talk. I did quite a bit of research and this is more of a post on where you can find some useful info.

Everyone starts with Wikipedia definitions, not sure why, but here is Event Sourcing according to Wikipedia…wait, there isn’t a Wikipedia page for it (as of 8/26/2013). Even Martin Fowler has Event Sourcing as a Work-in-Progress on his EAA page on the subject. So why the hell are we talking about it?

Event sourcing is in production on some of the most data intensive systems on the planet. People way smarter than me advocate it. Also, sometimes it’s nice to be on the cutting edge of a movement as it forces you to innovate.

Event Sourcing is a data persistence technique that focuses on capturing  the state of an application overtime. The states are captured in an event object and the objects are stored in sequential order according to the time that the state changed. Once the state is captured, it can’t be changed or undone, it is immutable. To correct a mistaken state change you have to issue a compensating state change to correct it. So, your persisted state is the gospel, if it was stored you can trust that it is true and wasn’t tampered with (outside of some malicious change to mess with you).

OK, I’m not sure about you, but when I learned this it blew my mind. The idea of persisting the entire history of the state of my application was a red or green pill moment for me. On one hand it seemed terribly inefficient to store the state of every object in my application especially since most of the discussions is about using NoSQL DB’s. How could you possibly query this data easily and what benefit does it get me? Then I learned about the ease of data recovery and production incident research and being able to replay events that happen in production last month on my local box today…what!

Then I had an epiphany. I have source control for my code, took me a little to get comfortable with it and it provided a lot of benefits for me and hopefully for you too. Event Sourcing is something a little like source control for application state. Actually, SVN is an example of Event Sourcing used in my environment at work today. So, this understanding made it a practical solution to me, but I was still unclear on real world usage and what scenarios would benefit most from Event Sourcing.

Being in the financial industry auditing is a big deal and Event Sourcing could provide an instant audit log of every transaction we record. Yet, the whole logging of every event seemed a little overkill. I won’t try to persuade you either way or actually try to explain it to you as I couldn’t do the subject justice, but I decided it was too much for my current projects. Actually, a couple videos by one of the originators of CQRS (another concept that I am researching) has a lot to offer on the subject of event sourcing. Its buried in these references, but its all related and in my opinion all fascinating. Especially, if you are into broadening your coding horizons.

CQRS/DDD by Greg Young – YouTube

http://cqrs.wordpress.com/video/

Lambdas and Generic Delegates

It took me a century to figure out lambdas and what they are all about. So, as I was thinking about what to blog about next I thought I’d share about the moment that lambdas and me clicked.

When I looked at lambdas as shorthand for anonymous delegates and expressions, I came up with a phrase to help me visualize what’s going on. When I read a lambda I say, “with value of variable return expression.” A Predicate delegate would be expressed as a lambda as x => x == 1 would read, “with value of x return x is equal to 1.” When I made => read as return, I stopped trying to force it into some kind of comparison operator (if you have code dyslexia like me, you know what I’m talking about).

Another way to look at it is in terms of what’is happening under the hood. A lambda is like shorthand for anonymous delegates. In longhand, full declaration, as an anonymous delegate, the above lambda would be,

delegate(int x){return x == 1;}

Generic Delegates

Since I mentioned anonymous delegates, I should giving a passing shout out to Generic Delegates.  I use most often:

Predicate must return true or false. Can accept only one parameter.

Func returns the value specified in the parameter. Can accept 4 parameters in .net 3.5 and 16 in 4.0.

Action would not return a value. Can accept 4 parameters in .net 3.5 and 9 in 4.0.

Comparison returns a signed int indicating the result of comparison. If the returned int is

< 0 then x < y
= 0 then x = y
> 0 then x > y

The Comparison delegate can accept two objects of the same type that will be compared (x and y).

Converter returns the result of an object conversion operation. Can accept one input object (to be converted) and an output (return) object (is the converted input object).

EventHandler returns void. Accepts a System.Object (source of event) and TEventArgs (the event’s data).

Anyway, delegates are a powerful feature of C# that I am guilty of not taking advantage of like I should. Hopefully, doing this little post will help in grain them more into my solution designs. If you haven’t been exposed to or currently using Generic Delegates or Lambda Expressions, I challenge you to see how they can help solve some of your problems in a more abstract, efficient and maintainable way. Try them out you may discover a new way to think about and write code.