Posts Tagged ‘C#’

24
Jan

Try catch return bool

I was recently writing a lot of method that talked to 3rd party API. And after small refactoring a lot of methods was like try to call some method, if it throws exception return false, if not return true. And I was wondering, what’s the best (in terms of code being generated, speed, efficiency but also readability) way to write it.

I found basically three ways to write it (sure there are other ways):

try
{
	FooBar();
	return true;
}
catch (SomeException ex)
{
	LogException(ex);
	return false;
}
try
{
	FooBar();
	return true;
}
catch (SomeException ex)
{
	LogException(ex);
}
return false;
bool result = false;
try
{
	FooBar();
	result = true;
}
catch (SomeException ex)
{
	LogException(ex);
}
return result;

No magic. The third way is probably something you might recognize, if you were programming couple of years in Delphi/(Object)Pascal. Anyway, back to basics. My friend ildasm is going to help us with initial review, what we have actually done.
Everything compiled with full optimization turned on.

.method private hidebysig static bool  Test1() cil managed
{
  // Code size       28 (0x1c)
  .maxstack  1
  .locals init (class TryCatchTest.SomeException V_0,
           bool V_1)
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  call       void TryCatchTest.Program::FooBar()
    IL_0007:  nop
    IL_0008:  ldc.i4.1
    IL_0009:  stloc.1
    IL_000a:  leave.s    IL_0019
  }  // end .try
  catch TryCatchTest.SomeException
  {
    IL_000c:  stloc.0
    IL_000d:  nop
    IL_000e:  ldloc.0
    IL_000f:  call       void TryCatchTest.Program::LogException(class [mscorlib]System.Exception)
    IL_0014:  nop
    IL_0015:  ldc.i4.0
    IL_0016:  stloc.1
    IL_0017:  leave.s    IL_0019
  }  // end handler
  IL_0019:  nop
  IL_001a:  ldloc.1
  IL_001b:  ret
} // end of method Program::Test1
.method private hidebysig static bool  Test2() cil managed
{
  // Code size       32 (0x20)
  .maxstack  1
  .locals init (class TryCatchTest.SomeException V_0,
           bool V_1)
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  call       void TryCatchTest.Program::FooBar()
    IL_0007:  nop
    IL_0008:  ldc.i4.1
    IL_0009:  stloc.1
    IL_000a:  leave.s    IL_001d
  }  // end .try
  catch TryCatchTest.SomeException
  {
    IL_000c:  stloc.0
    IL_000d:  nop
    IL_000e:  ldloc.0
    IL_000f:  call       void TryCatchTest.Program::LogException(class [mscorlib]System.Exception)
    IL_0014:  nop
    IL_0015:  nop
    IL_0016:  leave.s    IL_0018
  }  // end handler
  IL_0018:  nop
  IL_0019:  ldc.i4.0
  IL_001a:  stloc.1
  IL_001b:  br.s       IL_001d
  IL_001d:  nop
  IL_001e:  ldloc.1
  IL_001f:  ret
} // end of method Program::Test2
.method private hidebysig static bool  Test3() cil managed
{
  // Code size       34 (0x22)
  .maxstack  1
  .locals init (bool V_0,
           class TryCatchTest.SomeException V_1,
           bool V_2)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  .try
  {
    IL_0003:  nop
    IL_0004:  call       void TryCatchTest.Program::FooBar()
    IL_0009:  nop
    IL_000a:  ldc.i4.1
    IL_000b:  stloc.0
    IL_000c:  nop
    IL_000d:  leave.s    IL_001b
  }  // end .try
  catch TryCatchTest.SomeException
  {
    IL_000f:  stloc.1
    IL_0010:  nop
    IL_0011:  ldloc.1
    IL_0012:  call       void TryCatchTest.Program::LogException(class [mscorlib]System.Exception)
    IL_0017:  nop
    IL_0018:  nop
    IL_0019:  leave.s    IL_001b
  }  // end handler
  IL_001b:  nop
  IL_001c:  ldloc.0
  IL_001d:  stloc.2
  IL_001e:  br.s       IL_0020
  IL_0020:  ldloc.2
  IL_0021:  ret
} // end of method Program::Test3

