C#: Query active directory to get a user’s roles

There are a few different ways to get the roles/groups of user from Active Directory. Here are 3 different ways to do it.

The first way to do it is to use UserPrincipal.FindByIdentity:

private static IEnumerable<string> GetGroupsFindByIdentity(string username, string domainname, string container)
{
	var results = new List<string>();
	using (var context = new PrincipalContext(ContextType.Domain, domainname, container))
	{
		try
		{
			UserPrincipal p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
			if (p != null)
			{
				var groups = p.GetGroups();
				foreach (var group in groups)
				{
					try
					{
						results.Add(@group.Name);
					}
					catch (Exception ex)
					{
					}
				}
			}
		}
		catch (Exception ex)
		{
			throw new ApplicationException("Unable to query Active Directory.", ex);
		}
	}

	return results;
}

You can then print the roles using:

var groups = GetGroupsFindByIdentity("benohead", "aw001.amazingweb.de", "DC=aw001,DC=amazingweb,DC=de");
foreach (var group in groups)
{
	Console.WriteLine(group);
}

Another way to do it is to use a DirectorySearcher and fetching DirectoryEntries:

private static IEnumerable<string> GetGroupsDirectorySearcher(string username, string container)
{
	var searcher =
		new DirectorySearcher(new DirectoryEntry("LDAP://" + container))
		{
			Filter = String.Format("(&(objectClass=user)(samaccountname={0}))", username)
		};
	searcher.PropertiesToLoad.Add("MemberOf");

	var directoryEntriesFound = searcher.FindAll()
		.Cast<SearchResult>()
		.Select(result => result.GetDirectoryEntry());

	foreach (DirectoryEntry entry in directoryEntriesFound)
		foreach (object obj in ((object[]) entry.Properties["MemberOf"].Value))
		{
			string group = Regex.Replace(obj.ToString(), @"^CN=(.*?)(?<!\\),.*", "$1");
			yield return group;
		}
}

The regular expression is required in order to extract the CN part of the returned string.

var groups = GetGroupsDirectorySearcher("benohead", "DC=aw005,DC=amazingweb,DC=de");
foreach (var group in groups)
{
	Console.WriteLine(group);
}

The third way to do it is to use a WindowsIdentity:

private static IEnumerable<string> GetGroupsWindowsIdentity(string userName)
{
	var results = new List<string>();
	var wi = new WindowsIdentity(userName);

	if (wi.Groups != null)
	{
		foreach (var group in wi.Groups)
		{
			try
			{
				results.Add(@group.Translate(typeof (NTAccount)).ToString());
			}
			catch (Exception ex)
			{
				throw new ApplicationException("Unable to query Active Directory.", ex);
			}
		}
	}
	return results;
}

You can then print the roles using:

var groups = GetGroupsWindowsIdentity("benohead");
foreach (var group in groups)
{
	Console.WriteLine(group);
}

You might notice that this last option seems to return more groups than the other two options. I’m not yet sure why. I’ve tested it with multiple users and saw that it does return different groups but for some reason, it also returns groups not returned by any other method. So for now I’ll rather stick to the first or second method.

Working with Enums in C#

Just wanted to share a helper class I’m using in some projects to make it easier to work with enums.

    public static class EnumHelpers
    {
        private const string MustBeAnEnumeratedType = @"T must be an enumerated type";

        public static T ToEnum<T>(this string s) where T : struct, IConvertible
        {
            if (!typeof (T).IsEnum) throw new ArgumentException(MustBeAnEnumeratedType);
            T @enum;
            Enum.TryParse(s, out @enum);
            return @enum;
        }

        public static T ToEnum<T>(this int i) where T : struct, IConvertible
        {
            if (!typeof (T).IsEnum) throw new ArgumentException(MustBeAnEnumeratedType);
            return (T) Enum.ToObject(typeof (T), i);
        }

        public static T[] ToEnum<T>(this int[] value) where T : struct, IConvertible
        {
            if (!typeof (T).IsEnum) throw new ArgumentException(MustBeAnEnumeratedType);
            var result = new T[value.Length];
            for (int i = 0; i < value.Length; i++)
                result[i] = value[i].ToEnum<T>();
            return result;
        }

        public static T[] ToEnum<T>(this string[] value) where T : struct, IConvertible
        {
            if (!typeof (T).IsEnum) throw new ArgumentException(MustBeAnEnumeratedType);
            var result = new T[value.Length];
            for (int i = 0; i < value.Length; i++)
                result[i] = value[i].ToEnum<T>();
            return result;
        }

        public static IEnumerable<T> ToEnumFlags<T>(this int i) where T : struct, IConvertible
        {
            if (!typeof (T).IsEnum) throw new ArgumentException(MustBeAnEnumeratedType);
            return
                (from flagIterator in Enum.GetValues(typeof (T)).Cast<int>()
                    where (i & flagIterator) != 0
                    select ToEnum<T>(flagIterator));
        }

        public static bool CheckFlag<T>(this Enum value, T flag) where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum) throw new ArgumentException(MustBeAnEnumeratedType);
            return (Convert.ToInt32(value, CultureInfo.InvariantCulture) & Convert.ToInt32(flag, CultureInfo.InvariantCulture)) != 0;
        }

        public static IDictionary<string, T> EnumToDictionary<T>() where T : struct, IConvertible
        {
            if (!typeof (T).IsEnum) throw new ArgumentException(MustBeAnEnumeratedType);
            IDictionary<string, T> list = new Dictionary<string, T>();
            Enum.GetNames(typeof (T)).ToList().ForEach(name => list.Add(name, name.ToEnum<T>()));
            return list;
        }

