Category Archives: C#

Friend assemblies (or how to make internals visible to other assemblies)

As you know, the internal modifier denotes that types and type members are only accessible by code from the same assembly.

Therefore the DoSomething method in the following is not visible to other assemblies but can be using by code within the assembly which contains this type

public class MyClass
{
   internal int DoSomething()
   {
   }
}

In some cases it’s useful to have internal types or type members visible to other assemblies, but limited to only those assemblies. These assemblies are known as friend assemblies.

To denote the friend assemblies we add the InternalsVisibleTo attribute to the assembly who hosts the internals and specify the friend assembly in the following manner

[assembly: InternalsVisibleTo("FriendAssembly")]

Now the FriendAssembly can access the DoSomething method on type MyClass.

Dynamically resolve assemblies at runtime

I came across this recently. I must admit I’ve not personally had a need for it, but it’s an interesting “trick”, so I wrote a little reusable framework around it.

So let’s say you deploy an application without all of it’s dependencies as part of the expected dependency resolution path. For example, in this case I’ve embedded all the assemblies as resources into the EXE so I can deploy a single file, but the technique should allow us to also resolve the dependencies via some other technique, such as from a remote location.

Create an EXE application and add the DLL(s) or EXE(s) and optionally their PDB(s) to the application as embedded resources. As your application depends on one (or more) of these assemblies then one (or more) of them will also be referenced. Mark the referenced assemblies which you’ve embedded as Copy Local=false (obviously we’re not talking about the GAC assemblies here) so they’re not copied to the output folder, obvious if you run the application now it will fail to locate these required assembles as we’ve embedded them as resources.

So, when the application starts up it attempts to resolve any missing dependencies and if it has any problem resolving the dependencies it fires the AssemblyResolve event on the AppDomain.CurrentDomain, it’s at this point that we want to dynamically load the assemblies ourselves into the app domain.

What we need to do is attach an event handler to the AppDomain.CurrentDomain.AssemblyResolve, as per

AppDomain.CurrentDomain.AssemblyResolve +=
       DynamicAssemblyResolver.Resolve(args, new ResourceAssemblyResolver());

I now try to resolve the missing dependency using an IAssemblyResolver (in this instance that is the ResourceAssemblyResolver class).

Below is a helper class named DynamicAssemblyResolver which simple (potentially) loops through any supplied IAssemblyResolver implementations passing the AssemblyName that we’re trying to resolve

public class DynamicAssemblyResolver
{
   public static Assembly Resolve(ResolveEventArgs e, 
            IAssemblyResolver resolver, params IAssemblyResolver[] alternateResolvers)
   {
      return Resolve(e.Name, resolver, alternateResolvers);
   }

   public static Assembly Resolve(string nameToResolve, 
            IAssemblyResolver resolver, params IAssemblyResolver[] alternateResolvers)
   {
      return Resolve(new AssemblyName(nameToResolve), resolver, alternateResolvers);
   }

   public static Assembly Resolve(AssemblyName assemblyToResolve, 
            IAssemblyResolver resolver, params IAssemblyResolver[] alternateResolvers)
   {
      Assembly assembly = resolver.Resolve(assemblyToResolve.Name);
      if (assembly != null)
      {
         return assembly;
      }

      if (alternateResolvers != null)
      {
         foreach (IAssemblyResolver alternateResolver in alternateResolvers)
         {
            assembly = alternateResolver.Resolve(assemblyToResolve.Name);
            if (assembly != null)
            {
               return assembly;
            }
         }
      }
      return null;
   }
}

The interface for a resolver class looks like this

public interface IAssemblyResolver
{
   Assembly Resolve(string assemblyName);
}

and finally the implementation that resolves dependencies using the files embedded within the resource looks like

public class ResourceAssemblyResolver : IAssemblyResolver
{
   public Assembly Resolve(string assemblyName)
   {
      Assembly executingAssembly = Assembly.GetExecutingAssembly();
      return (from name in executingAssembly.GetManifestResourceNames() 
		where name.Contains(assemblyName) 
		select Resolve(executingAssembly, name)).FirstOrDefault();
   }