The third way is longest and I think also least readable (taking into account it’s C#). Also you can easily break the code. The first and second are really close in terms of code. The first one I’m using if I like to state, that after the exception is processed, nothing is going on further – “do, return or catch, return, done”. Nor in catch block, nor after it. The second one I’m using if my code is like “do something and return something” and then “else recover based on error and return fallback result”.

And what’s your preference?

13
Jan

CultureInfo equality

I have a small morale from today. I was writing some code that was handling searching for items base also on CultureInfo. Because it’s a pretty straightforward object, in core of .NET Framework (it’s in mscorlib) I was expecting to handle equality using == based on culture itself not the object. And of course, I was wrong. :)

The code below should explain it clearly (CurrentUICulture might be different based on your system).

// false
System.Threading.Thread.CurrentThread.CurrentUICulture == System.Globalization.CultureInfo.GetCultureInfo("en-US");
// true
System.Threading.Thread.CurrentThread.CurrentUICulture.Equals(System.Globalization.CultureInfo.GetCultureInfo("en-US"));

Yep. Learning something every day.

29
Dec

PowerShell script to tabify text (i.e. in code files)

Few weeks ago I needed to tabify (change spaces to tabs) in a C# files in a solution. I tested some plug-ins to Visual Studio, but none of them did what I wanted. I left the idea, as it was not that important to have consistent tabs/spaces. But a day or two ago I had some time and yen for to create simple PowerShell script to fix that for me. It simply replaces x spaces taken from input parameter with tab(s). Text goes to stdin and result to stdout.

param([int]$spaces)

$pattern = '';
for ($i = 0; $i -lt $spaces; $i++) {
	$pattern = $pattern + ' ';
}
$pattern = '^((' + $pattern + ')*)' + $pattern;
$replace = '$1' + "`t";

$input | foreach {
	$text = $_;
	do {
		$prev = $text;
		$text = $text -replace $pattern, $replace;
	} while ($prev -ne $text)
	Write-Output $text;
}

The script, as you can see, is not interpreting the code in any way, hence some spaces i.e. in comments at the beginning might become tabs even if that’s actually wrong. But hey, you can take Roslyn and plug it in, as an exercise. :)

To, for instance, tabify all .cs files in some path, you can call this script (saved as tabify.ps1) using something like:

Get-ChildItem -Recurse ".\src" | Where-Object {$_.Extension -eq ".cs"} | foreach { Get-Content $_.FullName | .\tabify.ps1 -Spaces 2 | Set-Content -Encoding UTF8 ($_.FullName + ".tabs") }
24
Dec

Composing functions the LINQ way

Few days ago I was writing a class, that was simply wrapped for a collection of other classes (with same interface), aggregate class. The class also had few methods, where the logic was simple. Let’s say one method M. Other classes having same method as well. This method was simple transformation of data with same output as input. The aggregate class was simply calling M method of first, second, … of other classes.

I started with something like this:

function T M<T>(T data)
{
	T tmp = data;
	foreach (var c in classes)
	{
		tmp = c.M(tmp);
	}
	return tmp;
}

But then I had some weird wave in my brain and started thinking. I could create collection of functions, like IEnumerable<Func<T, T>> and call methods from this collection. Wait a minute… I can create from this collection of function one aggregate function and call just this one. Crazy? ;) Probably. But it’s a nice way to keep my brain running.

It turned out, it’s pretty easy with LINQ:

public static Func<T, T> Compose<T>(this IEnumerable<Func<T, T>> source)
{
	return source.Aggregate((agg, fn) => (d => fn(agg(d))));
}

I don’t think it’s any more (less) useful than the foreach with direct method calls, but it’s more succinct, more functional and more fun. 8-)

29
Aug

Collection type result – speed comparison of IList.Add and IEnumerable.Concat

From time to time I’m working on some method that returns some collection. Mainly processing some data from input. Often it’s really just couple of conditions, get something from there and here and return it. Because I’m composing these methods too, if I return IEnumerable<T> and later in other method I need to add something (if you’re lost, you’ll see what I mean in example below), I need to use some variable, like array or list and append (or prepend). Boring.