The first ToEnum extension allows you to write something like this:

"Value1".ToEnum<MyEnum>()

It adds a ToEnum method to the string class in order to convert a string to an enum value.

The second ToEnum extension does the same but with ints e.g.:

0.ToEnum<MyEnum>()

The third ToEnum extension is similar but extends int arrays to return a collection of enum values e.g.:

new[] {1, 0}.ToEnum<MyEnum>()

The forth ToEnum extension does the same but with string arrays e.g.:

new[] {"Value2", "Value1"}.ToEnum<MyEnum>()

The ToEnumFlags extension returns a list of enum values when working with flags e.g.:

13.ToEnumFlags<MyEnum2>().Select(e => e.ToString()).Aggregate((e, f) => (e + " " + f))

The EnumToDictionary method returns a dictionary with the enum item name as key and values e.g.:

EnumHelpers.EnumToDictionary<MyEnum>()["Value2"]

The CheckFlag extension converts checks whether an enum flag is set e.g.:

(MyEnum2.Flag1 | MyEnum2.Flag4).CheckFlag(MyEnum2.Flag4)

To test this you can use the following:

    internal enum MyEnum
    {
        Value1,
        Value2,
    }

    [Flags]
    internal enum MyEnum2
    {
        Flag1 = 1,
        Flag2 = 2,
        Flag3 = 4,
        Flag4 = 8,
    }

    public static class MainClass
    {
        public static void Main()
        {
            Console.WriteLine("1) {0}", (int) "Value1".ToEnum<MyEnum>());
            Console.WriteLine("2) {0}", 0.ToEnum<MyEnum>());
            Console.WriteLine("3) {0}", new[] {1, 0}.ToEnum<MyEnum>());
            Console.WriteLine("4) {0}", new[] {"Value2", "Value1"}.ToEnum<MyEnum>());
            Console.WriteLine("5) {0}", 13.ToEnumFlags<MyEnum2>().Select(e => e.ToString()).Aggregate((e, f) => (e + " " + f)));
            Console.WriteLine("6) {0}", (int) EnumHelpers.EnumToDictionary<MyEnum>()["Value2"]);    
            Console.WriteLine("7) {0}", (MyEnum2.Flag1 | MyEnum2.Flag4).CheckFlag(MyEnum2.Flag4));
            Console.WriteLine("8) {0}", (MyEnum2.Flag1 | MyEnum2.Flag4).CheckFlag(MyEnum2.Flag3));
        }
    }

which will output:

1) 0
2) Value1
3) Playground.MyEnum[]
4) Playground.MyEnum[]
5) Flag1 Flag3 Flag4
6) 1
7) True
8) False

I guess most methods are pretty basic but sometimes it’s easier to just have a helper class and not have to think about how to solve the problem again and again (even though it’s not a very complex problem)…

Three options to dynamically execute C# code

I’ve been working in the past few months on a project where users can write C# to query data from a model. This means that I needed to dynamically execute C# code entered by the user.

There are basically three options for compiling and executing C# code dynamically:

  • Using the CodeDOM compiler
  • Using the Mono Compiler Service
  • Using Roslyn

Using the CodeDOM (Code Document Object Model), you can dynamically compile source code into a binary assembly. The steps involved are:

  1. Create an instance of the CSharpCodeProvider
  2. Compile an assembly from source code
  3. Get the type from the assembly
  4. Instantiate this type
  5. Get a reference to the method
  6. Call the method with the appropriate parameters

Here’s an example how to implement steps 1 and 2:

        private static Assembly CompileSourceCodeDom(string sourceCode)
        {
            CodeDomProvider cpd = new CSharpCodeProvider();
            var cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            cp.GenerateExecutable = false;
            CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);

            return cr.CompiledAssembly;
        }

The other steps can then be implemented like this:

        private static void ExecuteFromAssembly(Assembly assembly)
        {
            Type fooType = assembly.GetType("Foo");
            MethodInfo printMethod = fooType.GetMethod("Print");
            object foo = assembly.CreateInstance("Foo");
            printMethod.Invoke(foo, BindingFlags.InvokeMethod, null, null, CultureInfo.CurrentCulture);
        }

Since you can only compile full assemblies with the CodeDOM, this means that:

  • You cannot execute snippets of code, you need a full class definition
  • Every time you compile some code a new assembly will be created and loaded

Using the Mono Compiler Service, you can also execute code dynamically. The big difference here (except the fact that you need a few other assemblies) is that MCS allows you to evaluate code with needing to define a class with methods so instead of this:

class Foo
{
    public void Print()
    {
        System.Console.WriteLine(""Hello benohead.com !"");
    }
}

You could just evaluate the following:

System.Console.WriteLine(""Hello benohead.com !"");

This is of course very useful when dynamically executing pieces of code provided by a user.

Here is a minimal implementation using MCS:

private static void ExecuteMono(string fooSource)
{
    new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter())).Run(fooSource);
}

If you need a return value, you can use the Evaluate method instead of the Run method.

One other advantage of MCS is that it doesn’t write an assembly to disk and then loads it. So when you evaluate 1000 expressions, you don’t end up loading 1000 new assemblies.

The last and latest option to handle dynamic C# code execution is to use the .NET Compiler Platform Roslyn. Roslyn is a set of open-source compilers and code analysis APIs for C# and Visual Basic.NET.

