Author Archives: purpleblob

Creating Local Packages with NuGet

NuGet allows us to download and install packages to our solutions using the NuGet manager in Visual Studio (or from the command line using nuget.exe) from a remote server – for example, nuget.org. But what if you want to host your own packages locally or remotely (outside of nuget.org) for example due to workplace policies or simply not wanting to publish your own libraries to a public server.

All the information contained in this post was gleaned from the references below. These are fantastic posts and I would urge anyone visiting this site to go and read those resources. What I want to do here is just distill things down to some basics to remind myself how to quickly and easily reproduce packages and spec for packages

Getting Started

Let’s start of by creating a local (i.e. on your development machine) NuGet package folder.

  1. Simply create a folder on your machine which will be used to store your packages, let’s call it LocalPackages
  2. In Visual Studio 2012, select Tools | NuGet Package Manager | Package Manager Settings
  3. In Package Sources you’ll see the nuget.org source, click the + button, give your source a name such as “Local Feed” and set the Source to the location of your LocalPackages folder
  4. Press OK and we’ve now added a new package source

At the point we now have Visual Studio set up to read from our packages folder – now we need to create some packages.

Creating a package

So we need to create a nupkg file (which is basically a compressed file which includes binaries and configuration – change the extension to .zip and open with your preferred zip editor/viewer to see the layout). This can be created using the Package Explorer GUI or via a nuspec file and nugget.exe.

If you don’t already have it, download and install the command line version of NuGet which can be found here see Command Line Utility. I placed mine in the folder I created previously, LocalPackages, as I will run it from here to work with the nupkg files etc.

As I prefer to let tools do the heavy lifting for me, I’ve downloaded the clickonce application, Package Explorer GUI.

With the package explorer we can easily create nupkg files without a care in the world for what’s inside them :)

So let’s create a package very quickly using the Package Explorer GUI

  1. If you haven’t already done so, download/run the Package Explorer Gui
  2. Create a new package
  3. We can now edit the meta data or meta data source from the UI – the metadata editor gives us, a simple GUI with input fields and the meta data source is basically an text editor (well it’s a little better than that but you get the idea). For now let’s stick with the GUI meta data editor with it’s nice input fields
  4. Enter an Id – this is the package name, it’s the name used when installing the package
  5. Supply a version. NuGet allows us to download specific package versions. The version should be in the format 1.2.3
  6. Now supply a human friendly title, if none is supplied the Id is used instead
  7. Now enter a comma separated list of authors
  8. I’m not going to step through every UI element here – check out the Nuspec Reference for a complete list of fields and what’s expected
  9. We can add any framework assemblies and both dependencies and assmebly references via the GUI, but also we need to actually add our assemblies, i.e. what the package has been created to deploy. We drag and drop those into the right hand pane of the GUI tool
  10. We can right click on the right pane to add files and folders and more, all of which are a little beyond this first post
  11. For now just drag and drop an assembly you wish to package and accept the defaults
  12. Save the nupkg file to the LocalPackages folder

If you now attempt to open this nupkg file, you’ll find it’s a binary file. If you prefer you can save the file as a nuspec (An XML file) via the GUI using the File | Save Meta data as… option and then when you are ready you can use

NuGet Pack MyPackageName.1.0.0.nuspec

However you may well find that this fails because the assemblies added may need updating to the actual locations on your hard drive, so open the nuspc file and check the src paths. See the GUI made things easy.

Also when running the NuGet command line tool with Pack you may get a warning about the location of your assmebly, for example mine was by default stored in lib, but running the command line I find it is warning that I should move the file to a framework-specific folder.

For now we’ll not worry about this. Instead let’s see our nuget package being used.

Is our nuget package available

We can now open Visual Studio (if not already opened) and assuming you’ve added your local package as outlined previously.

  1. Go to Tools | NuGet Package Manager | Package Manager Console
  2. Your should see “Package source” in the console, select “Local Feed” or whatever name you gave for your local package location
  3. Type
    Get-Package -ListAvailable
    

    and you should see the package you created

Adding a local nuget package to our application

  1. Create yourself a new application to test your nuget package in
  2. Now we can add our package using the Package Manager Console, for example
    Install-Package MyPackage
    

    or from the References folder on your solution, right mouse click and select Manage NuGet Packages, from Online, select your Local Feed and select your packages as normal and install

Remote Packages

Check out the excellent post Hosting Your Own NuGet Feeds. The section on “Creating Remote Feeds” get’s you up and running in no time at all.

But let’s list the steps anyway

  1. Creating a empty web application
  2. Add the NuGet.Server package using NuGet
  3. Change the WebConfig packagesPath value to match the path to your packages
  4. Run the app – yes it’s that simple
  5. In Visual Studio 2012, select Tools | NuGet Package Manager | Package Manager Settings
  6. In Package Sources click the + button, give your remote source a name such as “My Package Feed” and set the Source to the URL of your server which you just created and ran

