Extension Methods for Easy Data Extraction

Today I am continuing the theme of extension methods by talking about a few I primarily use for aiding in testing scenarios. Have you ever been in the situation where you are stepping through your code and get a set of data back from a SQL call and wish there was an easy way to save it so you could use it as test data? I have a few extension methods that make this situation much easier and all deal with a DataTable.

DataTable Extension Methods

public static void ToCSVFile(this DataTable dt, string fileName, char splitCharacter) {     File.WriteAllText(fileName, dt.ToCSVString(splitCharacter)); } public static string ToCSVString(this DataTable dt, char splitCharacter) {     StringBuilder sb = new StringBuilder();     string[] columnNames = dt.Columns.Cast<DataColumn>().                                         Select(column => column.ColumnName).                                         ToArray();     sb.AppendLine(string.Join(",", columnNames));     foreach (DataRow row in dt.Rows)     {         string[] fields = row.ItemArray.Select(field => field.ToString()).ToArray();         sb.AppendLine(string.Join(",", fields));     }     return sb.ToString(); } public static void FromCSVFile(this DataTable dt, string fileName, char splitCharacter) {     StreamReader sr = new StreamReader(fileName);     dt.FromCSVString(sr.ReadToEnd(), splitCharacter); } public static void FromCSVString(this DataTable dt, string csvData, char splitCharacter) {     StringReader sr = new StringReader(csvData);     string[] columns;     string[] rows;     string myStringRow = sr.ReadLine();     columns = myStringRow.Split(splitCharacter);     foreach (string column in columns)     {         dt.Columns.Add(column);     }     myStringRow = sr.ReadLine();     while (myStringRow != null)     {         rows = myStringRow.Split(splitCharacter);         dt.Rows.Add(rows);         myStringRow = sr.ReadLine();     } }

Here I have four extension methods that make saving and loading a DataTable extremely easy. You can save to and read from a file or string that contains data separated by the delimiter of your choosing.

Usage

There are two ways to use these methods to save data off quickly, of course these methods can also be used for normal coding as well and not limited to the below scenarios.

  • Drop in a line of code right after you get the data back into your DataTable.
myTable.ToCSVFile(@"C:\Source\CSVTest.csv", ',');         // OR string s = myTable.ToCSVString(',');
  • While debugging use the Immediate Window and write the same line after a break point … Continue reading

Guard Clauses Via Extension Methods

Extension methods are pretty cool. They allow you to add functionality to a class or to a type’s behavior. Extension methods usually make life much easier and your code cleaner. I am going to share a few extension methods that make repetitive guard clauses, shorter and easier to read.

Guard Clauses

Guard clauses are those checks at the top of a method to validate all the parameters being passed in. Most of the time, they are used to check if an object is null, a string is empty, or that a collection at least contains something and is not empty. When the parameters do not pass the checks usually some sort of Argument Exception should be thrown. This helps to validate all the parameters before your method begins working on them and provides a better explanation than what could possibly be thrown. Without guard clauses we would have null reference exceptions all over the place which are a pain to debug.

Below I have a method that prints a heading and then a list of names. I want to validate the heading and all the names before I actually print them out. The traditional way is to have code that looks like the following:

public static void PrintNames(string heading, ICollection<string> names) {     if (string.IsNullOrEmpty(heading))         throw new ArgumentNullException("heading");     if (names == null || names.Count == 0)         throw new ArgumentNullException("names");     foreach (string name in names)     {         if (string.IsNullOrEmpty(name))             throw new ArgumentNullException("names has a null or empty item.");     }

This is pretty ugly to have all over the place and this type of checking is extremely repetitive across all your methods. So I have a class of extension methods that make this cleaner and … Continue reading

Using Multithreaded Counters Safely

Have you ever had multiple threads running all trying to read and update a counter variable? Has that variable not always been what you expected? If yes you are probably not using any type of locking to guard that variable from being updated in one thread at the exact same time another thread is trying to update it as well. There are two main ways of updating a counter variable safely and ensuring that a value does not get missed or overwritten in C#. Those two ways are using the lock keyword or using the Interlocked class in .Net.

Keep in mind that incrementing  involves three actions:

  • Read, in which a variable is accessed from memory.
  • Increment, in which the value is increased.
  • Write, where the incremented value is written back to memory.

If multiple threads are trying to do this all at once there can be trouble. If thread A is in the increment step at the same time thread B is at the read step, then when A writes its value B will overwrite it with the exact same value. Two increments will only be seen as one in this scenario.

Lock

The first way is to have some code such as the following:

object myLock = new object(); int counter = 0;          public void ThreadMethod() { lock(myLock)    {    counter++;    } }

Here we create an object, myLock, which is the object we are going to lock on, this is like the bathroom key at a gas station, only … Continue reading

Recruiters, the Good the Bad and the Ugly

My Experience with Recruiters

I recently, for the first time, got a new job through a recruiter, who found me on LinkedIn. I have worked with several different recruiters over the past years with a wide range of results. While I can’t say I worked extensively with all of them, I have gone on several interviews through several different recruiting agencies. I would like to share some of my insights and help you understand how I perceive them to work. Now when I speak about recruiters, I am going to generalize and my opinions are only a reflection of the recruiters I have worked with. There have been some great ones and some horrible ones.

The Ugly

  • They will use you: Some use you to get their client more options when they have no interest in actually placing you and really want to place someone else. This can happen when a company says they need to interview x number of people before making a decision.
  • Not keeping you updated: Some recruiters are really bad at keeping you informed about interview results and positions they have mentioned. A lot of this will stem from my other points. Recruiters can turn unprofessional in a heart beat if they think you are no longer a viable option at the moment. Remember this and do not let it happen again when they call back a few months later begging you to go on another interview.
  • Quality vs quantity: Most recruiters are playing the numbers game. Get as many candidates in … Continue reading

Improve Your Code by Using the New C# 6 Features

The new versions, C# 6 and Visual Studio 2015 come with some pretty cool new features. Mads Torgersen and Dustin Campbell gave a presentation at //build/ 2015 covering a lot of them, which can be viewed at https://channel9.msdn.com/Events/Build/2015/3-711. I want to point out and give a few samples of the ones I found the most interesting and useful.

IDE Features

Many new features have been added in Visual Studio 2015. They are mostly subtle, but they each make life just a little bit easier.

Fade Unused Code

Now, for example, in your list of using statements at the top of each file the unused ones become faded to tell you that your code is not actually using anything from those namespaces. As you can see below the only using statement being referenced is the System namespace. All the rest are not used in this particular coding file and are faded out.

Faded Usings Feature

Quick Actions

As you might have noticed there is also a new little light bulb to the left of the code. This little guy means there are suggestions to make your code better. Clicking on it shows you something like the screenshot below. It is showing you that it can remove unused using statements and is indicated in the red highlighted area. These new suggestions are designed to keep you in the coding context without a jarring dialog that … Continue reading

Tagged

Item Templates, Saving You Time in Visual Studio

Item Templates

As software developers who spend a large majority of our time in front of our IDE, it makes sense to optimize it’s settings to meet our specif needs. Changing just a few small things can have dramatic time savings over the long run if we are constantly having to do them over and over again. I am going to primarily focus on Visual Studio item templates. Every time you hit shift+alt+c to add a new class file or right click on a project and choose “Add->New Item…” this gives you the ability to select a pre-canned/starter file. These files contain the same boring and repetitive skeleton code to get that type of item started. Imagine having to type out all your usings, namespace, and class declarations every time you need to create a new class. Item templates are a great productivity booster!

Ya, And?

So you are probably saying to yourself, so what, every one knows about these and have been using them forever. What if you don’t like the pre-canned ones? What if you love them and wish they were just slightly different? What if you wanted your own custom, perhaps multi-file item templates? I am sure many of you have downloaded other item templates that come with extensions or even as standalone templates from the Visual Studio Gallery. Today I am going to show you how you can modify existing item templates or create your … Continue reading