Dynamically executing code with Roslyn is actually pretty similar to the way you would do it with the CodeDOM. You have to create an assembly, get an instance of the class and execute the method using reflection.

Here is an example how to create the assembly:

        private static Assembly CompileSourceRoslyn(string fooSource)
        {
            using (var ms = new MemoryStream())
            {
                string assemblyFileName = "gen" + Guid.NewGuid().ToString().Replace("-", "") + ".dll";

                CSharpCompilation compilation = CSharpCompilation.Create(assemblyFileName,
                    new[] {CSharpSyntaxTree.ParseText(fooSource)},
                    new[]
                    {
                        new MetadataFileReference(typeof (object).Assembly.Location)
                    },
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                    );

                compilation.Emit(ms);
                Assembly assembly = Assembly.Load(ms.GetBuffer());
                return assembly;
            }
        }

Note that I do not handle any error scenarios here (or in the other pieces of code in this post) but to use it in a production system, you’d of course need to do it.

As with CodeDOM, a new assembly is created every time code is dynamically compiled. The difference is that you need to create a temporary assembly name yourself.

Executing the code from the assembly is then the same as with the CodeDOM.

Now let’s look at it from a performance perspective. Running the dynamic execution 100 times in a row for using the three methods, I got the following results:

roslyn: assemblies loaded=114
roslyn: time=2049,2049 milliseconds

codedom: assemblies loaded=100
codedom: 7512,7512 milliseconds

mono: assemblies loaded=6
mono: time=15163,5162 milliseconds

Running it multiple times has shown that the numbers are pretty stable.

So you can see that with Roslyn and CodeDOM, the number of assemblies loaded is increasing with the number of runs. The 14 more assemblies with Roslyn as well as the 6 assemblies with MCS are due to the fact that the assembly required by the compilers themselves are not loaded when the program is started but when they are used.

From a number of loaded assemblies point of view, MCS is a clear winner. It doesn’t need to load any assemblies except the assemblies required by the compiler.

From a performance perspective, Roslyn is quite impressive being more than 3 times faster than the CodeDOM and more than 7 times faster than MCS.

The main disadvantage of Roslyn versus CodeDOM is that Roslyn is not yet production ready and is pretty much work in progress. Once Roslyn is more feature complete and production ready, there will be no reasons to further use CodeDOM for dynamic code execution.

Although it’s the slowest solution, MCS is the one which scales better so if you have to execute a non-finite number of dynamic code, it’s the way to go. Also if you are just executing snippets of code and not whole classes, it makes your life easier.

 

Orchard CMS: Exporting and Importing custom content types

Orchard CMS provides a nice module to import and export content items. You just need to enable the module called “Import Export”. This will add a menu item in the left navigation sidebar. There you can export all content items of given types. This will create an XML file containing all exported content items. It also provides an import function where you can choose an exported XML file and have it imported.

In Orchard CMS cloning is using the same infrastructure as import/export. So please first read my previous post about cloning content items in Orchard CMS.

Once you’ve added the Importing and the Exporting methods to your driver, you might see that the export file looks like this:

<!--Exported from Orchard-->
<Orchard>
  <Recipe>
    <Name>Generated by Orchard.ImportExport</Name>
    <Author>admin</Author>
    <ExportUtc>2014-04-19T14:28:24.7757008Z</ExportUtc>
  </Recipe>
  <Data>
    <MyCustomType Id="" Status="Draft">
      <CommonPart Owner="/User.UserName=admin" CreatedUtc="2014-04-17T09:23:30Z" ModifiedUtc="2014-04-17T09:23:30Z" />
      <MyCustomTypePart Name="My name is..." />
    </MyCustomType>
  </Data>
</Orchard>

And when you import this, nothing happens (and the log files contain no error). If it is the case, you have the same problem I had and there is an easy fix.

The problem is that the export file contains an empty ID for all content items. Actually you should have an ID in there starting with /Identifier= and followed by a unique ID. In order to fix it, you need to add an IdentityPart to your content type. Here’s what the Orchard documentation says about the IdentityPart:

The Identity part is useful to provide a unique identity to a content item that doesn’t have a natural one. For example, pages are naturally identified by their relative URL within the site, or users by their user name, but widgets have no such natural identity. In order to enable importing and exporting of those items, the identity part can be added. It creates GUIDs that are used as a unique identity that can reliably be exchanged between instances of Orchard.

So you just need to add this part to your content item. You can either add it in the Admin UI or add an Update method to your Migrations.cs file e.g.:

[UsedImplicitly]
public int UpdateFrom19()
{
	ContentDefinitionManager.AlterTypeDefinition("MyCustomType", cfg => cfg.WithPart("IdentityPart"));

	return 20;
}

Now the export file will look like this:

<!--Exported from Orchard-->
<Orchard>
    <Recipe>
        <Name>Generated by Orchard.ImportExport</Name>
        <Author>admin</Author>
        <ExportUtc>2014-04-19T14:47:34.3426219Z</ExportUtc>
    </Recipe>
    <Data>
        <MyCustomType Id="/Identifier=defe165123124b20a7fcb35e66873fbf" Status="Draft"> 
            <IdentityPart Identifier="defe165123124b20a7fcb35e66873fbf" /> 
            <CommonPart Owner="/User.UserName=admin" CreatedUtc="2014-04-17T09:23:30Z" ModifiedUtc="2014-04-17T09:23:30Z" />
            <MyCustomTypePart Name="My name is..." />
        </MyCustomType>
    </Data>
</Orchard>

 

And the import will work…

 

 

Orchard CMS: Cloning custom content items