For a while I was wondering, how slow it will be, if I’ll be simply creating new IEnumerable sequences and concatenating these. I was expecting it to be slower, but is it only couple of percents or order of magnitude? Today, when I came to my office, I simply decided to test it.

The first version looks like

static IEnumerable Test1(int[] part1, int[] part2, int[] part3)
{
	IEnumerable<int> result = Enumerable.Empty<int>();
	result = result.Concat(part1);
	result = result.Concat(part2);
	result = result.Concat(part3);
	return result;
}

And the other one

static IEnumerable<int> Test2(int[] part1, int[] part2, int[] part3)
{
	IList<int> result = new List<int>();
	foreach (var item in part1)
		result.Add(item);
	foreach (var item in part2)
		result.Add(item);
	foreach (var item in part3)
		result.Add(item);
	return result;
}

Although it, especially the other one, can be written in different way(s), as a measure I think it’s OK. And it’s close to how I often process the data.

I did couple of runs to eliminate some errors, with “Release” build, without attached debugger. The part1 and part3 parameters were always the same in size. The part2 I was playing with, because the size affects the speed too.

If the part2 size was roughly under 10k items, the speed difference was on the edge error of measurement. From 10k+ to 1M items it’s about 25% the Concat approach being slower. Some absolute numbers (averages from 20 runs, “Release” build, without attached debugger) from my laptop:

Size: 1         Time1: 0        Time2: 0        %: 0
Size: 2         Time1: 0        Time2: 0        %: 0
Size: 3         Time1: 0        Time2: 0        %: 0
Size: 4         Time1: 0        Time2: 0        %: 0
Size: 5         Time1: 0        Time2: 0        %: 0
Size: 6         Time1: 0        Time2: 0        %: 0
Size: 10        Time1: 0        Time2: 0        %: 0
Size: 100       Time1: 0        Time2: 0        %: 0
Size: 1000      Time1: 0        Time2: 0        %: 0
Size: 6000      Time1: 0,2      Time2: 0        %: 0
Size: 20000     Time1: 2,05     Time2: 0,5      %: 24,390243902439
Size: 60000     Time1: 6,55     Time2: 1,6      %: 23,3576642335766
Size: 100000    Time1: 11,8     Time2: 3,15     %: 24,7899159663866
Size: 1000000   Time1: 124,85   Time2: 33,2     %: 26,9609775325187

Conclusion? If the data is relatively small, the path you choose doesn’t really matter. For “bigger” collections the imperative approach provides better performance.

24
Aug

All and Any optimization in Entity Framework queries

When I’m teaching my Entity Framework trainings, I’m always begging to look, at least from time to time or when you see the query looks complex, to generated SQL statement. And if you have (near to) real data, also execution plan. Although Entity Framework helps you with standard data access layer, it’s not magic – the query translation is complex process and sometimes what you capture in LINQ query isn’t exactly how you’d express it in SQL. You simply have different concepts in LINQ vs. in SQL.

Last week I was writing some decision algorithms based on data and I was accessing it, of course, using Entity Framework. Because the conditions we’re complex I was writing these as it came from my head to my fingers. The day after I was writing similar condition, only one or two options negated and I wrote it differently. Basically I was swapping All and Any methods. These two are interchangeable, if you change conditions accordingly.

As an example let’s have and condition: “All apples are green.” aka “All(apple => apple.Color == Green)“. But you can also say “No (any) apple is non-green.” aka “!Any(apple => apple.Color != Green)“.

Now the magic comes to play. You might think, well, if it’s interchangeable, then it’s good, as Entity Framework can always utilize EXISTS predicate from SQL. For simple queries maybe. But if you think about various places where the condition can occur and how easy is to negate the condition you immediately have a lot of problems in front of you. Add to this database engine optimized, where it can or can’t use properly indices, reorder conditions to create smaller intermediate result sets etc. A lot of places where the machine needs to (try to) figure out what’s best way of getting your data for you.