That’s is for now.

References

Nuspec Reference
Hosting Your Own NuGet Feeds
Using A GUI (Package Explorer) to build packages
Creating and Publishing a Package
Package Manager Console Powershell Reference

More Moq

In the previous post we touched on the fundamentals of using Moq, now we’ll delve a little deeper.

Please note, MOQ version 4.20 has introduced a SponsoreLink which appears to send data to some third party. See discussions on GitHub.

Verifications

So we can verify that a method or property has been called using the following

var mock = new Mock<IFeed>();

FeedViewModel vm = new FeedViewModel(mock.Object);
vm.Update();

mock.Verify(f => f.Update());

This assumes that the vm.Update() calls the IFeed.Update().

But what if we are passing a mock into a view model and we want to verify a method on the mock is called but we don’t care about the specific arguments passed into the method. We can do the following (this example uses the IEventAggregator in Caliburn Micro)

var eventMock = new Mock<IEventAggregator>();

PostListViewModel vm = new PostListViewModel(eventMock.Object);

eventMock.Verify(e => e.Subscribe(It.IsAny<PostListViewModel>()), Times.Once);

In the above example, PostListViewModel’s constructor is expected to call the Subscribe method on the IEventAggregator. The actual implementation passes this into the Subscribe method, but we’ll ignore the argument, except that we’re expecting it to be of type PostListViewModel. The It.IsAny() handles this and the Times.Once simply verifies the Subscribe method was called just once.

Fundamental Moq

Moq is a fabulously simple yet powerful mocking framework.

Please note, MOQ version 4.20 has introduced a SponsoreLink which appears to send data to some third party. See discussions on GitHub.

For those unaware of what a mocking framework are and what they have to offer check out Wikipedia’s Mock Object post.

Here’s the fundamentals for starting to use Moq…

Let’s start with a simple interface for us to mock out

public interface IFeed
{
   string Name { get; set; }
   bool Update(int firstNPosts);
}

Now to mock this interface we can simply create a mock object based on the interface, as follows

IMock<IFeed> mock = new Mock<IFeed>();

obviously this is of little use unless we can set up some behaviours, i.e. what happens when a property or method etc. is called. So in the case of this interface we might want to return a known string for Name like this

IMock<IFeed> mock = new Mock<IFeed>();

mock.Setup(f => f.Name).Returns("SomeUniqueName");

// now use the mock in a unit test
IFeed feed = mock.Object;
Assert.Equal("SomeUniqueName", feed.Name);

The code mock.Object gets the actual interface from the mock, i.e. in this case an IFeed.

For methods we do much the same thing

IMock<IFeed> mock = new Mock<IFeed>();

mock.Setup(f => f.Update(10)).Returns(true);

// now use the mock in a unit test
IFeed feed = mock.Object;
Assert.True(feed.Update(10));

The examples above are a little contrived, after all we obviously are not really going to test that the mock we setup, but instead want to test something that uses the mock.

For example, what about if we have a FeedViewModel which takes an IFeed for display via WPF, something like the following

public class FeedViewModel : PropertyChangedBase
{
   private IFeed feed;
   private bool showProgress;
   private string error;

   public FeedViewModel(IFeed feed)
   {
      this.feed = feed;
   }

   public string Name { get { return feed.Name; } }

   public void Update()
   {
      ShowProgress = true; 
      bool updated = feed.Update(10);
      if(updated)
      {
         Error = "Failed to update";
      }
      ShowProgress = false;
   }

   public bool ShowProgress
   {
      get { return showProgress; }
      set { this.RaiseAndSetIfChanged(ref showProgress, value); }
   }

   public string Error
   {
      get { return error; }
      set { this.RaiseAndSetIfChanged(ref error, value); }
   }
}

Now we can test our FeedViewModel by creating a mock of the IFeed and passing into the FeedViewModel, allowing us to set up mock calls and check our expectations in tests.

The previous examples showed how we can use mocks to setup return values or just take the place of methods when they are called. We may, however, also wish to verify that our code did correctly call our mock objects one or more times – we can do this by marking the set up as Verifiable and then Verify the mocks at the end of the unit test, as per the following

Mock<IFeed> mock = new Mock<IFeed>();
mock.Setup(f => f.Posts).Returns(posts).Verifiable();

FeedViewModel model = new FeedViewModel(mock.Object);
Assert.Equal(posts.Count, model.PostCount);

mock.Verify();

In this example posts is a list of Post objects. Our view model has a property PostCount which uses the list of posts. We want to verify that the Posts property on our (new extended IFeed) was actually called. So we mark it as Verifiable() and at the end of the test we use mock.Verify(); to verify it was actually called.

We can be a little more explicit with our verifications, for example if we expect a method to be called twice, we can verify this as follows