When listing instances of a custom content item type, you will see that next to the Preview, Publish, Edit and Delete operations, there is also a Clone operation.
clone operation
When using it on a custom content item, you will also see that it’s merely creating an empty content item, not taking over any of the actual data.
Unfortunately, in all tutorials about custom content items I have read, I haven’t seen anything pointing to how to make Orchard actually create a real copy of the selected content item.

It’s actually pretty simple. The ContentPartDriver class your driver is extending, contains a bunch of methods for importing and exporting:

protected virtual void Importing(TContent part, ImportContentContext context) {}
protected virtual void Imported(TContent part, ImportContentContext context) {}
protected virtual void Exporting(TContent part, ExportContentContext context) {}
protected virtual void Exported(TContent part, ExportContentContext context) {}

All you have to do is override the methods Importing and Exporting in your driver:

protected override void Importing(MyCustomQueryPart part, ImportContentContext context)
{
}

protected override void Exporting(MyCustomQueryPart part, ExportContentContext context)
{
}

Exporting will be called when the content part is exported. You have to map the properties from the content part to XML attributes.
Importing will be called when importing a content part. You have to map back the XML attributes to content part properties.

For example:

protected override void Importing(MyCustomQueryPart part, ImportContentContext context)
{
	string name = context.Attribute(part.PartDefinition.Name, "Name");
	if (name != null)
	{
		part.Name = name;
	}
}

protected override void Exporting(MyCustomQueryPart part, ExportContentContext context)
{
	context.Element(part.PartDefinition.Name).SetAttributeValue("Name", part.Name);
}

Note that if your properties are not strings you’ll have to convert them in the importing using e.g. bool.Parse or int.Parse e.g.:

protected override void Importing(MyCustomQueryPart part, ImportContentContext context)
{
	part.IsOk= bool.Parse(context.Attribute(part.PartDefinition.Name, "IsOk"));
}

In the exporter, the conversion to strings is done automatically using ToString().

That’s it. Now your content part can be imported and exported and it can be cloned as well !

Now if one of the properties is actually a reference to a different content part, you’ll have to map in the importer the id to a content part e.g.:

int referenceId = int.Parse(context.Attribute(part.PartDefinition.Name, "Reference"));
part.Reference = _otherContentService.GetOtherContentPart(referenceId);

And you of course need to inject the service in the constructor of your driver:

private readonly ILinqFileService _fileService;

public MyCustomDriver(IOtherContentService otherContentService)
{
	_otherContentService = otherContentService;
}

And define GetOtherContentPart in IOtherContentService and implement it in the service itself e.g.:

public ContentItem GetOtherContentPart(int referenceId)
{
	return _contentManager.Get(referenceId, VersionOptions.AllVersions);
}

_contentManager is also injected in the Service by defining it in the constructor:

private readonly IContentManager _contentManager;

public OtherContentService(IContentManager contentManager)
{
	_contentManager = contentManager;
}

It’s a little bit more complex but I guess you’ll need the GetOtherContentPart method for other purposes anyway (I already had it in there).

So the conclusion is that Orchard provides pretty much everything you need in a nicely designed way but unfortunately the lack of documentation makes it very difficult to figure out how to use it. In such cases (as always with Orchard) your best starting point is the source code of existing modules and search engines (although Orchard being relatively new, you will not find everything in search engines).

C#: Safe navigation avoiding NULLs

Groovy has a safe navigation operator “?.” which works just like the dot operator except that it returns nulls instead of throwing NullPointerExceptions when the object on the left is null.

Let’s see you want to do the following:

a.b.c;

But a could be null or a.b could be null, then you have to write something like this:

a == null ? null : a.b == null ? null : a.b.c;

This is getting much longer. If you actually allow your users to write code to extend your functionality, handling those nulls really becomes a pain. But in Groovy, you could just use the safe navigation operator to write the following:

a?.b?.c;

A little bit shorter than the one before… Well, now it’s great if you’re programming in Groovy. If you’re programming in C#, it just makes you wish you could use it…

Let’s see what can be done to get something similar (of course we can’t make it as compact as the Groovy syntax).

Let’s first start without checking for nulls:

using System;

namespace Playground
{
    public static class NullTest
    {
        public static void Main()
        {
            var a5 = new ClassA {B = new ClassB {C = new ClassC {S = "Hello"}}};

            Console.WriteLine(a5.B.C.S.Length);
        }
    }

    internal class ClassA
    {
        internal ClassB B { get; set; }
    }

    internal class ClassB
    {
        internal ClassC C { get; set; }
    }

    internal class ClassC
    {
        internal string S { get; set; }
    }
}

If instead of having a5 you have a4:

var a4 = new ClassA {B = new ClassB {C = new ClassC()}};

You’ll get a NullReferenceException because the string S is not initialized:

System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Playground
StackTrace:
at Playground.NullTest.Main() in d:\Software\Visual Studio 2008\Projects\Playground\Playground\Program.cs:line 11
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

And instead of a4 you could have any of those:

ClassA a1 = null;
var a2 = new ClassA();
var a3 = new ClassA {B = new ClassB()};

And you’d also get a NullReferenceException. So you need to end up writing something like:

a4 == null ? 0 : a4.B == null ? 0 : a4.B.C == null ? 0 : a4.B.C.S == null ? 0 : a4.B.C.S.Length

So what do we need to make it better ? First you need some kind of method which allows you to say return the property B of a4 is a4 is not null otherwise return something. Right now we’ll say that it’s fine to return null if a4 is null.

