Category Archives: C#

MSBuild with C# 6 and UpgradeTemplate.xaml

If you use UpgradeTemplate for your MSBuild, getting it to work with C# 6 can be a little tricky.
First, we need to set the tools version by passing these parameters to MSBuild:
/tv:14.0 /p:VisualStudioVersion=14.0

This, however, may not change the MSBuild version used to run your build. TFS Build server may still use the MSBuild from your .Net framework folder (C:\Windows\Microsoft.NET\Framework64\v4.0.30319). To verify the location of your MSBuild, used by the TFS, open one of your completed builds, and check the Diagnostics tab. It should show the MSBuild.exe forlder in the “Run TfsBuild for Configuration Folder” step.

To fix this, we need to explicitly set the ToolPath for the MSBuild template.
Open the UpgradeTemplate.xaml in Visual Studio
Right click on “Run TfsBuild for Configuration” -> Properties
Set the ToolPath property to point to your msbuild: “C:\Program Files (x86)\MSBuild\14.0\Bin\”
Don’t forget the quotation marks.

While you’re at it, check out Target Framework Migrator – it’s a Visual Studio extension, which helps update all of your projects to target a specific .Net version. Can be quite helpful when you have a lot of projects.

Functional Extensions for C#

Map

public static TResult Map<TSource, TResult>(
	this TSource @this,
	Func<TSource, TResult> fn) => fn(@this);
);

Tee

public static TResult Tee<t>(
	this T @this,
	Action<T> fn) => fn(@this)
    {
		act(@this);
		return @this;
	}
);

Partial Function Application

public static Func<int, int> Add(int x) => y => x + y;
new[] {1, 2, 3}.Select(Add(1))

More stuff like this in Dave Fancher PluralSight course Functional Programming with C#

Short Summary of Delegation in C#

Classic

public delegate decimal MathOp(decimal left, decimal right)

public static decimal Add(decimal left, decimal right)
{
	return left + right;
}
private static MathOp GetOp(char op)
{
	switch (op)
	{
		case '+': return Add;
	}
}

Interfaces

public interface IMathOp
{
	decimal Compute(decimal left, decimal right);
}

public class AddOp : IMathOp
{

	decimal Compute(decimal l, decimal r)
	{
		return l + r;
	}
}

private static MathOp GetOp(char op)
{
	switch (op)
	{
		case '+': return new AddOp();
	}
}

Anonymous Methods

public delegate decimal MathOp(decimal left, decimal right)

private static MathOp GetOp(char op)
{
	switch (op)
	{
		case '+': return delegate (decimal l, decimal r) { return l + r};
	}
}

Generic Delegates and Lambda Expressions

public static Func<decimal, decimal, decimal> GetOp(char op)
{
	switch (op)
	{
		case '+': return (l, r) => l + r;
	}
}

For complete details, see Dave Fancher PluralSight course Functional Programming with C#

C# 6 Summary

Short and incomplete notes on Rob Conery Pluralsight course “Exploring C# 6 with Jon Skeet”

  • Auto-properties
    Immutability
    Old way (still can set anywhere within the class)

    public string Name {get; private set;}
    

    New way (can be set only in a constructor or initializer)

    public string Name{get;}
    

     
    Initializers

    public string Name{get;} = "J";
    
  •  

  • Expression-bodied members
    For Properties
    Old way

    public Timespan Age{ get {return DateTime.UtcNow - DateOfBirth;}
    

    New way

    public Timespan Age => return DateTime.UtcNow - DateOfBirth;
    

     
    For Methods
    Old way

    public int GetName() {return "Joe";}
    

    New way

    public int GetName() => "Joe";
    
  •  

  • nameof
    Old way
    Use string literal; expression tree, or [CallerMemberName] attribute
    New way
    nameof(propertyName)
  •  

  • Using Static
    Old way

    Math.Sin(x)
    SomeEnum.EnumName
    

    New way

    using static System.Math;
    using static SomeEnum
    ...
    Sin(x)
    EnumName
    
  •  

  • String Interpolation
    $”{SomePropertyOrExpression} …”
  •  

  • Nullability
    Null Conditional Operator
    Old way

    return a!=null && a.b!=null && a.b.c=="abc";
    

    New way

    return a!.b!.c=="abc";
    

     
    Event Handlers
    Old way

    var handler = eventHandler;
    if (handler !=null) {handler...}
    

    New way

    eventHandler?.Invoke...
    
  •  

  • Exception Filters
    catch(WebException e) when(e.Status == ...)
    

Custom MVC Model Binder

When you expect data in non-standard way and you want it to magically bind to your model, custom model binders could be a way to go.

Let’s say we want to post xml data to our controller method and we have a model for it.

public class XmlModel
        {
            public int Number { get; set; }
        }

Which we want to accept in our controller method:

public ActionResult Xml(XmlModel xmlModel)
        {
            return Content(xmlModel.Number.ToString());
        }

Now, let’s add our xml binder:

public class XmlModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var modelType = bindingContext.ModelType;
            return new XmlSerializer(modelType).Deserialize(controllerContext.HttpContext.Request.InputStream);
        }
    }

And XMLModelBinderProvider:

public class XMLModelBinderProvider : IModelBinderProvider
    {      
        public IModelBinder GetBinder(Type modelType)
        {
            var contentType = HttpContext.Current.Request.ContentType;
            if (string.Compare(contentType, @"text/xml", StringComparison.OrdinalIgnoreCase) != 0)
            {
                return null;
            }

            return new XmlModelBinder();
        }
    }

Add the provider to our Application_Start method in the Global.asax:

ModelBinderProviders.BinderProviders.Insert(0, new XMLModelBinderProvider()); 

To test this we can use Composer from Fiddler:
http://localhost/home/xml
User-Agent: Fiddler
Content-Type: text/xml

Request Body:

<XmlModel>
<Number>42</Number>
</XmlModel>

If we add breakpoint in our controller, we should see 42 coming through in our model.

How to Find Column Causing “String or binary data would be truncated” Exception in Entity Framework 5.0.

I recently encountered an issue with Entity Framework when it would throw “String or binary data would be truncated. The statement has been terminated.” Since the query contained close to 80 fields, I needed an easy way to determine the culprit. Since I already had a class which inherits from DbContext, I added suggested try-catch block in my SaveChanges() override method:

public partial class MyContext : DbContext
	{
		public override int SaveChanges()
		{
			try
			{
				return base.SaveChanges();
			}
			catch (DbEntityValidationException ex)
			{
				foreach (var error in ex.EntityValidationErrors)
				{
					Console.WriteLine("====================");
					Console.WriteLine(
						"Entity {0} in state {1} has validation errors:",
						error.Entry.Entity.GetType().Name,
						error.Entry.State);
					foreach (var ve in error.ValidationErrors)
					{
						Console.WriteLine("\tProperty: {0}, Error: {1}", ve.PropertyName, ve.ErrorMessage);
					}
					Console.WriteLine();
				}
				throw;
			}
		}
	}

You have to make sure that you don’t set ValidateOnSaveEnabled to false. It is set to true by default, but sometimes it is useful to disable it to improve performance.