   private static Assembly Resolve(Assembly executingAssembly, string assemblyName)
   {
      try
      {
         using(Stream manifestResourceStream = 
                      executingAssembly.GetManifestResourceStream(assemblyName))
         {
            if (manifestResourceStream == null)
   	    {
               return null;
            }

            string pdb = Path.ChangeExtension(assemblyName, ".pdb");
	    using (Stream pdbResourceStream =                
                     executingAssembly.GetManifestResourceStream(pdb))
	    {
	       return Assembly.Load(Read(manifestResourceStream),
			(pdbResourceStream != null) ?
			Read(pdbResourceStream) : null, 								                
                        SecurityContextSource.CurrentAppDomain);
 	    }
         }
      }
      catch (Exception)
      {
         throw;
      }
   }

   private static byte[] Read(Stream stream)
   {
      byte[] array = new byte[stream.Length];
      stream.Read(array, 0, array.Length);
      return array;
   }
}

The above code tries to match the supplied assembly name with the resources found embedded in the calling assembly.

Note: A failing of the above approach is that if more than one file exists with the same name, i.e. MyLib.dll existing in multiple resources but in different folders (obviously), then the first one only is ever resolved.

Ix/Interactive Extensions

I’m a bit late to the party with this one – Ix or Interactive Extensions.

Available on NuGet via the Ix-Main package. This will give us the System.Interactive assembly.

Ix are basically a bunch of extension methods for IEnumerable and the
EnumerableEx class. I’m sure many of us have written IEnumerable extensions to supply a ForEach extension method or the likes. Well Ix gives us that and more.

In this post I will not be documenting each overload but will try to give an idea of what the methods might be used for and how to use them. Checking which overload is suitable is down to the reader.

Note: some of the examples may be less than useful, I will attempt to update with better examples as/when I come up with them.

Buffer

Basically takes an IEnumerable and creates an IEnumerable of IList of type T of the given buffer size.

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76, 45, 32, 1, 6, 3, 89, 100 };
IEnumerable<IList<int>> lists = items.Buffer(3);

The above would result in an IEnumerable with 4 ILists of type T each containing up to 3 items each. An overload of this method exists which allows you to skip a number of elements at the start of each buffer.

Case

Case is a static method on EnumerableEx and allows us to pass in an argument to compare against and an IDictionary of keys – which will be used to match with the argument passed into the Case method and it will return an IEnumerable relating to the values which appear in the dictionary against the given key. So for example

IDictionary<int, IEnumerable<string>> d = new Dictionary<int, IEnumerable<string>>
{
   {5, new[] {"Five"}},
   {4, new[] {"Four"}},
   {1, new[] {"One"}},
   {2, new[] {"Two"}},
   {3, new[] {"Three"}},
};

var matches = EnumerableEx.Case(() => 4, d);

In the above, matches will contain the IEnumerable of the values stored in the dictionary against the key 4, in other words the IEnumerable containing the string “Four”.

An overload of this method allows you to supply an IEnumerable to act as the default values should a match against the selector not be found.

Create

Create is a static method on the EnumerableEx class which allows us to create an IEnumerable from a IEnumerator (or via an overload from an IYielder).

Let’s assume we have a method that returns an IEnumerator of integers, here’s a mock up of such a method

private static IEnumerator<int> Factory()
{
   yield return 1;
   yield return 2;
   yield return 3;
   yield return 4;
}

Now using Ix we can create an IEnumerable of integers using

var items = EnumerableEx.Create(Factory);

Defer

As the name suggests Defer will defer the creation of an enumerable sequence until a call to GetEnumerator, so for example

var items = EnumerableEx.Defer(() => new [] { 3, 5, 6, 2 });

the code above will not call the enumerable factory method (in this case the anonymous method creating an array of integers) until the GetEnumerator is called.

Catch

Creates an IEnumerable sequence based on the source, but if the source has an exception will switch to the second IEnumerable.

A somewhat convoluted sample below

IEnumerable<int> GetNegatives()
{ 
   int[] items = new int[] { -1, -2, 0, -3 };
   for (int i = 0; i < items.Length; i++)
   {
      if (items[i] >= 0)
         throw new Exception();

      yield return items[i];
   }
}

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76, 45, 32, 1, 6, 3, 89, 100 };
IEnumerable<int> e = GetNegatives().Catch(items);

