Tuesday 20 January 2015

Autofac

Basic Setup

Autofac is a nifty dependency injection container that comes as a PCL (Portable Class Library) so it can be used in Xamarin projects.

To set it up you need to build a container using the ContainerBuilder class:
 var containerBuilder = new ContainerBuilder();  
   
 containerBuilder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());  
 
 // Register Types
   
 _container = containerBuilder.Build();  
You can then register types like this:
 container.RegisterType<First>().As<IFirst>();   
To use the container to resolve objects you need to get a lifetime scope from it:
 using (var scope = _container.BeginLifetimeScope())  
 {  
   // Reslove Types  
 }  
You can then resolve types like so:
 var first = scope.Resolve<IFirst>();  
If you are using MVC/Web.Api you can add additional nuget packages that will enable constructor injection on your controllers!


Automatic resolution of concrete types

If you want the container to automatically resolve concrete types you can add this to the container builder. This will mean that if it can't find a registration and the type is a concrete (non-interface, non-abstract) class it will just new up the class and return it.
 containerBuilder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());  


Passing some parameters

You can pass in some parameters and the container will automatically resolve the non passed ones. This means you can have a constructor like this and still pass in some of the parameters and have the container resolve the others automatically.
 public Test(IFirst first, ISecond second)  
To pass in the IFirst parameter just do:
 var test = scope.Resolve<Test>(new TypedParameter(typeof(IFirst), first));  
This will then pass first in and create a new Second instance. 


delegate Factories

You can use a Func<T> as a factory, this will then pass in a function that will resolve instances from the container so you can create multiple instances.
     public NeedAFactory(Func<Test> factory)  
     {  
       _test1 = factory();  
       _test2 = factory();  
     }  


Delegate Factories with parameters

You can also add a Func that takes parameters and this will be passed in to the constructor of the class when it is constructed.
   internal class Parent  
   {  
     private IChild _child;  
   
     public Parent(Func<Parent, IChild> factory)  
     {  
       _child = factory(this);  
     }  
   }  
   
   internal class Child : IChild  
   {  
     private readonly Parent _parent;  
   
     public Child(Parent parent)  
     {  
       _parent = parent;  
     }  
   }  
When autofac creates the child class it will pass the varable specified in the parent (this).

Friday 9 January 2015

C# 6 (Part 2)

String Interpolation

String interpolation is a replacement/alternative to string.format.

 var name = "Rob";  
 var output = "Hello \{name}";  
   
 Console.WriteLine(output);  

This will output "Hello Rob"

This is quite a nice feature as I find the syntax a lot easier to read than string.format.

Resharper 9.1 does not support this yet and will highlight it as an error, but it still compiles and runs.

https://roslyn.codeplex.com/discussions/540869
https://roslyn.codeplex.com/discussions/570614

nameof Operator

Quick and easy way of getting the name of something
 Console.WriteLine(nameof(test));  // varable outputs: "test"
 Console.WriteLine(nameof(TestProperty));  // property outputs: "TestProperty"
 Console.WriteLine(nameof(MyClass.TestProperty));  // property of class outputs: "TestProperty"
 Console.WriteLine(nameof(System.Text));   // namespace outputs: "Text"
 Console.WriteLine(nameof(MyClass.Method));  // method outputs: "Method"

Another useful little feature for when you are setting things using reflection and don't want to use strings, you can use an expression tree but this is simpler and I assume more efficient.

Resharper 9.1 does not support yet but it still compiles and runs
https://roslyn.codeplex.com/discussions/570551

Expression Bodied Members

You can now define fields with lambda expressions.


 private int _total => _first + _second;  
 private static Program CreateProgram => new Program();  

Can also be used to define methods.

 public int Add(int x) => _number += x;  

Nice little feature for quick definition of simple methods.

Exception Filters
It is now possible to filter exceptions without affecting the stack trace.
 try  
 {  
   ThrowException();  
 }  
 catch (Exception e) if (e is InvalidDataException || e is InvalidOperationException)  
 {  
   // Handle it  
 }  

This can also be used (abused) to log exceptions.
 try  
 {  
   ThrowException();  
 }  
 catch (Exception e) if (Log(e))  
 {  
   // Handle it  
 }  
This seems to be an acceptable abuse of the feature as it is described in the language spec :)

Thursday 8 January 2015

Asp.net Mvc Image Helpers (Part 3)

Image helper with lazy loading

This article looks at creating a html helper to lazy load images using the jQuery lazy load plugin.
It follows on from 2 earlier articles on creating html helpers for image loading:


There are a few different ways of making an image lazy load, but this seems to be the simplest to get working I've found so far.

First of all you need to install the Lazy load plugin for jQuery (search "lazyload") using the Nuget package manager. There are 2 versions available, I used 1.8.4. You will also need some additional images for this part, a ajax style loading spinner (create your own here!) and a 1x1 pixel spacer image (create one or download from here).

First we will create the html helper that will generate the html code that lazy loads the image.

 public static MvcHtmlString LazyLoadImage(  
               this HtmlHelper helper,  
               string image,  
               string alternative,  
               int width,  
               int height)  
 {  
   var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);  
   var url = urlHelper.Action("ImageResize", "Image", new { image, width, height });  
   var spaceUrl = urlHelper.Action("Image", "Image", new { image = "spacer.gif" });  
   
   var html = String.Format("<div class='lazyWrapper' style='height:{0}px; width:{1}px'>", height, width);  
   html += String.Format("<img class='lazy' src='{0}' data-original='{1}' alt='{2}'/>", spaceUrl, url,  
               alternative);  
   html += String.Format("</div>");  
   
   return MvcHtmlString.Create(html);  
 }  