Sadly there’s no rule of thumb, like always use Any. Only one good and 100% working advice is to always check the query and execution plan. But even with i.e. All the result could be absolutely fine.

9
Jul

Coalescing object and accessing it

I was reading Twitter yesterday and spotted a tweet from Shawn Wildermuth about his pain about using coalesce operator (??) in C# and doing immediately something with result.

I had same problem maybe a year back, when I was dealing heavily with XML and LINQ to XML (but it doesn’t matter). I created for myself a little extension method to help me solve writing lines like:

Something x = (a == null ? "FooBar" : a.FooBar);

The method:

public static TResult ObjectCoalesce<T, TResult>(this T o, Func<T, TResult> operation, TResult @default)
	where T : class
{
	if (o == null)
		return @default;
	else
		return operation(o);
}

And simple usage:

Something x = a.ObjectCoalesce(y => y.FooBar, "FooBar");

When it’s nested in some calls, it really helped me to make my code shorter. You can also play (I did) with idea of having the default parameter as delegate so it will be evaluated only if needed. In some cases it could make a huge difference (i.e. side-effects).

16
May

Easy indentation control for Debug/Trace/…

I was setting up simple command logging, but keeping in my mind where I increased the indentation to later decrease it back was causing me headache. Also formatting the string I’d like to put out wasn’t smooth.

So I created simple wrapper class implementing IDisposable, where the disposing will actually decrease the indentation automatically. Only thing you (I) have to use is simple using block. The precooked WriteLine helper method is there just to save me some typing.

class IndentHolder : IDisposable
{
	public void Dispose()
	{
		Trace.Unindent();
	}
}

public static void WriteLine(string format, string category, params object[] args)
{
#if (TRACE)
	Trace.WriteLine(string.Format(format, args), category);
#endif
}

public static IDisposable Indent()
{
#if (TRACE)
	Trace.Indent();
	return new IndentHolder();
#endif
}
15
Mar

Are you Lazy<T>?

Yesterday I was chatting with Aleš Roubíček after lunch and he told me he likes the Lazy<T> I put into project we’re working right now and that could be worth to write about it.

Well, here it is. The Lazy<T> class is new in .NET Framework 4. Using this class is easy. If you don’t wnat to create instance of some object until it’s really needed this class will help you. And it can deal with multithreading as well.

So the well known code:

Foo _foo;
public Foo Foo
{
	get
	{
		if (_foo == null)
			_foo = new Foo();
		return _foo;
	}
}

can be replaced with:

Lazy<Foo> _foo = new Lazy<Foo>(() => new Foo());
public Foo Foo
{
	get
	{
		return _foo.Value;
	}
}

Nothing special, but when the multithreading comes into play, it’s more fun. This class has a constructor taking LazyThreadSafetyMode and you can specify what kind of thread safety you want.

By the way if you don’t provide the function, the default constructor will be invoked.

Handy isn’t it.

Let’s play with it:

class Program
{
	static void Main(string[] args)
	{
		Test(LazyThreadSafetyMode.PublicationOnly); // 2x ctor, True
		Console.WriteLine("===");
		Test(LazyThreadSafetyMode.ExecutionAndPublication); // 1x ctor, True
	}

	static void Test(LazyThreadSafetyMode mode)
	{
		Lazy<Foo> _foo1 = new Lazy<Foo>(() => new Foo(), mode);
		Foo f1 = null;
		Foo f2 = null;

		Parallel.Invoke(() => { f1 = _foo1.Value; }, () => { f2 = _foo1.Value; });
		Console.WriteLine("Same: {0}", object.ReferenceEquals(f1, f2));
	}
}

class Foo
{
	public Foo()
	{
		Console.WriteLine("Running Foo's ctor.");
		Thread.Sleep(2000);
		Console.WriteLine("About to finish ctor.");
	}
}
28
Feb

Casting Expression<Func<TEntity, TProperty>> to Expression<Func<TEntity, object>>