The above will create an IEnumerable e that contains -1, -2 and then the values from the items IEnumerable.

There are several overloads of the Catch method to check out.

Distinct

Returns an IEnumerable of the distinct values in a sequence

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76, 45, 32, 1, 6, 3, 89, 100 };
IEnumerable<int> distinct = items.Distinct();

The above will result in a sequence 3, 5, 6, 2, 76, 45, 32, 1, 89, 100 removing the duplicates.

DistinctUntilChanged

Returns consecutive distinct values

IEnumerable<int> items = new int[] { 3, 3, 3, 5, 5, 2, 76, 76, 100 };
IEnumerable<int> distinct = items.DistinctUntilChanged();

The above will return an sequence 3, 5, 2, 76, 100

Do

Several overloads of the Do method exist, we’ll just take a look at the one which takes an Action. Do will simply invoke some action on each item within the IEnumerable, so for example

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76 };
items.Do(Console.WriteLine);

the above code will simply call WriteLine on each integer within the items IEnumerable. However, this is lazy and hence we actually need to do something with the items returns enumerable.

DoWhile

The DoWhile method iterates over an IEnumerable whilst the supplied function is true, so for example

var items = new int[] { 3, 5, 6, 2 };

int i = 0;
var results = items.DoWhile(() => i++ < 2);
int len = results.Count();

If we run this code the len variable will be 12 as the DoWhile looped through the IEnumerable 3 times and the items array contained four items. So basically if we output to the console each item returned by results will see the array items output three times.

Expand

Expand, basically loops through the supplied IEnumerable (possibly infinitely if you do not use a Take or similar method to stop it). In essence is applies a selector function each time through the enumerable changing the values.

So imagine we have an array of values 1, 2 and 0 and apply Expand to this as follows

var items = new [] { 1, 2, 0 };
var results = items.Expand(i => new[] {i + 1}).Take(9);

what happens here is the output (if we ran results.ForEach(Console.WriteLine)) will output 1, 2, 0 (the values from items then 2, 3, 1 and finally 3, 4, 2. As you see each time we iterate through we add 1 to each element.

Finally

Finally can be used on a sequence so that an action may be invoked upon the termination or disposal, so for example the following will output the sequence to the console then output “Completed”

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };

items.Finally(() => Console.WriteLine("Completed")).ForEach(Console.WriteLine);

For

The For method takes a source enumerable and applies a supplied enumerable to it, so a simple example might be

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76 };
EnumerableEx.For(items, i => new []{i + 1, i + 2});

In this case each item in the items enumerable will have the new []{i + 1, i + 2} applied to it, thus output for this would be

4, 5, 6, 7, 7, 8, 3, 4, 77, 78

the first item 3 in the source enumerable is sent to the For method and we get back a transformed value as two values 3 + 1 and then 3 + 2 and so on.

ForEach

ForEach will invoke an action on each item within an IEnumerable, so a simple example might be to just write a more compact foreach to write output to the console, i.e.

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76 };
items.ForEach(Console.WriteLine);

Generate

As the name suggests, Generate can be used to generate a sequence in a similar way to a for loop might be used, here’s an example which creates an IEnumerable with the range [10, 20]

EnumerableEx.Generate(10, i => i <= 20, i => i + 1, i => i)

The first argument is the starting value, then we have the condition to stop the generator, next we have the state update function, in this case we’re incrementing the state by 1, finally we have the result function, in this case we’re just using the supplied state value.

Hide

To quote the documentation “Returns Enumerable sequence with the same behavior as the original, but hiding the source identity”.

I’m not wholly sure of the use cases for this, but basically if we have the following

List<int> items = new List<int> { 3, 5, 6, 2, 76 };

if we used items.AsEnumerable() the type returned would still be a List however using

var result = items.Hide();

result will be a funky EnumerableEx type hiding the underlying implementation.

If

The If method is self-explanatory, it allows us to return an IEnumerable if a condition is met or it will return an empty sequence or the overload shown below acts as an if..else returning the alternate sequence

EnumerableEx.If(() => someCondition, new[] { 3, 5, 6, 2, 76 }, new [] {6, 7});

So it’s probably obvious that if the someCondition is true the first array is returned else the second array is returned.

IgnoreElements