Mock<IFeed> mock = new Mock<IFeed>();
mock.Setup(f => f.Update()).Returns(true);

FeedViewModel model = new FeedViewModel(mock.Object);
// do something on the model which will call the feed Update method

mock.Verify(f => f.Update(), Times.Exactly(2));

So this will fail verification (with a MockException) if the Update() method is not called exactly 2 times.

We also may wish to raise events on the mocked object to see what happens in our object under test, for example assume we have a StatusChanged event on our IFeed which the FeedViewModel should subscribe to and change an Updating property upon the relevant event arguments

Mock<IFeed> mock = new Mock<IFeed>();
FeedViewModel model = new FeedViewModel(mock.Object);

mock.Raise(f => f.StatusChanged += null, 
       new StatusChangedEventArgs(StatusChange.UpdateStarted));
Assert.True(model.Updating);

mock.Raise(f => f.StatusChanged += null, 
        new StatusChangedEventArgs(StatusChange.UpdateEnded));
Assert.False(model.Updating);

In this code we’re raising StatusChanged events on the IFeed mock and expecting to see the view model’s Updating property change.

Using Common.Logging with Caliburn Micro

Caliburn Micro offers several extension points into it, one of which is for logging. For example

LogManager.GetLog = type => new MyLogManager(type);

LogManager.GetLog is a Func and allows us to supply our own logging mechanism.

As you can see, Caliburn Micro includes the interface ILog (the second generic parameter in the Func) for us to implement our own logging code. However I also rather like using the Common.Logging library to abstract the specific logger (i.e. NLog or log4net etc.) from my logging code. So how can we implement our logging using the Common.Logging ?

We just need to implement our own Caliburn Micro ILog and redirect it to the Common.Logging framework. For example

using CommonLogging = global::Common.Logging;
public class CommonLogManager : Caliburn.Micro.ILog
{
   private readonly CommonLogging.ILog log;

   public CommonLogManager(Type type)
   {
      log = CommonLogging.LogManager.GetLogger(type);
   }

   public void Error(Exception exception)
   {
      log.Error("Exception", exception);
   }

   public void Info(string format, params object[] args)
   {
      log.Info(String.Format(format, args));
   }

   public void Warn(string format, params object[] args)
   {
      log.Warn(String.Format(format, args));
   }
}

The code is a little convoluted with namespaces due to ILog existing in both Caliburn Micro and Common.Logging, but unfortunately being different types.

Now just place the following code into the Configure method on your implementation of a Caliburn Micro Bootstrapper

LogManager.GetLog = type => new CommonLogManager(type);

MahApps, where’s the drop shadow ?

In the MahApps Metro UI, specifically the MetroWindow we can turn the drop shadow on using the following. In code…

BorderlessWindowBehavior b = new BorderlessWindowBehavior
{
   EnableDWMDropShadow = true,
   AllowsTransparency = false
};

BehaviorCollection bc = Interaction.GetBehaviors(window);
bc.Add(b);

Note: We must set the Allow Transparency to false to use the EnableDWMDropShadow.

In XAML, we can use the following

<i:Interaction.Behaviors>
   <behaviours:BorderlessWindowBehavior 
      AllowsTransparency="False" 
      EnableDWMDropShadow="True" />
</i:Interaction.Behaviors>

Binding Ninject to an instance based upon the dependency type

I want to bind the Common.Logging.ILog to an implementation which can take a type argument as it’s parameter, i.e. We can use the Common.Logging.LogManager.GetManager method by passing a type into it, as per the following code

LogManager.GetLogger(typeof(MyType));

So how can we simply declare a dependency on our type to ILog and have it automatically get the logger with the type parameter.

The code speaks for itself, so here it is

IKernel kernel = new StandardKernel();

kernel.Bind<ILog>().ToMethod(ctx =>
{
   Type type = ctx.Request.ParentContext.Request.Service;
   return LogManager.GetLogger(type);
});

In the above code we bind to a method, thus we can dynamically handle the binding. From the IContext ctx we can find which type requested the binding and then use this in the call to GetLogger.

So with this the dependency object simply includes the following

public class MyClass
{
   // other methods, properties etc.

   [Inject]
   public ILog Logger { get; set; }
}

and everything “magically” binds together to get the logger with the type set to typeof(MyClass).

Dynamic Objects

The IDynamicMetaObjectProvider interface represents an object that can be late bound.

Microsoft supplies to implementations of this interface out of the box. DynamicObject and ExpandoObject.

DynamicObject

The DynamicObject is mean’t to be used as a base class for the user’s own dynamic object and hence has a protected constructor. The idea is that we can create our own dynamic object and handle any attempted access to member properties or methods etc. at runtime.

For example here’s an implementation of a dynamic object which adds (at runtime) a method which takes no arguments and returns a string