It uses the Image Controller re-size method created in part 2 of this series.

We create a div element to wrap the img element, this enables us to set the background of the div to the loading spinner element and easily center the spinner. We set the img tags src attribute to a single pixel transparent image so that it will not show until updated by jQuery lazy load. The data-original tag holds the image that we want to lazy load.

Done!

C# 6

Been digging in to some of the new C#6 features, a few examples/thoughts

Auto Property Initializers

Auto property initializers allow you to set the initial value without having  to do it in a constructor

 public string TestString { get; set; } = "Hello";  

This can also be used for get only properties

 public string TestString { get; } = "Hello";  

Seems like a non-static field cannot access a method to set the value:
 Cannot access non-static method 'GetString' in static context  

When changing the method to static it appears to work, interesting...
 public string TestMethodReturn { get; } = GetString();  
   
 public static string GetString()  
 {  
   return "Method";  
 }  

This appears to be because the property initializers are called before the constructor.

Think I will be using this stuff, especially setting the get only property. Nice little bits of syntactic sugar.

Constructor Assignment to get only Auto Properties

Does what it says on the tin,
 public string TestString { get; }  
 public Program()  
 {  
   TestString = "Hello";  
 }  

Also seems reasonably useful, though not sure if I will favour this or setting it on the property.

Static Using

Pretty simple, just imports the static methods for use without their class name.
 using System.Console;  
   
 WriteLine("Hello");  

Not sure if using this stuff will be a good idea as it may reduce readability, but then maybe there will be cases where this would be useful. Advise using with caution.

Dictionary Initializers

There is a new dictionary initialzer format, the old one like the following still works
 var dictionaryOld = new Dictionary<string, string>  
 {  
   {"first", "First"},  
   {"Second", "Second"},  
   {"Third", "Third"},  
 };  

The new format is as follows
 var dictionaryNew = new Dictionary<string, string>  
 {  
   ["First"] = "First",  
   ["Second"] = "Second",  
   ["Third"] = "Third",  
 };  

So why the new format, well the only reason that I can see is this allows you to use the new format initializer just by implementing a this property on your own class:
 public class MyCollection  
 {  
   private readonly Dictionary<string, string> _store = new Dictionary<string, string>();  
   
   public string this[string key]  
   {  
     get { return ""; }  
     set { _store[key] = value; }  
   }  
 }  

You can then use the new initializer when creating instances
 var custom = new MyCollection  
 {  
   ["First"] = "First",  
   ["Second"] = "Second",  
   ["Third"] = "Third",  
 };  

Think this stuff will be useful for people making custom collections, good to know it exists so that I can use it when necessary. Though i'm now not sure which initializer I should be using when initializing dictionaries...

Wednesday 7 January 2015

New Toys

Looks like there has been a load of new stuff for Visual Studio and .NET Recently. So I thought I would have a play. Link.

Visual Studio Ultimate 2015 Preview
Download and installation pretty standard, havent noticed anything exceptionally different, lambda debugging looks like it will be pretty cool. Will spend a bit more time playing with the features after I have played with C#6.
List of features

Roslyn (The new C# compiler platform)
Pretty easy to install in to a project just put open a console and type:
Install-Package Microsoft.CodeAnalysis -Pre
Roslyn Website

R#
New platform installer for 9.1 picked up vs2015 and installed, works fine. Looks like some of the c# 6 support is already added as it suggests adding the ?. (Null Propagation) operator.
Resharper Platform Installer

C# 6
Tried out some of the new features including Null propagation, using Static Members ,auto Property Initializers,Getter only auto properties,Exception Filters. Lots of fun :) hopefully will have time to look at a few of these more in depth.

Here is a list of c#6 features:
















FeatureExampleC#VB
Auto-property initializerspublic int X { get; set; } = x;AddedExists
Getter-only auto-propertiespublic int Y { get; } = y;AddedAdded
Ctor assignment to getter-only autopropsY = 15AddedAdded
Parameterless struct ctorsStructure S : Sub New() : End Sub : End StructureAddedAdded
Using static membersusing System.Console; … Write(4);AddedExists
Dictionary initializernew JObject { ["x"] = 3, ["y"] = 7 }AddedNo
Await in catch/finallytry … catch { await … } finally { await … }AddedNo
Exception filterscatch(E e) if (e.Count > 5) { … }AddedExists
Partial modulesPartial Module M1N/AAdded
Partial interfacesPartial Interface I1ExistsAdded
Multiline string literals"Hello<newline>World"ExistsAdded
Year-first date literalsDim d = #2014-04-03#N/AAdded
Line continuation commentsDim addrs = From c in Customers ' commentN/AAdded
TypeOf IsNotIf TypeOf x IsNot Customer Then …N/AAdded
Expression-bodied memberspublic double Dist => Sqrt(X * X + Y * Y);AddedNo
Null propagationcustomer?.Orders?[5]?.$priceAddedAdded
String interpolation$"{p.First} {p.Lastis {p.Ageyears old."Added*Planned
nameof operatorstring s = nameof(Console.Write);Added*Planned
#pragma#Disable Warning BC40008AddedAdded
Smart name resolutionN/AAdded
ReadWrite props can implement ReadOnlyExistsAdded
#region inside methodsExistsAdded
Overloads inferred from OverridesN/AAdded
CObj in attributesExistsAdded
CRef and parameter nameExistsAdded
Extension Add in collection initializersAddedExists
Improved overload resolutionAddedN/A
Source

Xamarin
At first the Xamarin project templates did not appear, but I updated Xamarin studio to v 3.9 (In the alpha/Beta Channel) which features Visual Studio 2015 support and the templates appeared.

Looks like there is lots of fun ahead for .net!