Category Archives: C#

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.

WCF – Basics

I’ve used WCF (and the previous incarnation of web services in .NET) on and off for a while. However once the inital work to set the application up is completed I tend to forget much of what I’ve done to concentrate on the actual application. This is one of the great things with WCF – it just works once set-up.

So this post is going to be written as a quick refresher.

ABC

One of the key things to remember with WCF is the the setting up is pretty much all about the ABC’s

  • A is of Address. In other words what’s the location (or endpoint) of the service.
  • B is of Binding. How do we connect to the endpoint, i.e. what’s the protocol etc.
  • C is of Contract. The application/programming interface to the web service, i.e. what does it do ?

Contracts

Simply put, creating an interface and decorating the interface with [ServiceContract] will mark out an interface as a service contract. Marking the methods that you want to publish with [OperationContract] i.e.

[ServiceContract]
public interface IPlantService
{
   [OperationContract]
   List<Plant> GetPlants();
   // and so on
}

where we’re passing our own complex types back (in the above we have the Plant class) here we mark the class with [DataContract] attribute and each property we wish to publish are marked with [DataMember] as per

[DataContract]
public class Plant
{
   [DataMember]
   public int Id { get; set; }
   [DataMember]
   public string CommonName { get; set; }
   // ... and so on
}

Don’t forget to include the System.ServiceModel assembly and System.Runtime.Serialization.

Hosting a service outside of IIS

Whilst IIS offers a scaleable, consistent and secure architecture for hosting WCF web services, one might prefer to host via a console app or Windows service for example. The following is a simple example of the code needed to get WCF self hosted in a console application.

class Program
{
   static void Main(string[] args)
   {
      ServiceHost serviceHost = new ServiceHost(typeof(PlantService));
      serviceHost.Open();
      Console.WriteLine("Service Running");
      Console.ReadLine();
      serviceHost.Close();
   }
}

Configuring the ABC’s

Configuration of the ABC’s can be accomplished through code or more usually through configuration. I’m not going to dig deep into configuration but instead point to something I’ve only recently been made aware of. Having always edited the app.config by hand.

It’s slightly strange in Visual Studio 2010 how you enable this option but go to Tools | WCF Service Configuration Editor then close it. Now if you right mouse click to get the context menu on the App.config file you’ll see the Edit WCF Configuration option. Now you can configure WCF via this UI.

Entity Framework – Dynamic Proxies and WCF

A quick post regarding a simple problem you might find using Entity Framework with WCF. I have a simply little application which uses Entity Framework to access SQL Server and currently this all happens in a little client application.

I decided I wanted to move the DB access into a web service so I could look at writing an iPad or the likes front end to access it. All went well until I got the following exception


An error occurred while receiving the HTTP response to http://localhost:9095/MyService. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

My web service code looked like the following

public List<Plant> GetPlants()
{
   using (PlantsContext context = new PlantsContext())
   {
       return context.Plants.ToList();
   }
}

The problem is that the return is returning dynamic proxies, of the Plant type, not strictly real Plant types. What we need to do is change the code to add a line to turn off proxy creation

using (PlantsContext context = new PlantsContext())
{
   context.Configuration.ProxyCreationEnabled = false;
   return context.Plants.ToList();
}

And all works.

Quick Start – MahApps Metro

I discovered the excellent MahApps Metro libraries a while back but it wasn’t until I started using github:Windows that I was inspired to really start using this excellent library.

Basically MahApps Metro offers a bunch of styles and controls which duplicate aspects of Windows 8 UI but ofcouse they can be used on non-Windows 8 versions of Windows. For example, I have code on both WinXP and Windows 7 using these libraries and they look great.

This post is just a quick “how to quickly get up and running” with MahApps.

  • Let’s start by creating a WPF Application in Visual Studio.
  • Now using NuGet type MahApps.Metro into the search box of NuGet and install MahApps.Metro
  • In the MainWindow.xaml.cs change the base class from Window to MetroWindow and add using MahApps.Metro.Controls;
  • In the MainWindow.xaml change Window to MetroWindow add the namespace if need be (for example xmlns:Controls=”clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro”)
  • Finally add A Window.Resources section to the MainWindow.xaml file as per the code below to enable the Metro styles
<Window.Resources>
   <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
         <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
      </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>
</Window.Resources>

Note: After installing MahApps.Metro using NuGet the page http://mahapps.com/MahApps.Metro/ is displayed, it contains the steps above plus more so obviously read that for a fuller explanation. I’ve written these steps out just to show the bare minimum I need to do to get started.

The Singleton Pattern in C#

The singleton pattern has fallen out of favour in recent times, the preference being towards using IoC in it’s place, but it’s still useful. I’m not going to go in depth into coding samples for this pattern as there’s an excellent article “Implementing the Singleton Pattern in C#” which covers the subject well.

A simple thread safe implementation taken from the aforementioned article is

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();

   static Singleton()
   {
   }

   private Singleton()
   {
   }

   public static Singleton Instance
   {
      get { return instance; }
   }
}

Note: The private constructor is included as the intention is for the user to use the Instance property to interact with the Singleton instance and not allow creating a new Singleton directly.

System.Lazy has been around since .NET 4.0 and it offers a threadsafe means to implement lazy loading/initialization. So now we can rewrite the above Singleton class with lazy loading

public sealed class Singleton
{
   private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton());   

   private Singleton()
   {
   }

   public static Singleton Instance
   {
      get { return instance.Value; }
   }   
}