public class MyObject : DynamicObject
{
   public override bool TryGetMember(
            GetMemberBinder binder, out object result)
   {
      result = null;
      if (binder.Name == "GetName")
      {
         result = new Func<string>(() => "Hello World");
         return true;
      }
      return false;
   }
}

If we wanted to handle a property named GetName we’d simply return a string, not a function. The TryGetMember is used for methods with no arguments or get properties, when arguments are supplied to a method we should override TryInvokeMember.

ExpandoObject

Unlike DynamicObject an ExpandoObject can be instantiated and then we can add methods and properties to it via it’s IDictionary interfaces.

So for example, let’s create an ExpandoObject and add a new method

dynamic d = new ExpandoObject();

((IDictionary<string, object>)d).Add("GetName", new Func<string>(() => "Hello World"));

Console.WriteLine(d.GetName());

As you can see we must ofcourse declare our variable as dynamic otherwise the use of GetName will cause the compilation error

System.Dynamic.ExpandoObject’ does not contain a definition for ‘GetName’ and no extension method ‘GetName’ accepting a first argument of type ‘System.Dynamic.ExpandoObject’ could be found (are you missing a using directive or an assembly reference?)

We also need to cast the instance to IDictionary<string, object> as access to the Add method needs to go through an explicit interface.

So as you see, we can add to the ExpandoObject at runtime, unlike a DynamicObject derived class where only the derived class would be able to add to the object at runtime (obviously assuming we don’t add methods to allow this ourselves).

Dynamically loading assemblies into Caliburn Micro

I want to be able to load the views/viewmodel assemblies into Caliburn Micro dynamically, i.e. instead of adding references to them to the project….

Well, we’ve got two ways of loading assemblies (that I’m currently aware of). The first is via the Bootstrapper and the second can be handled pretty much anywhere. Both examples below are shown using the DLL name, but ofcourse we could take this further via configuration files, build out own attributes and so on, but I leave that decision to the user.

So through Bootstrapper simply overload SelectAssemblies, for example

protected override IEnumerable<Assembly> SelectAssemblies()
{
   string path = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location);
   return base.SelectAssemblies().Concat(
         new Assembly[] 
         { 
            Assembly.LoadFile(Path.Combine(path, "MyViews.dll"))
         });
}

However if you’re using a plugin approach, possibly where you allow the user to select a plugin DLL or the likes, then at the point you want to load the assembly you could write something like the following

string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assembly a = Assembly.LoadFile(Path.Combine(path, "Rabbit.Controls.dll"));
AssemblySource.Instance.Add(a);

The key here is the AssemblySource singleton and adding assemblies to the IObservableCollection Instance.

Binding to a listbox and selected item using Caliburn Micro

This will work with a listbox or combo box.

So, using Caliburn Micro we use convention based naming for the ItemsSource as follows

<ListBox x:Name="Employees" />

But as you see there’s nothing for SelectedItem, instead it is taken that the property name in the view model for the selected item will be SelectedEmployee, i.e.

public class EmployeesViewModel : PropertyChangedBase
{
   private EmployeeViewModel selected;

   public ObservableCollection<EmployeeViewModel> Employees { get; private set; }

   public EmployeeViewModel SelectedEmployee
   {
      get { return selected; }
      set
      {
         if (selected != value)
         {
            selected = value;
            NotifyOfPropertyChange();
         }
      }
   }
}

NinjectModules

NinjectModules allow us to define bindings in assemblies without the need to resort to passing around an instance of the IKernel.

So let’s look at an example. We have an EXE project and another project which contains the common interfaces used in the application. Let’s assume we have an IAdministrationSettings interface in the “common” project. The main application has classes and/or properties which have service dependencies on IAdministrationSettings.

Now we create a third project which will contain the implementations of the interfaces used in our application. So it’s got a reference to the common interfaces project/DLL but has no knowledge of the EXE and likewise the EXE has no knowledge of the implementation project.

So we want to now bind our implementation to the interface and have it automatically injected into our EXE.

In the implementation project we add the usual NInject references (or use NuGet to do it) and create a file, mines called Module.cs but the name doesn’t matter. Then we place the following code into the file

public class Module : NinjectModule
{
   public override void Load()
   {
      Bind<IAdministrationSettings>().To<AdministrationSettings>().InSingletonScope();
   }
}

We’ve declared a NinjectModule (there could be more than one) which define the bindings of our interface(s) to implementation(s), but we now need Ninject in the EXE to load these modules and hence allow it to bind the correct implementation, so we use the following code in the EXE

IKernel kernel = new StandardKernel();
kernel.Load("*.dll");

The above used the wildcard to load any/all DLL’s which have NinjectModules, alternatively we could store the implementations in “known” locations or ofcourse put the actual path to the DLL into this method.

Now Ninject will automatically handle the bindings.