From time to time I’m dealing with API that’s using Expression<Func<TEntity, object>> as parameter, mainly to show property you want to deal with. And that’s fine, if you need just the expression itself. But I often create my custom extensions, where I’m somehow working with the property itself or the result. And that’s a problem, because I don’t know any info about the type, it’s just object.

If you try to directly cast the expression, it will not work, of course. First I though, it’s going to be a lot of juggle with pieces of expression and reconstructing the final one. But it’s pretty easy, see yourself:

void FooBar<TEntity, TProperty>(TEntity entity, Expression<Func<TEntity, TProperty>> property)
{
	Expression<Func<TEntity, object>> result;
	if (typeof(TProperty).IsValueType)
		result =  Expression.Lambda<Func<TEntity, object>>(Expression.Convert(property.Body, typeof(object)), property.Parameters);
	else
		result = Expression.Lambda<Func<TEntity, object>>(property.Body, property.Parameters);
	// do something with result ...
}

I’m simply creating new expression based on the original ones’ body and parameters. If the TProperty‘s type was value type I only do boxing in addition.

Nothing difficult, right?

4
Nov

Mapping private or protected properties with Code First (EFv4, CTP4)

If you’re specifying mapping in Code First in Entity Framework you’re essentially describing it with like this (assuming using EntityConfiguration class).

this.Something(x => x.Foo).Bar();

This is nice, but if the property you wanna to use is either private or protected you are hitting wall as you can’t write such expression. I faced the same problem today. The easiest approach is to have the configuration class nested to entity itself. But that’s not a clean (or may not be doable) and I do want clean code.

Because I know, Entity Framework can use these properties – if you’re using designer it’s just setting some fields in Properties window. So I concluded, that the only problem is to how to push it into Code First. My focus was primarily for MapSingleType method (but it’s doable for i.e. Property method as well).

With the method you can write two types of mapping, one using EntityMap class directly.

this.MapSingleType(x =>
	EntityMap.Row(
		EntityMap.Column(x.Foo, "FooColumn"),
		EntityMap.Column(x.Bar, "BarColumn")))
.ToTable(new StoreTableName("Baz", "dbo"));

Or one using anonymous type.

this.MapSingleType(x => new
    {
        FooColumn = x.Foo,
        BarColumn = x.Bar
    })
.ToTable(new StoreTableName("Baz", "dbo"));

With the starting point set I decided the easiest way to specify private or protected properties will be using string. The only task is to create the Expression that’s else generated by compiler. After some juggling with the trees I created this extension method.

public struct ColumnPropertyMapping
{
	public string Column { get; set; }
	public string Property { get; set; }

	public ColumnPropertyMapping(string column, string property)
		: this()
	{
		this.Column = column;
		this.Property = property;
	}
}
public static EntityMap MapSingleType<TEntity>(this EntityConfiguration<TEntity> configuration, Expression<Func<TEntity, object>> initialMapping, params ColumnPropertyMapping[] additionalMappings)
	where TEntity : class
{
	if (additionalMappings == null)
		throw new ArgumentNullException("additionalMappings");

	List<Expression> newParameters = new List<Expression>();
	var entity = initialMapping.Parameters[0];

	Func<ColumnPropertyMapping, MethodCallExpression> makeColumnCall =
		m =>
			Expression.Call(
				typeof(EntityMap),
				"Column",
				null,
				Expression.Convert(
					Expression.MakeMemberAccess(entity, typeof(TEntity).GetMember(m.Property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).First()),
					typeof(object)),
				Expression.Constant(m.Column));

	var callExpression = (initialMapping.Body as MethodCallExpression);
	var newExpression = (initialMapping.Body as NewExpression);
	if (callExpression != null)
	{
		newParameters.AddRange((callExpression.Arguments[0] as NewArrayExpression).Expressions);
	}
	else if (newExpression != null)
	{
		newParameters.AddRange(newExpression.Arguments.Select((e, i) => new ColumnPropertyMapping(newExpression.Members[i].Name, (e as MemberExpression).Member.Name)).Select(x => makeColumnCall(x)));
	}
	else
	{
		throw new ArgumentException("initialMapping");
	}

	newParameters.AddRange(additionalMappings.Select(x => makeColumnCall(x)));

	var finalMapping = Expression.Lambda<Func<TEntity, object>>(
		Expression.Call(
			typeof(EntityMap),
			"Row",
			null,
			Expression.NewArrayInit(
				typeof(EntityMapColumn),
				newParameters)),
		entity);

	return configuration.MapSingleType(finalMapping);
}