A slightly odd one, which probably is more useful when used in combination with other methods. IgnoreElements returns a source sequence without its elements

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.IgnoreElements();

result will be an empty sequence.

IsEmpty

As the name suggests, checks if the sequence is empty or not, obviously the following is not empty

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.IsEmpty();

whereas the following will be empty

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.IgnoreElements().IsEmpty();

Max

Returns the maximum value in the sequence

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.Max();

this will result in the result being 76.

MaxBy

In essence MaxBy returns a sequence of values less than the supplied comparer, for example

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
items.MaxBy(i => i < 50).ForEach(Console.WriteLine);

this will create a sequence with values less than 50 and in this case write them to the console, thus outputting the values 3, 6 and 2.

Memoize

Memoize creates a buffer over the source sequence to ensure that if we were to iterate over the items multiple times we would not call the source multiple times. Obviously this would be useful if we’ve got the data from some file system or remote source to stop us retrieving the data multiple times, in use we have

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.Memoize();

Min

Returns the minimum value in the sequence

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.Max();

this will result in the result being 2.

MinBy

In essence MinBy returns a sequence of values greater than the supplied comparer, for example

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
items.MinBy(i => i < 50).ForEach(Console.WriteLine);

this will create a sequence with values greater or equal to 50 and in this case write them to the console, thus outputting the values 50 and 76.

OnErrorResumeNext

Concatenates the sequence with a second sequence regardless of whether an error occurred, used in situation where you might be getting data from a source that could fail, the example below just shows the syntax really as this wouldn’t need to use OnErrorResumeNext

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
var result = items.OnErrorResumeNext(new[] {9, 10});

result would contain the items sequence followed by the sequence { 9, 10 }.

Publish

To quote the documentation, “creates a buffer with a view over the source sequence, causing each enumerator to obtain access to the remainder of the sequence from the current index in the buffer”.

This allows the sequence to be shared via the buffer, in syntax terms this looks like

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
var buffer = items.Publish();

There is an overloaded method which allows you to supply a selector.

Repeat

Allows us to iterate through a sequence infinitely or with the overload, n times

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };

// iterate over three times
items.Repeat(3).ForEach(Console.WriteLine);

// iterate infinitely
items.Repeat().ForEach(Console.WriteLine);

Retry

This method allows us to retry enumerating a sequence whilst an error occurs or via the overload we can specify the maximum number of retries

items.Retry(2);

Return

The Return method returns a single element as a sequence, for example

EnumerableEx.Return(1);

this creates an IEnumerable of integers with the single value 1 in it.

Scan

Scan generates a sequence using an accumulator, so for example

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
items.Scan((i, j) => i + j).ForEach(Console.WriteLine);

will pass 3 (i) and 5 (j) into the accumulator method the result will be 8 this will then be pass into the accumulator as i followed by 6 (j) and so on.

SelectMany

Several overloads exist, the one shown here simply projects each element of the sequence with a given sequence. For example the following simply projects the array { 5, 6 } over the original sequence

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
items.SelectMany(new [] { 5, 6 }).ForEach(Console.WriteLine);

This will output { 5, 6 } the number of times matching the number of elements in the items sequence, i.e. 5 times.

Share

A couple of overloads. This method creates a buffer with a shared view over the sequence so mutiple enumerators can be used to fetch the next element from the sequence, this example is a little convoluted

IEnumerable<int> items = new [] { 20, 10, 60, 30 };
items.Share(x => x.Zip(x, (a, b) => a - b)).ForEach(Console.WriteLine);

The same sequence is used on Zip and passed into Zip hence we’re zipping the sequence with itself, the result selector simply subtracts one value from the other. When output to the console this will write a sequence 10, 30 because the first item (20) has the second item (10) subtracted from it, as then the next item (60) has the final item (30) subtracted.

SkipLast

Allows us to skip/bypass n elements from the end of in the sequence, thus

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
items.SkipLast(2).ForEach(Console.WriteLine);

lists values 3, 5, 6 but not the last 2 items.

StartWith

StartWith starts the sequence with the newly supplied enumerable, for example

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
items.StartWith(new []{9, 10}).ForEach(Console.WriteLine);

will output the sequence 9, 10 then follow with the items sequence.