Since we want it to work for all types but do not want to end up loosing all type information because we handle everything as an object, we need to use some generics. So our method would look like:

TOut NullSafe<TIn, TOut>() {}

Since I’d rather have:

a4.NullSafe(...)

than:

NullSafe(a4, ...)

let’s make it an extension method:

    internal static class Nullify
    {
        public static TOut NullSafe<TIn, TOut>(this TIn obj, ...)
        {
        }
    }

First we need to check whether obj is null. If we just compare it with null, you might see that you get a warning saying that it’s a possible compare of value type with null. To do it properly, you will need to check it this way:

if (EqualityComparer<TIn>.Default.Equals(obj, default(TIn)))

If it is true, just return the default for TOut otherwise we’ll return a4.B.

Now, if you do not only want to support properties like a4.B but also indexers, method calls, operators or other kinds of expressions, it’s better to provide a lambda expression like:

a => a.B

This gives you maximum flexibility. It then looks like this:

    internal static class Nullify
    {
        public static TOut NullSafe<TIn, TOut>(this TIn obj, Func<TIn, TOut> memberAction)
        {
            return (EqualityComparer<TIn>.Default.Equals(obj, default(TIn))) ? default(TOut) : memberAction(obj);
        }
    }

And you can use it like this:

a4.NullSafe(a => a.B)

So instead of:

a4 == null ? 0 : a4.B == null ? 0 : a4.B.C == null ? 0 : a4.B.C.S == null ? 0 : a4.B.C.S.Length

you’d have:

a4.NullSafe(a => a.B).NullSafe(b => b.C).NullSafe(c => c.S).NullSafe(s => s.Length)

It’s not that much shorter but it does look less complex.

If instead of Length you had something which returns an object which could be null and instead of null you want to return some other default value, you can extend the class like this:

    internal static class Nullify
    {
        public static TOut NullSafe<TIn, TOut>(this TIn obj, Func<TIn, TOut> memberAction)
        {
            return (EqualityComparer<TIn>.Default.Equals(obj, default(TIn))) ? default(TOut) : memberAction(obj);
        }

        public static TIn NullDefault<TIn>(this TIn obj, TIn defaultValue)
        {
            return EqualityComparer<TIn>.Default.Equals(obj, default(TIn)) ? defaultValue : obj;
        }
    }

You then just need to add a call to NullDefault in the end e.g.:

xxx.NullDefault("not set");

If xxx is an expression return a string in the end.

NHibernate: NullReferenceException on bitwise operations in the where clause

When performing a bitwise operations in the where clause of a LINQ query using the NHibernate LINQ provider e.g.:

from o in SomeObjects where (o.SomeFlags & myBitMask) != myBitMask

you might geht the following exception:

System.NullReferenceException: Object reference not set to an instance of an object.
   at NHibernate.Criterion.SubqueryExpression..ctor(String op, String quantifier, DetachedCriteria dc, Boolean prefixOp) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Criterion\SubqueryExpression.cs:line 30
   at NHibernate.Criterion.Subqueries.Eq(Object value, DetachedCriteria dc) in c:\Users\sebros\Documents\My Projects\nhibernate-core\src\NHibernate\Criterion\Subqueries.cs:line 130
   at NHibernate.Linq.Visitors.WhereArgumentsVisitor.VisitBinaryCriterionExpression(BinaryExpression expr)
   at NHibernate.Linq.Visitors.WhereArgumentsVisitor.VisitBinary(BinaryExpression expr)
   at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp)
   at NHibernate.Linq.Visitors.WhereArgumentsVisitor.VisitOrElseExpression(BinaryExpression expr)
   at NHibernate.Linq.Visitors.WhereArgumentsVisitor.VisitBinary(BinaryExpression expr)
   at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp)
   at NHibernate.Linq.Visitors.WhereArgumentsVisitor.VisitAndAlsoExpression(BinaryExpression expr)
   at NHibernate.Linq.Visitors.WhereArgumentsVisitor.VisitBinary(BinaryExpression expr)
   at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp)
   at NHibernate.Linq.Visitors.ExpressionVisitor.VisitLambda(LambdaExpression lambda)
   at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp)
   at NHibernate.Linq.Visitors.WhereArgumentsVisitor.VisitUnary(UnaryExpression expr)
   at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp)
   at NHibernate.Linq.Visitors.RootVisitor.HandleWhereCall(MethodCallExpression call)
   at NHibernate.Linq.Visitors.RootVisitor.VisitMethodCall(MethodCallExpression expr)
   at NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp)
   at NHibernate.Linq.Visitors.NHibernateQueryTranslator.Translate(Expression expression, QueryOptions queryOptions)

I actually even got this exception with a much simpler query:

query
	.Where(
		q =>
			(q.QueryType == null || q.QueryType != xxx) &&
			(q.Variables == null || q.Variables.Trim().Length == 0));

This is due to a bug in NHibernate which seems to be solved in the newer versions of NHibernate. Unfortunately, since I’m using Orchard CMS moving to a newer version of NHibernate is not an option. But the solution is quite simple: You need to convert the query object to a list first and then perform the Where operation. Like this you basically do not rely on any NHibernate class and can workaround the bug:

IEnumerable<LinqQueryPart> query = zzz.List<LinqQueryPart>();
return
	query
		.Where(
			q =>
				(q.QueryType == null || q.QueryType != xxx) &&
				(q.Variables == null || q.Variables.Trim().Length == 0));

C#: Get the element type of an enumerable through reflection

