Archive for the ‘.NET’ Category
MSBuild Task: Solution and Project dependencies
Few months ago I needed to use MSbuild to build solution. Sounds simple right? Yeah, but not quite.
Somehow, my msbuild failed with project dependency issues. It turns out that MSBuild doesn’t respect project dependencies in a solution. Google “msbuild solution dependencies” and you’ll find various post complaining about the problem with MSBuild.
I modified the MSBuild task found here to get projects in a solution file in dependency order.
You can then call the task to get the projects and compile them in order:
<Target Name="BuildProjects"> <GetProjecsInOrder Solution="$(MSBuildProjectDirectory)\MySolution.sln"> <Output ItemName="ProjectFiles" TaskParameter="Output"/> </GetProjecsInOrder> <MSBuild Projects="%(ProjectFiles.FullPath)" Targets="Build" Properties="Configuration=Release"/> </Target>
You can download the modified source from http://www.esnips.com/doc/8e232db4-21ac-4d93-90dc-2a8bc4db34a8/MSBuildTasks
IDataReader GetValue Extension method
It is offten desired to get a value from DataReader using column name with known Type. For example you want to get a string value of column ‘first_name’ and int value of column ‘account_number’. The following extension method makes it easy to fetch values from a DataReader using Type and column name:
public static class ReaderHelper
{
public static bool IsNullableType(Type valueType)
{
return (valueType.IsGenericType &&
valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
}
public static T GetValue<T>(this IDataReader reader, string columnName)
{
object value = reader[columnName];
Type valueType = typeof(T);
if (value != DBNull.Value)
{
if (!IsNullableType(valueType))
{
return (T)Convert.ChangeType(value, valueType);
}
else
{
NullableConverter nc = new NullableConverter(valueType);
return (T)Convert.ChangeType(value, nc.UnderlyingType);
}
}
return default(T);
}
}
It can be used as:
User GetUser(IDataReader reader)
{
User user = new User();
user.FirstName = reader.GetValue<string>("first_name");
user.LastName = reader.GetValue<string>("last_name");
user.Email = reader.GetValue<string>("email");
user.AccountNumber = reader.GetValue<int>("account_number");
user.NumberOfVehiclesOwned = reader.GetValue<int?>("vehicle_count"); // nullable data field
return user;
}
RotateString v2.0
I added the ability to rotate string right or left. Here is the code:
public enum Direction { Right, Left }
string rotateString(string source, int rotationCount, Direction direction)
{
if (String.IsNullOrEmpty(source) || rotationCount <= 0)
return source;
int pivot = 0;
List<int> delimiterLocations = new List<int>();
char[] sourceChars = new char;
char temp;
// Reverse the whole string and
// save the dilimiter locations
for (int i = 0; i < source.Length; i++)
{
sourceChars = source[i];
if (source[i] == ' ')
delimiterLocations.Add(source.Length - i - 1);
}
// calculate neededDelimiters mod wordCount
// (assume words = delimiterCount + 1)
pivot = rotationCount % delimiterLocations.Count;
if (pivot > 0)
{
if (direction == Direction.Left)
pivot = delimiterLocations.Count - pivot;
pivot = delimiterLocations[delimiterLocations.Count - pivot];
}
else
{ return source; }
// reverse the first part
for (int i = 0, j = pivot - 1; i <= j; i++, j--)
{
temp = sourceChars[i];
sourceChars[i] = sourceChars[j];
sourceChars[j] = temp;
}
// reverse the second part
for (int i = pivot + 1, j = sourceChars.Length - 1;
i <= j; i++, j--)
{
temp = sourceChars[i];
sourceChars[i] = sourceChars[j];
sourceChars[j] = temp;
}
return new string(sourceChars);
}
StackOverflow – RotateString
Someone asked the following question on StackOverflow. Before I could post my answer, it was removed. Hmm, so He/She tried to abuse StackOverflow! Anyway, I found that question interesting.
The question was to write a function to rotate a string of words. Words are separated by ‘ ‘ (space). In the result string, the words should remain human readable. The function will also take an integer argument that will specify number of words to rotate.
example:
string source = “A quick brown fox jumps over the lazy dog.”
rotateString(source, 3);
Should give:
the lazy dog. A quick brown fox jumps over
Here is my solution:
static string rotateString(string source, int rotationCount)
{
if (String.IsNullOrEmpty(source) || rotationCount <= 0)
return source;
int pivot = 0;
List<int> delimiterLocations = new List<int>();
char[] sourceChars = new char;
char temp;
// Reverse the whole string and
// save the dilimiter locations
for (int i = 0; i < source.Length; i++)
{
sourceChars = source[i];
if (delimiterLocations.Count < rotationCount && source[i] == ' ')
delimiterLocations.Add(source.Length - i - 1);
}
// calculate neededDelimiters mod wordCount
// (assume words = delimiterCount + 1)
pivot = rotationCount % (delimiterLocations.Count + 1);
if (pivot > 0)
pivot = delimiterLocations[pivot-1];
else
return source;
// reverse the first part
for (int i = 0, j = pivot - 1; i <= j; i++, j--)
{
temp = sourceChars[i];
sourceChars[i] = sourceChars[j];
sourceChars[j] = temp;
}
// reverse the second part
for (int i = pivot + 1, j = sourceChars.Length - 1;
i <= j; i++, j--)
{
temp = sourceChars[i];
sourceChars[i] = sourceChars[j];
sourceChars[j] = temp;
}
return new string(sourceChars);
}
Asynchronous Delegates in .NET 2.0
One of the good features of .NET 2.0 is Asynchronous Delegates. Use these when you want to maintain the application responsive and reliable. Especially when the application wants to complete an IO call, database call, web service call or number crunching (CPU intensive) that can take up fairly long time. For example refreshing of the UI is handled by a single main thread. Which means all the events such as mouse click, mouse movement, keyboard events and even displaying text to the console are handled by this single thread. In this case we were told that we should use threads, i.e. spawn a worker thread and return quickly. But in .NET it is efficient to re-use threads, i.e. borrow them from .NET ThreadPool and not instantiate them. Jeffrey Richter goes on to describe in detail why so in this interview. To simply summarize Jeffrey I can say that spawning a new thread is a costly affair. One of the ways to re-use/borrow threads is to use Asynchronous Delegates. Asynchronous pattern basically involves fire and forget. Once the result is available .NET will call back a method that you must specify during the initial call.
The .NET runtime generates BeginInvoke and EndInvoke methods for each delegate defined. BeginInvoke is a non blocking method and returns right away.Lets take an example of a method that takes long time
public int MySlowTask(int someInput)
{
//simulate slow task
Thread.Sleep(20);
Console.WriteLine(“Processed input : {0}”,someInput);
return someInput+1;
}
In order to call a method asynchronously we must define a delegate with same method singnature as that method.
delegate int SlowTaskDelegate(int someInput);
SlowTaskDelegate slowTaskDelegate = MySlowTask;
Then we call the BeginInvoke method to call the long task asynchronously.
slowTaskDelegate.BeginInvoke(10, // Input parameter to MySlowTask()
EndInvokeMySlowTask, // Callback Method
slowTaskDelegate); // AsyncState
We must also write EndInvokeMySlowTask method (a callback method) that the runtime calls after completing the task.Its signature is fixed defined as
void MethodName(IAsyncResult result):
public void EndInvokeMySlowTask(IAsyncResult result)
{
SlowTaskDelegate myDelegate = result.AsyncState as SlowTaskDelegate;
// obtain the result
int resultVal = myDelegate.EndInvoke(result);
Console.WriteLine(“Returned output : {0}”,resultVal);
}