TakeLast

In essence the opposite of SkipLast, TakeLast results in a sequence on the last n items, such as

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
items.TakeLast(2).ForEach(Console.WriteLine);

which outputs 2 and 76.

Throw

With the Throw method we can create a sequence which throws an exception when we try to enumerate it, for example

EnumerableEx.Throw<int>(new NullReferenceException()).ForEach(Console.WriteLine);

will throw the NullReferenceException when ForEach attempts to enumerate the sequence.

Using

Using creates a sequence which has a resource who’s lifetime is determined by the sequence usage. The idea being the resource is created via the Using method’s first argument then passed to the second argument (in all likelihood to be used in some way) before an IEnumerable is returned. The key thing to note is the resource is not created until we use the returned IEnumerable, for example

IEnumerable<int> items = new [] { 3, 5, 6 };
IEnumerable<int> results = EnumerableEx.Using(() => new SomeDisposable(), resource => items);
results.ForEach(Console.WriteLine);

Assuming SomeDisposable implements IDisposable, when we call GetEnumerator the SomeDisposable is created and passed to the second argument – this rather simplistic example does nothing with the resource but hopefully you get the idea. We then return the IEnumerable and when the GetEnumerator completes the resources Dispose method is called.

While

Loops through the sequence whilst a condition is true, so for example

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };

int i = 0;
EnumerableEx.While(() => i++ < 3, items).ForEach(Console.WriteLine);

will output the items sequence three times.

How to exclude code from code coverage

In Visual Studio 2012 we can run code coverage analysis across our code (for example across our unit test suite). But we might not want to have all code analysed. For example I don’t really want to see the test classes as part of the analysis but do want to see the code under test.

So we can exclude code from the code coverage analysis using the ExcludeFromCodeCoverageAttribute. This can be applied to methods, properties, classes, structs etc.

Operator Overloading in C#

I don’t use operator overloading as much in C# as I did in my C++ days. Part of this might simply be down to the types of application I write nowadays where using operating overloading is less useful. Anyway, every time I need to overload an operator I seem to have forgotten the format/syntax. So this post is my memory dump on this subject.

Not all operators can be overloaded. To save myself some typing, check this link for a full list of the operators and what may or may not be overloaded, http://msdn.microsoft.com/en-us/library/8edha89s(v=vs.80).aspx.

Unary Operators

Unary operators, such as +, -, !, ~, ++, –, true, false (yes even true and false) can be overloaded. The syntax is as follows:

public static ReturnType operator Operator(ContainingType)
{
}

For +, -, ++ and — The ReturnType might be the actual object that the code is associated with on another valid type which makes sense for the operation (for example an int).

For the !, ~, true, false the return type must be a boolean.

The Operator is obviously the operator +, -, !, ~, ++, –, true, false and finally the ContainingType must be, well the containing type. You must overload both true and false if you want to overload either of these.

Binary Operators

Binary operators, such as +, -, *, /, %, |, &, ^, << and >> can be overloaded. The syntax is as follows:

public static ReturnType operator Operator(ContainingType, Type)
{
}

The difference being that two arguments are supplied, the two arguments may both be the ContaingType or the second argument might be a different type, for example when using a + b, a might be a complex number and b an int. In the case of the << and >> bit shift operators the second argument must be an int.

Comparison Operators

Comparison operators, such as ==, != <, <=, >, >= can be overloaded. The syntax is as per the binary operator’s syntax. The == and != must both be implemented as pairs of operators as must the > and < operators and the >= and <= operators. Implicit and Explicit operators

If you want to implement cast operators, you can implement an implicit cast should be used if the operation is guaranteed to not lose information and explicit should be used for scenarios where a loss of information is possible and/or where you want to ensure the user is aware of the possible cast.

The syntax for both implicit and explicit cast is the same

public static CastOperator operator CastType(ContainingType)
{
}

The CastOperator is either implicit or explicit, the CastType is the returning type that you’re casting to and the ContainingType is the type that contains the overloaded operator.

For a full, if somewhat pointless example, here’s a Number class that wraps and int

public class Number
{
   private int number;

   public Number(int value)
   {
      number = value;
   }

   public int Value
   {
      get { return number; }
   }

