.NET 4 – Tuple instead of out parameters

.NET 4 introduced a tuple class which can be very useful.

Wikipedia defines a Tuple as “… a tuple is an ordered list of elements.”

MSDN defines a Tuple as “A tuple is a data structure that has a specific number and sequence of elements.”

You may be asking right now, “What am I supposed to do with that?”  I hope to give you a good idea by the time you are done reading this post.  I will provide a few examples of why, when and how to use them.  Let’s get to it.

One of my pet peeves is output parameters also known as ByRef in VB.  I know there many reasons to use them but the default seems to be where you need to return more than one value from a function.  Consider the following:

string outParameter1, outParameter2;
var v = OutParameterFunction("Test", out outParameter1, out outParameter2);
Console.WriteLine("return value: {0} :: out parameters: {1}, {2}", v, outParameter1, outParameter2);

public static int OutParameterFunction(string inParameter, out string outParameter1, out string outParameter2)
{
     var retValue = 0;
     outParameter1 = null;

     if (!string.IsNullOrEmpty(inParameter))
     {
         outParameter1 = inParameter;
         outParameter2 = "Kewl";
         retValue = 1;
     }
     else outParameter2 = "NOT Kewl";

     return retValue;
}

Simply put there are two values being returned with one of them being the integer value and the other being the output string parameter.

It would be easy to circumvent issue by creating a class to hold the multiple values and return the class.  What happens when you have a bunch of permutations of data, you could end up having dozens of container classes therefore increasing the cost of maintenance.

Another option would be to use an array of object.  Although it can be done, it has a huge performance impact and

The tuple option can be like this:

var t = TupleFunction("Test");
Console.WriteLine("return value: {0} :: {1}", t.Item1, t.Item2, t.Item3);

public static Tuple<int, string, string> TupleFunction(string inParameter)
{
var retInt = 0;
var retString1 = string.Empty;
string retString2;

     if (!string.IsNullOrEmpty(inParameter))
{
retString1 = inParameter;
retString2 = "Kewl";
retInt = 1;
}
else retString2 = "NOT Kewl";

     return Tuple.Create(retInt, retString1, retString2);
}

The code performs the same overall function but does not rely on output parameters.  You may look at the source as the same length and seems to hide the vales inside of a strange object.  The caller of the Tuple function does not have to create a container variable except for the return value.  Consider the situation where the call needs to be extended to return a third value, or a forth?  The tuple can be extended with more values and the caller can deal with the longer return set or not as the caller’s choice (if you like var) because the actual call is not determined at run time but at compile time.

There are some drawbacks to tuples:

  1. You can’t change the values once placed into a tuple.
  2. Unlike list types, you can’t iterate through the values.

I hope this helps.

Windows: Wired vs Wireless

This morning I started up my work laptop after placing gently yet firmly into the docking station and saw my connection to the network was with the wireless network.  Something inside of me thought, “The docking station has a wired connection, why not use it versus a wireless connection?”.  Now that I have considered it for more than a few minutes, I am a little upset about the wireless preference when a perfectly good wired connection exists.

Armed with a sense of righteous empowerment and a little noodle power, I think I have come up with a sure fire way for WIndows to chose the right connection given a set of scenarios.  Here goes:

  1. Speed advantage– If one is faster than another then go with the fastest
    • Pros – the fastest will result in the best experience for the user.
    • Cons – How often does the measurement need to take place?  Do we warn the user when switching in case they are streaming or connected via VPN or any form of connection where the adapter and the data flow matters?
    • Net – I don’t see this as a viable option when it comes to configuration because the cons are too many and too hard to interpret.
  2. All network connections– Have no preference and use them all at once
    • Pros – Amazing throughput for applications that can use more than one connection at a time.
    • Cons – Incredibly complex implementation.  If wired and wireless are pointing to the same network there would be no advantage to the multiple connection points.  Possible application issues for apps that require a specific MAC or IP.
    • Net – Too many potential issues but if it could be done, the result could be amazing.
  3. Use wired as primary then wireless as a secondary or allow the user to select a preference
    • Pros – Simple and predictable; wired is usually better for speed and throughput; user preferential order for overrides; the functionality for wireless already exists
    • Cons – The user needs to know which is faster; the user may get confused if too many networks are available
    • Net – Easiest for Windows to support because half of the functionality exists

I don’t think making the third option work would be too hard and third parties may be able to get the other options working.  This request will be made to the Microsoft support network but I am interested in getting your feedback.

The PowerShell Journey: Part 1

As a developer I try to use the latest and greatest and when something good comes about I try to pick up as much of it as I can.  The use of command or batch files has been a part of my world for a long as I have used computers.  Back in the day, there were batch menus for DOS computers so people with little or no computer experience could get the their applications (Lotus 123, Wordstar, etc.)  The days of doing DOS menus has past but the power of the command shell remains.