In a project, I was getting an object and if it was an IEnumerable<T> I had to display a table with the properties of the object as columns. So I needed to figure out what was the generic type of this enumerable.

Using reflection, you can get the type of any object using:

Type type = o.GetType();

Let’s try this for a few enumerables:

IEnumerable<string> enumerable1 = new List<string> {"test"};
IEnumerable<object> enumerable2 = new List<string> {"test"};
IEnumerable<object> enumerable3 = new List<object> {"test"};

Console.WriteLine(enumerable1.GetType());
Console.WriteLine(enumerable2.GetType());
Console.WriteLine(enumerable3.GetType());

And see what we get:

System.Collections.Generic.List`1[System.String]
System.Collections.Generic.List`1[System.String]
System.Collections.Generic.List`1[System.Object]

So you get in the brackets the generic type. We just need to find how to get to this info. There ‘s a method called Type.GetGenericArguments(). MSDN says:

Returns an array of Type objects that represent the type arguments of a generic type or the type parameters of a generic type definition.

Since we are handling IEnumerable types, in our case the returned array will contain a single type which is what we’re looking for:

IEnumerable<string> enumerable1 = new List<string> {"test"};
IEnumerable<object> enumerable2 = new List<string> {"test"};
IEnumerable<object> enumerable3 = new List<object> {"test"};

Console.WriteLine(enumerable1.GetType().GetGenericArguments().FirstOrDefault());
Console.WriteLine(enumerable2.GetType().GetGenericArguments().FirstOrDefault());
Console.WriteLine(enumerable3.GetType().GetGenericArguments().FirstOrDefault());

And there it is:

System.String
System.String
System.Object

So that was pretty simple ! Unfortunately in some cases it doesn’t return what I want to get. Let’s assume you have such a class:

class MyEnumerable<T2, T> : List<T>
{
}

I know this particular class doesn’t make sense but it’s just to keep things simple.

If you run the following code:

IEnumerable<string> enumerable1 = new MyEnumerable<int, string> { "test" };
IEnumerable<object> enumerable2 = new MyEnumerable<int, string> { "test" };
IEnumerable<object> enumerable3 = new MyEnumerable<int, object> { "test" };

Console.WriteLine(enumerable1.GetType().GetGenericArguments().FirstOrDefault());
Console.WriteLine(enumerable2.GetType().GetGenericArguments().FirstOrDefault());
Console.WriteLine(enumerable3.GetType().GetGenericArguments().FirstOrDefault());

You’ll get:

System.Int32
System.Int32
System.Int32

Which is not what I need to get to be able to display my table… What I need is not the first generic argument type for the IEnumerable interface it implements. In order to get to this information, we’ll need to first get the corresponding interface type before using GetGenericArguments. You can get a list of interfaces implemented by a given type like this:

Type[] interfaces = enumerable.GetType().GetInterfaces();

You then get an array of interfaces. Once you have it you need to find the IEnumerable generic interface. In case of our class extending List, the array will contain:

  • IList`1
  • ICollection`1
  • IEnumerable`1
  • IEnumerable
  • IList
  • ICollection
  • IReadOnlyList`1
  • IReadOnlyCollection`1

As you can see IEnumerable is in there twice. This is because both the IEnumerable Interface from System.Collections and the IEnumerable(T) Interface from System.Collections.Generic are implemented. In our case, we are interested in the latter. So let’s fetch it with LINQ. We can identify this with the following criteria:

  • IsGenericType == true
  • GetGenericTypeDefinition() == typeof (IEnumerable<>)

So the code to get the element type is:

private static Type GetElementTypeOfEnumerable(object o)
{
	var enumerable = o as IEnumerable;
	// if it's not an enumerable why do you call this method all ?
	if (enumerable == null)
		return null;

	Type[] interfaces = enumerable.GetType().GetInterfaces();

	return (from i in interfaces
		where i.IsGenericType && i.GetGenericTypeDefinition() == typeof (IEnumerable<>)
		select i.GetGenericArguments()[0]).FirstOrDefault();
}

And the following:

IEnumerable<string> enumerable1 = new MyEnumerable<int, string> { "test" };
IEnumerable<object> enumerable2 = new MyEnumerable<int, string> { "test" };
IEnumerable<object> enumerable3 = new MyEnumerable<int, object> { "test" };

Console.WriteLine(GetElementTypeOfEnumerable(enumerable1));
Console.WriteLine(GetElementTypeOfEnumerable(enumerable2));
Console.WriteLine(GetElementTypeOfEnumerable(enumerable3));

Returns:

System.String
System.String
System.Object

Now the only remaining problem is that if I get enumerable3 as input, I’ll only see that it’s containing objects and will no be able to show the proper columns because I do not get the information that it’s actually containing a specific type. Of course it’s always better if the collections you get are not lists of objects but list of a specific type but in some cases you don’t have a choice.

One way to workaround this is to peek at the first element in the list and see what’s in there (but only if the specific type cannot be determined by the method above). Of course, if the list contains objects of different types, this will return some wrong information. But in my project I knew that all objects in the enumerable had the same type, so it wasn’t a problem.

So let’s create a second method doing exactly that:

private static Type GetElementTypeOfEnumerable2(object o)
{
	var enumerable = o as IEnumerable;
	// if it's not an enumerable why do you call this method all ?
	if (enumerable == null)
		return null;

	Type[] interfaces = enumerable.GetType().GetInterfaces();
	Type elementType = (from i in interfaces
		where i.IsGenericType && i.GetGenericTypeDefinition() == typeof (IEnumerable<>)
		select i.GetGenericArguments()[0]).FirstOrDefault();

	//peek at the first element in the list if you couldn't determine the element type
	if (elementType == null || elementType == typeof (object))
	{
		object firstElement = enumerable.Cast<object>().FirstOrDefault();
		if (firstElement != null)
			elementType = firstElement.GetType();
	}
	return elementType;
}