It’s method with similar signature as the original one, but taking extra collection of ColumnPropertyMapping, my helper objects to represent the mapping as strings. I take the input – EntityMap or anonymous object – peck up the important pieces and recreate the expression with added properties. I’m resulting to tree with EntityMap, as it looked easier to create. So now you can create the mapping also for non-public properties (and also dynamic mapping is easier).

this.MapSingleType(x =>
	EntityMap.Row(
		EntityMap.Column(x.Foo, "FooColumn"),
		EntityMap.Column(x.Bar, "BarColumn")),
	new ColumnPropertyMapping("SomeColumn", "ImNotPublic"))
.ToTable(new StoreTableName("Baz", "dbo"));

// or

this.MapSingleType(x => new
		{
			FooColumn = x.Foo,
			BarColumn = x.Bar
		},
		new ColumnPropertyMapping("SomeColumn", "ImNotPublic"))
.ToTable(new StoreTableName("Baz", "dbo"));

Enjoy, if you need it. :) I hope the CTP5 will address this “scenario”, thus I’ll not be forced to write it for other methods. And if not, stay tuned, I’ll definitely post it. 8-)

22
Oct

Explicit default access modifiers?

Few months ago Miguel de Icaza posted on Twitter message about explicitly stating your member private access modifier (or anything that’s default) and that he doesn’t understand it, the he wants his code be succinct.

class Foo
{
	private int _bar;
	// or?
	int _bar;
}

I, as a lot of other people, replied, that I want to be explicit about my code. Tell exactly what I want. However I had a sneaking idea in my brain since this message – because I like my code, my thoughts in code, to be succinct – and I decided give it a try. I removed all the explicit access modifiers that are actually default from ID3 renamer‘s code base a start. Well, after working with it some time, I didn’t noticed anything confusing. There’s only couple of default rules, so it’s not like you would need to learn a lot of new stuff. And, for me, because there’s less text in source code, it looks more readable for me, especially if I’m just checking something out using notepad-like (no highlighting) viewer.

I’m now following this “rule” for every new code I’m writing. I like it when I spin my head around something that looks completely useless to think about, for a first sight, but later shows up to be a good idea or true.

5
Oct

LINQ and left outer join helper

Previous two functions (function 1, function 2) I presented were doing something that wasn’t core part of LINQ and it was up to you to create it. On the other hand, this function is different. It’s just a helper to simplify writing of left outer join (or right outer join, depending on what collection you consider to be on left/right side). Not because it’s hard to write it, but because it involves couple of lines and repeating it all the time is just boring. 8-)

internal static IEnumerable<TResult> LeftOuterJoin<TOuter, TLeft, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TLeft> left, Func<TOuter, TKey> outerKeySelector, Func<TLeft, TKey> leftKeySelector, Func<TOuter, TLeft, TResult> resultSelector)
{
	return
		from o in outer
		join r in left on outerKeySelector(o) equals leftKeySelector(r) into j
		from r in j.DefaultIfEmpty()
		select resultSelector(o, r);
}

Nothing tricky. You can find this in many examples, I just wrapped it into method and parametrized it a little. Enjoy.

5
Oct

Aggregating with increments

Similarly to previous method for Interleaving two IEnumerables I needed one method for doing kind of aggregate, but also to know about the intermediate steps. I could abuse the Aggregate method either directly or indirectly but I’m always more happy with clean solution.

The method is pretty simple (but before I did some rework, it was ugly ;) ). It takes, apart from the IEnumerable, two functions. One for setting up the initial value for the first item and one for getting result for next step.