   // format for implicit cast but disabled to ensure it doesn't 
   // affect other operators, i.e. casting to in int automatically.
   //public static implicit operator int(Number n)
   //{
   //	return n.number;
   //}

   public static explicit operator int(Number n)
   {
      return n.number;
   }

   // unary operators
   public static Number operator +(Number n)
   {
      n.number = +n.number;
      return n;
   }

   public static Number operator -(Number n)
   {
      n.number = -n.number;
      return n;
   }

   public static bool operator !(Number n)
   {
      return n.number == 0;
   }

   public static bool operator ~(Number n)
   {
      return !n;
   }

   public static Number operator ++(Number n)
   {
      n.number++;
      return n;
   }

   public static Number operator --(Number n)
   {
      n.number--;
      return n;
   }

   public static bool operator true(Number n)
   {
      return n.number != 0;
   }

   public static bool operator false(Number n)
   {
      return n.number != 0;
   }

   // binary operators
   public static Number operator +(Number a, Number b)
   {
      return new Number(a.number + b.number);
   }

   public static Number operator -(Number a, Number b)
   {
      return new Number(a.number - b.number);
   }

   public static Number operator *(Number a, Number b)
   {
      return new Number(a.number * b.number);
   }

   public static Number operator /(Number a, Number b)
   {
      return new Number(a.number / b.number);
   }

   public static Number operator %(Number a, Number b)
   {
      return new Number(a.number % b.number);
   }

   public static Number operator &(Number a, Number b)
   {
      return new Number(a.number & b.number);
   }

   public static Number operator |(Number a, Number b)
   {
      return new Number(a.number | b.number);
   }

   public static Number operator ^(Number a, int b)
   {
      return new Number(a.number ^ b);
   }

   public static Number operator <<(Number a, int shiftBy)
   {
      return new Number(a.number << shiftBy);
   }

   public static Number operator >>(Number a, int shiftBy)
   {
      return new Number(a.number >> shiftBy);
   }

   // comparison operators
   public static bool operator ==(Number a, Number b)
   {
      return a.Value == b.Value;
   }

   public static bool operator !=(Number a, Number b)
   {
      return a.Value != b.Value;
   }

   public static bool operator <(Number a, Number b)
   {
      return a.Value < b.Value;
   }

   public static bool operator <=(Number a, Number b)
   {
      return a.Value <= b.Value;
   }

   public static bool operator >(Number a, Number b)
   {
      return a.Value > b.Value;
   }

   public static bool operator >=(Number a, Number b)
   {
      return a.Value >= b.Value;
   }
}

Basics of async and await

In .NET 4.5 Microsoft added the async and await keywords.

Important: By prefixing a method with the async keyword we’re telling the .NET compiler that you want to use the await keyword. The async keyword does NOT mean your method is automatically asynchronous, i.e. the compiler will not automatically assign a thread to it or a task. It simple indicates that the compiler to compile the code so that it can be suspended and resumes at await points.

If you wrote a simple async method which carried out some long running calculation the method would still be synchronous. Even if we await the result (you can have a async method without an await but this is equivalent to any other type of synchronous method and will result in compiler warnings).

So what’s the point of async and await ?

We basically use async on a method to allow us to use await. If there’s no async then we cannot use await. So the await is really where the magic happens.

The await keyword can be thought of as a continuation on a Task. It allows us to break a method into parts where we can suspend and resume a method. Below is an example of a call to some LongRunningTask

// simulation of a method running on another thread
private Task LongRunningTask()
{
   return Task.Delay(10000);
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
   textBox.Text = "";
   await LongRunningTask();
   textBox.Text = "Completed";
}

What happens with the above is that a button click event takes place and the textbox is set to an empty string, then a LongRunningTask occurs on a different task. The await keyword suspends operation of this method now until the LongRunningTask completes but the UI in this case remains responsive. When the LongRunningTask ends the text is set to “Completed”. As the button was called from the UI thread the code after the await line is run on the UI thread, i.e. the synchronization context for the code after the await line is the same as the synchronization context used before the await line.

An async method may have one of three types of return, a Task (non-generic) and Task<> (generic) and a void. The return should be either of the Task objects to allow for a calling method to await the method. Void should only be used for things like event handlers.