Now executing the following:

IEnumerable<string> enumerable1 = new MyEnumerable<int, string> { "test" };
IEnumerable<object> enumerable2 = new MyEnumerable<int, string> { "test" };
IEnumerable<object> enumerable3 = new MyEnumerable<int, object> { "test" };

Console.WriteLine(GetElementTypeOfEnumerable2(enumerable1));
Console.WriteLine(GetElementTypeOfEnumerable2(enumerable2));
Console.WriteLine(GetElementTypeOfEnumerable2(enumerable3));

Returns:

System.String
System.String
System.String

Which is exactly what I wanted to see !

ASP.NET MVC: Uploading a File

In a project I’m working on, I needed to implement a file upload in ASP.NET MVC. There are basically two ways to implement it:

  1. Handle the upload of the file in the view itself.
  2. Handle it in the controller.

The code for both of them is pretty similar.

First you need to have a file input in your view:

@Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data"})
{
	<input type="file" name="uploadedFile" value="Browse">
	<input id="uploadbutton" type="submit" value="Upload">	
}

If you want to handle it all in the view itself, you can also use null as action and controller name and add the following at the beginning of your view:

@{
    if (IsPost)
    {
        HttpPostedFileBase uploadedFile = Request.Files[0];
        if (uploadedFile != null)
        {
            string fileName = Path.GetFileName(uploadedFile.FileName);
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                string directory = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\UploadedFiles";
                string fileSavePath = directory + "\\" + fileName;
                Directory.CreateDirectory(directory);
                uploadedFile.SaveAs(fileSavePath);
            }
        }
    }
}

In case you want to handle it in the controller, you should provide the right controller name and action name e.g. Index:

@Html.BeginForm("Index", "File", FormMethod.Post, new { enctype = "multipart/form-data"})

Then in your controller create an Index method which will handle the file upload:

public class FileController : Controller
{
    // GET
    public ActionResult Index()
    {
        return View();
    }

    // POST
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase uploadedFile)
    {
        if (uploadedFile != null)
        {
            string fileName = Path.GetFileName(uploadedFile.FileName);
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                string directory = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\UploadedFiles";
                string fileSavePath = directory + "\\" + fileName;
                Directory.CreateDirectory(directory);
                uploadedFile.SaveAs(fileSavePath);
            }
        }
        return RedirectToAction("Index");        
    }
}

That’s it ! If you want to handle multiple file uploads e.g. to allow a user to upload a resume, a motivation letter, a degree… it’s damned easy.

In case you went for the solution in the view, you just have to iterate through Request.Files.

If you went for the solution in the controller, just change the signature of your action to take an enumerable instead of a single HttpPostedFileBase:

public ActionResult Index(IEnumerable<HttpPostedFileBase> uploadedFile)

Then iterate through the enumeration and save each file.

C#: A circular reference was detected while serializing an object

In a project, I had a tree of objects, each node of the tree having some attributes, a list of children and also in some cases a reference to some other object in the tree. I needed to serialize it in JSON format and send it to a JavaScript client.

In order to serialize it I used the JavaScriptSerializer. It basically serializes in a recursive way all public properties of the provided object. Here a short example:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace Playground
{
    public static class JsonTest
    {

        class MyObject
        {
            public MyObject()
            {
                Children = new List<MyObject>();
            }

            public string Name { get; set; }
            public Guid Guid { get; set; }
            public IList<MyObject> Children { get; set; }
            public MyObject BestFriend { get; set; }
        }

        public static void Main()
        {
            var root = new MyObject {Name = "Root", Guid = Guid.NewGuid()};
            var object1 = new MyObject { Name = "Child1", Guid = Guid.NewGuid() };
            var object2 = new MyObject { Name = "Child2", Guid = Guid.NewGuid() };
            var object3 = new MyObject { Name = "Child3", Guid = Guid.NewGuid() };
            var object4 = new MyObject { Name = "Child4", Guid = Guid.NewGuid() };
            var object5 = new MyObject { Name = "Child5", Guid = Guid.NewGuid() };
            var object6 = new MyObject { Name = "Child6", Guid = Guid.NewGuid() };

            object1.Children.Add(object3);
            object1.Children.Add(object4);

            object2.Children.Add(object5);
            object2.Children.Add(object6);

            root.Children.Add(object1);
            root.Children.Add(object2);

            string s = new JavaScriptSerializer().Serialize(root);
            Console.WriteLine(s);
        }
    }
}

This all works fine until you add a reference to a node further up in the tree to the BestFriend property:

public static void Main()
{
	var root = new MyObject {Name = "Root", Guid = Guid.NewGuid()};
	var object1 = new MyObject { Name = "Child1", Guid = Guid.NewGuid() };
	var object2 = new MyObject { Name = "Child2", Guid = Guid.NewGuid() };
	var object3 = new MyObject { Name = "Child3", Guid = Guid.NewGuid() };
	var object4 = new MyObject { Name = "Child4", Guid = Guid.NewGuid() };
	var object5 = new MyObject { Name = "Child5", Guid = Guid.NewGuid() };
	var object6 = new MyObject { Name = "Child6", Guid = Guid.NewGuid() };

	object1.Children.Add(object3);
	object1.Children.Add(object4);

	object2.Children.Add(object5);
	object2.Children.Add(object6);

	root.Children.Add(object1);
	root.Children.Add(object2);
	
	object3.BestFriend = object1;

	string s = new JavaScriptSerializer().Serialize(root);
	Console.WriteLine(s);
}

