Posts Tagged ‘sharepoint’

Linq “in” clause

July 14, 2011 Leave a comment

So… today I needed to do a simple query like

SELECT * FROM Activities a Where a.Community in ('Community 1', 'Community 2', 'Community 3')

…with Linq.

In the objects world this is managed using the Contains method of IList. The perfect Linq for the previous query is:

var communities = new []{ "Community 1", "Community 2", "Community 3" };
var result = activities.Where(x => communities.Contains(x.Community));

The problem with this is no all Linq providers understands it. And SPLinq (Linq for SharePoint) is one of those who doesn’t.

The other way to handle this kinds of queries is, in SQL:

SELECT * FROM Activities a Where a.Community = 'Community 1' or a.Community = 'Community 2' or a.Community =  'Community 3'

But how to create the Linq query dynamically? Well… All these months working with Magiq gived me the ability of compile Expression trees in my head 🙂

This is the code needed:

private static IQueryable<T> Where<T>(this IQueryable<T> self, Expression<Func<T,object>> property, IEnumerable<string> @in)
	var propertyName = ((MemberExpression)property.Body).Member.Name;

	Expression expression = null;

	var x = Expression.Parameter(typeof (ActivityItem), "x");
	foreach (var community in @in)
		var propertyExpression = Expression.Property(x, propertyName);
		var equal = Expression.Equal(propertyExpression, Expression.Constant(community));
		expression = expression == null ? equal : Expression.Or(expression, equal);

	if (expression == null)
		return list;

	var lamda = Expression.Lambda<Func<T, bool>>(expression, x);
	return self.Where(lamda);

var communities = new []{ "Community 1", "Community 2", "Community 3" };
var result = activities.Where(x => x.Community, @in: communities);

Linq rules!!

Categories: C# Tags: , , , ,

Why they don’t want us to do unit testing over Sharepoint?

August 10, 2010 2 comments

I don’t understand what’s happening. Besides the aberrant idea of havig such a monster without a way to mock it by design (I know, TypeMock supports Sharepoint isolation, but it’s not by design and it’s not free), they just disabled the possibility of doing unit tests over it.

Basically, it seems like Sharepoint runs in .NET framework 3.5 and you can’t change the target of a Visual Studio Test Project to 3.5, it has to be 4.0. So, you are not able to test it.

One more time, I’m moving to NUnit.