The New Command Shell for Windows

I know I am late to the party when it comes to PowerShell but when it comes to shells I am skeptical at first, excited or dismayed second.  Recently there seems to be more and more need to run a shell with more power than VBScript could hope to provide, I was skeptical but I now see the fruit of such a pursuit.  When PowerShell hit the street I hardly noticed because I was very happy with my shell and I could do anything with a cscript command that could not be done with old DOS commands.   Thanks, but no thanks.

Then something changed, I needed to run a script to start & stop an IIS application pool on another server.  I looked and found this http://blog.developers.ie/cgreen/archive/2006/10/20/2341.aspx which clearly uses .NET to control a remote IIS web application pool.  I was about to translate this to VBScript when I thought about what PowerShell is supposed to be able to do out of the box.  I pursued it and came up with the following script:

# Action : Start, Stop, Recycle
param([string]$server, [string]$AppPool, [string]$Action)
$sPath = "IIS://" + $server + "/W3SVC/AppPools/" + $AppPool
$de = New-Object System.DirectoryServices.DirectoryEntry($sPath)
$de.Invoke($Action)

I know it isn’t sexy but it performs the task I needed. This is just the beginning, I’m sure there will be more scripts with more meat in them. Stay tuned, I am starting a series: The PowerShell Journey.

Code Simplification: String Maximum Length

I was looking at some old code and ran across something that struck a chord of wrong with me.

string temp; 
temp = "There can only be one!";
if (temp.length > 15) temp = temp.substring(0, 15);

Then I thought we could use a little math to handle the problem:

string temp; 
temp = "There can only be one!";
temp = temp.substring(0, Math.Min(15, temp.Length));

I think Microsoft should have included this kind of method to the String class. Hope this helps.

Enterprise Library 5.0 – Notes

The new version of Enterprise Library has some interesting implied additions and constraints.  I have used the frameworks before and like them for the most part, they keep the structure of a large application from looking like slop.  I took a good look at it and I am impressed how much better the library gets in each release.  In our organization however, we have chosen not to use the framework because we used the first few and converting from 1.0 or 1.1 to 2.0 to 3.1 was a royal pain.  Several applications used 3 and 4 but they soon converted to the Castle framework because the Castle team seemed to be making more progress.  Both have pros and cons which you may assess for yourself if your interest level is high enough.

What I do want to note is the lack of expressed Windows XP support with the Enterprise Library 5.  Here is the beginning of the system requirements section:

System Requirements Screenshot

I saw a comment asking if Windows XP was supported and the reply was that if it works, it works.

There are a ton of breaking changes this time, but none appear to be outside the realm of making things better in the long run.  There is also a Migration Guide as usual to help in the transition process.

Great job on the release and I hope to see more good things from the Enterprise Library in the future.

When is CRUD enough?

Let’s lay some groundwork before we start the rant.

CRUD is an acronym for the Create, Read, Update and Delete operations done to tables in a database.  I believe I can safely say “All database applications do at least the CRU of the CRUD”.

Now for the argument

I have never dealt with an enterprise level application that does just plain old CRUD.  In every case, there was some sort of logical requirement that precluded the CRUD requirement.  In the academic world there are examples of applications where CRUD operations can be done, but I have not been involved with one for a very long time.

Here’s an example:

Tables: UserInfo, ProductInfo, EventHistory

Assume EventHistory is a generic event history table with the key from the foreign table (UserInfo, ProductInfo, etc.)

Now, let’s add a new UserInfo record with the appropriate EventHistory record, this would require an Insert of the  UserInfo record with the retrieval of the key column then a write to the EventHistory table to record the user and such of the action.  Two trips even in a transaction, bleh.

How about writing a stored procedure to do the same.  One trip with little overhead to the calling application.  Simple, nice.

I’m sure there are a ton of people saying it could be done in a trigger and yet others think it should be done in the business application layer but in my opinion, the database is a good place to database oriented things.

SQL Server: Like with Underscores

There are times when you need to do a LIKE based search and need to find an underscore.  I was surprised to find the underscore is reserved as a single character wild card.

There are two ways to get this done.  First is the explicit ESCAPE definition as follows where the backslash is the escape character.

-- looking for anything with an underscore
SELECT  *
FROM    dbo.SomeTable
WHERE   ColumnName like '%\_%' ESCAPE '\'

To me, a better approach is surrounding the character is square brackets.

-- looking for anything with an underscore
SELECT  *
FROM    dbo.SomeTable
WHERE   ColumnName like '%[_]%'

The second approach may get a little confusing when looking for brackets though.

-- Looking for '[' + sometext + ']'
SELECT  *
FROM    dbo.SomeTable
WHERE   ColumnName like '%[[]%[]]%'

Hope this helps.