When running it, you will get a InvalidOperationException with the following message:

A circular reference was detected while serializing an object of type ‘Playground.JsonTest+MyObject’.

The reason is that while walking through the tree we came to object3 and followed the reference back to object1 which would then lead us back to object3 and so on. So the solution is would be not to follow the BestFriend reference while serializing. In my case I didn’t even need to keep this reference in the JSON structure.

In order to do it you need to create a new object for each MyObject containing the properties we do need in the JSON structure and not containing the BestFriend property e.g.:

new {
	Name = o.Name,
	Guid = o.Guid,
	Children = o.Children
};

The problem is that if you use the Children property you’ll be back with the BestFriend problem. So we need to convert the MyObject to a new type and in this new type still have the children but not as MyObjects but as the new type. So basically we need to recursively convert all MyObjects.

Sounds like a job for Linq. Unfortunately Linq doesn’t provide any extension for working in such a recursive way. If you knew you had only three levels like in our example above you could do something like this:

new {
	Name = o.Name,
	Guid = o.Guid,
	Children = o.Children.Select(new {
		Name = o.Name,
		Guid = o.Guid,
		Children = o.Children.Select(new {
			Name = o.Name,
			Guid = o.Guid
		}
	}
};

But if the depth of the tree is not limited, you cannot do it this way. For something like this, you need to have a recursive method or function converting the nodes. Since in my case I couldn’t use a recursive methods (because the code was entered by a user and was dynamically compiled in a method), I had to go for a method delegate and a lambda expression. Since I couldn’t define a new class either I also needed a dynamic type. Here my first try at it:

Func<MyObject, object> f =  o =>
{
	dynamic t = new
	{
		Name = o.Name,
		Guid = o.Guid,
		Children = o.Children.Select(e => f(e))
	};
	return t;
};
var r = f(root);

string s = new JavaScriptSerializer().Serialize(r);

If you try this, you will see it won’t compile and will show the following error:

Use of unassigned local variable ‘f’

The problem is that we’re defining f and using it in one statement. So the solution is obvious: split the declaration and assignment:

Func<MyObject, object> f = null;
f = o =>
{
	dynamic t = new
	{
		Name = o.Name,
		Guid = o.Guid,
		Children = o.Children.Select(e => f(e))
	};
	return t;
};

With this I do get a JSON structure without any problems related to circular references. Here the whole source code for your reference:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;

namespace Playground
{
    public static class JsonTest
    {

        class MyObject
        {
            public MyObject()
            {
                Children = new List<MyObject>();
            }

            public string Name { get; set; }
            public Guid Guid { get; set; }
            public IList<MyObject> Children { get; set; }
            public MyObject BestFriend { get; set; }
        }

        public static void Main()
        {
            var root = new MyObject {Name = "Root", Guid = Guid.NewGuid()};
            var object1 = new MyObject { Name = "Child1", Guid = Guid.NewGuid() };
            var object2 = new MyObject { Name = "Child2", Guid = Guid.NewGuid() };
            var object3 = new MyObject { Name = "Child3", Guid = Guid.NewGuid() };
            var object4 = new MyObject { Name = "Child4", Guid = Guid.NewGuid() };
            var object5 = new MyObject { Name = "Child5", Guid = Guid.NewGuid() };
            var object6 = new MyObject { Name = "Child6", Guid = Guid.NewGuid() };

            object1.Children.Add(object3);
            object1.Children.Add(object4);

            object2.Children.Add(object5);
            object2.Children.Add(object6);

            root.Children.Add(object1);
            root.Children.Add(object2);
            
            object3.BestFriend = object1;

            Func<MyObject, object> f = null;
            f = o =>
            {
                dynamic t = new
                {
                    Name = o.Name,
                    Guid = o.Guid,
                    Children = o.Children.Select(e => f(e))
                };
                return t;
            };
			
            var r = f(root);

            string s = new JavaScriptSerializer().Serialize(r);
            Console.WriteLine(s);
        }
    }
}

Note that the Mono compiler seems to have issues with it but it works fine using the Microsoft CSharp compiler.

When using JSON.NET (also known as Newtonsoft.Json), there is a useful setting called ReferenceLoopHandling. If you set it to ReferenceLoopHandling.Ignore, the serializer will only serialize objects once. If an object is encountered a second time, it will not be serialized again. Here’s how to use this setting:

string s = JsonConvert.SerializeObject(root, Formatting.None,
	new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore});

There are two additional options for ReferenceLoopHandling:

  • ReferenceLoopHandling.Error: This is the default behavior. You get an Exception when a circular reference is detected.
  • ReferenceLoopHandling.Serialize: This will force the serializer to serialize everything even if a circular reference is detected. This seems to be mostly useful in cases where you have nested object but know there won’t be an infinite loop. But frankly I’d not recommend using it at all.

If you are using the standard JavaScriptSerializer, you should consider moving the JSON.NET. It’s fast, reliable and provide nice additional features like this one. I have moved to JSON.NET for all my projects and have never looked back.

Also if you are using the Entity framework, it might be worth a try switching off the automatic proxy generation on your DB context using:

dbContext.Configuration.ProxyCreationEnabled = false;