internal static IEnumerable<TResult> IncrementalAggregate<TSource, TResult>(this IEnumerable<TSource> data,
	Func<TSource, TResult> init,
	Func<TSource, TResult, TResult> nextResult)
{
	bool first = true;
	TResult intermediate = default(TResult);

	foreach (var item in data)
	{
		if (first)
		{
			intermediate = init(item);
			first = false;
		}
		else
		{
			intermediate = nextResult(item, intermediate);
		}
		yield return intermediate;
	}
}

With it you can do i.e. summing the numbers and know what the intermediate sums were. Yes, sounds weird, but you might need it, one day as I did. :)

5
Oct

Interleaving two IEnumerable sources

I was recently doing some work related to custom reporting and I needed to simply interleave two streams of data (it was actually same source, but different items selected). Kind of select first item from the first stream, first from the other, second from first, second from other etc. No big deal.

To make this easily doable I created simple extension method for me.

internal static IEnumerable<T> Interleave<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
	using (IEnumerator<T>
		enumerator1 = first.GetEnumerator(),
		enumerator2 = second.GetEnumerator())
	{
		while (enumerator1.MoveNext())
		{
			yield return enumerator1.Current;
			if (enumerator2.MoveNext())
				yield return enumerator2.Current;
		}
	}
}

It keeps reading elements from the first stream and if there’s enough in the second stream then interleave. If the second one isn’t “long” enough, it’ll keep returning only items from first one. If the second one is “longer”, it’ll stop when the first one is empty. If you need handle these cases differently, you can either change the method or preprocess the streams before using this method.

29
Jun

Prepend method in LINQ

Yesterday I needed to put one element at beginning of the collection I already had. Some kind of Concat upside down. :) As you can use the Concat method, it looks weird when you see the code, because two items are actually swapped. So I created a simple extension method to do it for me.

I started with:

public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
	yield return item;
	foreach (var x in source)
		yield return x;
}

It’s classic imperative approach, you’re expressing how you’ll do it. Then I thought: “Hey, why not to use LINQ methods already available.”. As you guess, I abused Concat method as I wrote above:

public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
{
	return new[] { item }.Concat(source);
}

You can easily extend both methods to accept also collection as a second parameter.

If you’re more about declarative programming you’ll probably like the other one. But choose whatever fits your brain better.

26
Jun

How to break your code easily a.k.a my params hell

Today I faced a behavior I have no idea exists. It’s more or less ambiguity between method with some parameters and one using params. Why more or less? Well, because it surely described in C# specification (“best match” or something similar to it). But I hadn’t know I should think about it until I was debugging weird behavior.

Let’s start with simple class:

class Test
{
	public Test(params int[] foos)
	{
		Console.WriteLine("foos");
	}

	public Test(int foo, int bar)
	{
		Console.WriteLine("foo bar");
	}
}

And now some (mind blowing ;) ) code:

new Test(1);
new Test(1, 2);
new Test(1, 2, 3);

If you see the code in the context you probably spot the problem easily. The second row will not call the params but the other constructor.

Which is “cool” until you’re doing some refactoring and you (as I did) add new constructor with params and everything starts behaving unexpectedly. Maybe this text will help somebody to realize this faster than I did. :D

6
Jun

Running the other method on same thread as the first one

Last week I was solving problem. The piece of code another code was plugged in was doing some crazy threading stuff inside while the code plugged in used some component that needed some methods (in my case just two) to be called in same thread. Well, that is to make the long story short.

As I couldn’t rely on the fact, that the thread calling the first method will be still available when the other one needs to be called I decided to simply steal one thread (in fact ThreadPool thread) for it a abuse it exclusively. To encapsulate this hack I created this class.

Before you dive into, I have to note, that it is really not a general purpose class and you shouldn’t blindly use it – you can easily use it badly and i.e. create unwanted shared state, screw the flow of your program or get wrong results due race conditions, …

/// <summary>
/// This is NOT a general purpose class.
/// Use with care.
/// </summary>
sealed class ThreadMethodRunner : IDisposable
{
	AutoResetEvent _eventMethodDone;
	AutoResetEvent _eventMethodIn;
	Action _method;

