Thursday, October 21, 2010

Run synchronous process with a timeout

I have run into situations where the blocking call I'm making isn't guaranteed to terminate itself ever. I want control over how long I wait before giving up.

private static void RunSync(int timeout, Action toDo)
      Exception threadException=null;
      Action wait = ( ) =>
          toDo( );
        catch (Exception ex)
      var thread = new Thread(( ) => wait( ));
      thread.Start( );
      if (!thread.Join(timeout))
        thread.Abort( );
        throw new TimeoutException("No connection found within timeout:"+timeout/100+" seconds");
      if (threadException!=null)
        throw threadException;
This function is set up to wait for another multi-threaded class to try to find a connection and use it. If the timeouts on that class are set improperly or the threading code is bad and just never does a timeout or return, this gives me the option to stop waiting.

Simple MsBuild Custom Task

Here's a very simple custom task that reads in the number in a text file (which only contains a number) increments, passes it back out to the calling MsBuild, and then writes the new value to the text file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace BMsBuildTasks
  public class IncrementerTask:Task
    public ITaskItem OutputFullPath { getset; }
    public int Value { getset; }
    public override bool Execute( )
      var path =OutputFullPath==null?OutputFullPath.GetWellKnownMetaData(WellKnownMetaData35.FullPath ):
      int value;
      using (var file=new System.IO.StreamReader(path))
        if (!int.TryParse(file.ReadToEnd( ), out value))
          return false;
      using (var file=new System.IO.StreamWriter(path,false))
      OutputFullPath = new TaskItem(path);
      return true;

    public static string GetWellKnownMetaData(this ITaskItem item, WellKnownMetaData35 value)
      return item.GetMetadata(value.ToString( ));

public enum WellKnownMetaData35

Wednesday, October 20, 2010

EF4 whitelist/explicit eager loading

In linq to sql it was very simple:

    var loadOptions = new System.Data.Linq.DataLoadOptions();
    loadOptions.LoadWith<alliance>(a => a.Players);
    dc.LoadOptions = loadOptions;

where dc was the datacontext.

This specifies that any queries that are submitted to this DataContext that return an Alliance object/entity would also go ahead on the same db trip and fetch it's related Players.

In EF4.0 so far it looks like you have to resort to magic strings. Magic strings are a pet peeve of mine. Your compile time type safety goes out the window in this type of magic string use.

Here are 2 solutions I've found on my googling that can get rid of the magic strings for EF4.