We can implement code similar to await using Task ContinueWith, but one neat feature of async/await is in WinForms/WPF The code after the await is executed on the same thread as the async method was called on. ContinueWith, by default, is executed on another thread. Obviously this feature of async/await is very useful with the likes of WinForms as a button click might await a webservice call or the likes, then return onto the GUI thread upon return.

A using clause inside a namespace is different to a using clause outside a namespace

For some reason I always forget the difference between using a using clause inside a namespace as opposed to outside. Occasionally I come across other people’s code where they’ve obviously explicitly copied their using clauses inside their namespace, being that by default creating a new C# file will place the default using clauses at the top of the file (outside the namespace).

So what’s the difference ?

If we have a class sitting in a namespace such as MyNamespace.MyClasses (with using System; outside the namespace) such as

using System;

namespace MyNamespace.MyClasses
{
   class MyClass
   {
      void MyMethod()
      {
         String s = String.Empty;
         // do something
      }
   }
}

It’s happily using the System.String object, but then along comes a new developer on the project who creates a String class specific to the project.

So the new class is added to the MyNamespace namespace in the following way

namespace MyNamespace
{
   class String
   {
   }
}

At this point our previous code will fail with a ‘MyNamespace.String’ does not contain a definition for ‘Empty’. This is because when the compiler searches for the String class it starts in the MyNamespace.MyClasses namespace then the MyNamespace namespace and then finally the using clauses outside of the namespace. So in this instance it finds a matching String class in the namespace MyNamespace and unless the String is fully qualified (i.e. System.String s = System.String.Empty; will try to use this. Obviously this is the wrong String class.

If we move the using System; inside the namespace of MyClass, such as

namespace MyNamespace.MyClasses
{
   using System;
   
   class MyClass
   {
      void MyMethod()
      {
         String s = String.Empty;
      }
   }
}

In this instance the compiler searches the MyNamespace.MyClasses namespace and then the using clauses within that namespace and so can resolve the String.Empty const and the newly added String class can still be implemented without being mistakenly used.

Custom storing our ApplicationSettingsBase derived object

In my post I details how you can create an application settings class to read application settings and read/write user settings in a simple and consistent manner. But there’s more…

By default the user scoped properties are stored in a user.config file in the user’s profile. But we can actually customise where/how the settings are persisted by implementing code in a class derived from the SettingsProvider class. Firstly we need to apply the following

[SettingsProvider(typeof(MySettingsProvider))]

to the ApplicationSettingsBase derived class (in my previous post this would look like)

[SettingsProvider(typeof(ConfigurationSettingsProvider))]
public sealed class ConfigurationSettings : ApplicationSettingsBase
{
   // properties
}

Next we obviously need to implement the ConfigurationSettingsProvider. In fact Microsoft implemented this to create the LocalFileSettingsProvider class which by default is applied to our settings class (allowing us to read from the app.config and persist to the user.config).

By overriding methods such as Initialize, GetPropertyValues and SetPropertyValues we can get our settings from our own mechanism, for example a web service and persist changes back to the web service.

For further information checkout .

User application settings using ApplicationSettingsBase

There are many ways to store application settings, whether they’re roll your own XML or old INI profile file settings. Another option is to use a class derived from ApplicationSettingsBase.

ApplicationSettingsBase

To create your own configuration class, you derive it from the ApplicationSettingsBase class and then add properties to define the values you want to persist. On top of this we can override methods such as Save to allow us to customise the saving of values etc. A simple example is listed below (note: we’d often write this class as a singleton but I’ve removed extraneous code from the sample).

public sealed ProxySettings : ApplicationSettingsBase
{
   [UserScopedSetting]
   public string Host
   {
      get { return (string)this["Host"]; }
      set { this["Host"] = value; }
   }

   [UserScopedSetting, DefaultSettingValue("8080")]
   public int Port
   {
      get { return (int)this["Port"]; }
      set { this["Port"] = value; }
   }

   [ApplicationScopedSetting]
   public string ApplicationContext
   {
      get { return (string)this["ApplicationContext"]; }
   }
}

For a property to be stored or read using this mechanism, it must have the UserScopedSetting or the ApplicationScopedSettings attribute applied to it, otherwise it’s ignored from the perspective of persistence but obviously you can still use it as a non-persisted property.

ApplicationScopedSettings is used for application specific settings whereas UserScopedSetting is used for user specific settings (I know the names give this away but I thought I should make it clear). In the case of UserScopedSettings these, by default, are stored in the Documents and Settings\\Application Data in a user.config file whereas ApplicationScoreSettings are stored within the app.config for the application.

Note: The user scoped settings are not stored automatically, you need to call the ApplicationSettingsBase.Save method.

ApplicationScopedSettings are in essence read-only. Whilst we can have a getter and setter on the class (above), allowing us to change the application setting at run-time the altered values are not persisted to a storage mechanism.

Q. So what’s the point of ApplicationScopedSetting ?

A. You can add these values to your app.config and use it from your project in a similar way to using ConfigurationManager.AppSettings but obviously it can reside along with your user settings in a class as above and thus both the user and application scoped values are read in the same way, using this class. Underneath they’re separated into the user.config and app.config.

You can declare a default value to an ApplicationScopedSetting and then if you wanted to change the value in the app.config you’ll have a fallback default if the configuration is missing. The app.config will look something like

<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="MyApplication.ConfigurationSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <MyApplication.ConfigurationSettings>
      <setting name="ProxyAdddress" serializeAs="String">
        <value>BlahBlah</value>
      </setting>
    </MyApplication.ConfigurationSettings>
  </applicationSettings>
</configuration>

Creating your application settings via a designer

Creating your ApplicationSettingsBase derived class is extremely useful if you have some more complex code (other than just read/write). But you can also create your own settings within Visual Studio and have it automatically created the source code for you. Simply go to the Properties folder in your solution and use the Settings.settings file, double clicking on this allows you to edit your properties and the Designer.cs will automatically be generated as a singleton and creates all the stuff as we’ve done previously ourselves. Better still this will generated the app.config code as well and save us having to remember the correct configuration xml.

You can ofcourse add more .settings files using the Add | New Item and select the Settings File.

Note: If you’re trying to track down where your configuration files might have been saved you can always call

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Console.WriteLine(configuration.FilePath);
configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
Console.WriteLine(configuration.FilePath);
configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
Console.WriteLine(configuration.FilePath);

Partial classes and methods in C#

Partial classes, structs and interfaces

Partial classes, structs or even interfaces can be declared in C#. This mechanism allows us to split a class, struct or interface definition across multiple files which gives us some interesting possibilities.

For example, let’s same you reference a web service and you’ve generated a class like the following (I’ve removed extraneous base classes etc.)

public partial class Person
{
   private string string FirstNameField;
   private string string LastNameField;

   public string FirstName
   {
      get { return this.FirstNameField; }
      set
      {
         if((this.FirstNameField.Equals(value) != true))
         {
            this.FirstNameField = value;
            this.RaisePropertyChanged("FirstName");
         }
      }
   }

   public string LastName
   {
      get { return this.LastNameField; }
      set
      {
         if((this.LastNameField.Equals(value) != true))
         {
            this.LastNameField = value;
            this.RaisePropertyChanged("LastName");
         }
      }
   }
}

By default svcutil.exe will create the class as a partial. This allows us to now define an addition to the class that implements more functionality which can be run locally and will remain when/if we need to regenerate the proxies class above. We simply create another file (by convention this would be the .partial.cs, so in this case Person.partial.cs but of course this isn’t a requirement for partials to work).

public partial class Person
{
    public string FullName
    {
       get { return String.Format("{0} {1}", FirstName, LastName); }
    }
}

Partial Methods

Partial methods are methods whose signature can exist in one partial type but it implementation may defined in another. For example

public partial class Project
{
   partial void Run();
}

// in another file we might have
public partial class Project
{
   partial void Run()
   {
      Console.WriteLine("Running");
   }
}

A partial method must have the following:

  • The signature for the method must match in the partial type
  • The method can only return void
  • Partial methods are implicitly private and no access modifiers are allowed (even private is not allowed)

One of the key things about a partial method is the even if there’s no implementation of the method the code will still compile successfully and run. So you can use a partial method as a place holder for possible implementation at some later time if you wished and the code would still work. If no implementation exists for Run (in the above example) any calls to the Run method will be removed.