	public ThreadMethodRunner()
	{
		_eventMethodDone = new AutoResetEvent(false);
		_eventMethodIn = new AutoResetEvent(false);
		ThreadPool.QueueUserWorkItem(new WaitCallback(MethodRunnerWrapper), null);
	}

	private void MethodRunnerWrapper(object o)
	{
		for (int i = 0; i < 2; i++)
		{
			Debug.WriteLine("Waiting for method");
			_eventMethodIn.WaitOne();
			Action a = Interlocked.Exchange(ref _method, null) as Action;
			a();
			Debug.WriteLine("Method done");
			_eventMethodDone.Set();
		}
		Debug.WriteLine("Thread done");
	}

	public void Do(Action method)
	{
		Interlocked.Exchange(ref _method, method);
		_eventMethodIn.Set();
		_eventMethodDone.WaitOne();
	}

	public void Dispose()
	{
		_eventMethodDone.Dispose();
		_eventMethodIn.Dispose();
	}
}

This class allows you to call the Do method with Action delegate and the method will run the code on the same thread every time (in my case just two times) called. This method blocks as you probably want to keep the behavior of you old code (at least in boundaries of method calls order, not changing some state etc. as mentioned above).

I don’t know if it’s worth any other usage than mine, but at least somebody may be inspired.

15
May

T4 templates processing at runtime

The T4 templates are great tool for use. You can generate literally anything with it with comfort of using any .NET code you have available. Code generation (i.e. POCO classes in EFv4), web service proxies, simple DALs, …, all easily available.

But what if your scenario is one step further? You don’t want to use T4 template to generate i.e. code you’ll later compile into your application, but use the T4 template in runtime to generate result your application will later use (i.e. email based on template). Good news is you can do it, and it’s not hard either.

Easiest way is to start with Preprocessed Text Template file type adding to your solution. The file itself is ordinary T4 template you’re familiar with. But if you build your project the result produced isn’t output from template, but the C#/VB code that produces the result if called. Same result can be done by changing Custom Tool into TextTemplatingFilePreprocessor in Properties window of your current T4 template file.

Then you can create instance of this class (it has same name as your template file), setting up properties, if any and calling TransformText method. Pretty easy, isn’t it?

28
Aug

Using custom properties as parameters in queries (in EF)

Most of the time you’re using properties in objects that are also in database. But sometimes you may need to create property in object that’s not in database – it’s used only in this application or it’s there custom logic. Then, if you wanna use it in queries, you’re out. You can use only those properties declared in table, obviously.

But there’s a solution. First, the property has to be created from some other properties, so you’re able to do the same in database. And of course, functions used there needs to be translatable to store language too. This may limit you, but there’s nothing you can do about it, except evaluating query on client side.

Let’s have a table like this:

create table Foo (
  ID int primary key,
  IsAccepted bit,
  IsPaid bit not null,
  IsPacked bit not null,
);

And you wanna have property IsReadyToShip, in application. So you create:

public bool IsReadyToShip
{
  get { return this.IsAccepted.HasValue && this.IsAccepted && this.IsPaid && this.IsPacked; }
}

But with this property you’re not able to query for all Foos ready to ship. Luckily the solution is pretty easy. First you’ll create expression for this:

public static Expression<Func<Foo, bool>> IsReadyToShipExpression = f => f.IsAccepted.HasValue && f.IsAccepted && f.IsPaid && f.IsPacked;

Then you’l prepare static compiled version of this expression, just for performance reasons, you can compile it in getter everytime too:

protected static Func<Foo, bool> IsReadyToShipFunc = IsReadyToShipExpression.Compile();

And finally the property:

public bool IsReadyToShip
{
  get { return IsReadyToShipFunc(this); }
}

Right now we have the same result as before – working property. But because we also have the expressions of the property (and incidentally it’s translatable to store language ;) ), so we can use it for querying. You can use it in an easy way (this is in this case ObjectContext used in Entity Framework):

public IQueryable<Foo> FoosReadyToShip
{
  get { return this.Foos.Where(Foo.IsReadyToShipExpression); }
}

Not the shortest way to do it. But if you don’t wanna to write the condition again and again (and lower the maintainability) this is a way to do it.

Next Page »