Moving House

I’m currently in the process of moving my blog from it’s old home of geekswithblogs to this new location, so please bear with me. I’ll be putting new posts here, and migrating my older ones as and when needed.

So – if you’re here and you expected to be at the old blog – you need to head over to: http://www.geekswithblogs.net/cskardon/

 

Migrating from NUnit to XUnit–SetupFixture fun

Originally posted on: http://geekswithblogs.net/cskardon/archive/2017/02/22/migrating-from-nunit-to-xunitndashsetupfixture-fun.aspx

So I was limited to a specific version of NUnit for various reasons, and needed to start being able to run ‘core’ tests, so I migrated to XUnit. Generally not a problem until I hit ‘SetupFixture’. XUnit has no concept of ‘SetupFixture’ and from what I can gather, won’t either (https://github.com/xunit/xunit/issues/111).

So, in order to get the same approach, I need to implement ‘IClassFixture<T>’ on every test class. I could do this by going through each 1 by 1, but then how can I ensure that another developer (or even me!) remembers to do it the next time? For example, creating a new test class. In fact the reason for the SetupFixture was entirely because you can’t assume someone will derive or implement an interface.

In the end, I took the approach of adding another test to my code to ‘test the tests’ ensuring that each test class implemented IClassFixture. The code is below, tweak to your own needs!

[Fact]
public void AllClassesImplementIUseFixture()
{
    var typesWithFactsNotImplementingIClassFixture =
       //Get this assembly and it’s types.
        Assembly.GetExecutingAssembly().GetTypes()
        //Get the types with their interfaces and methods
        .Select(type => new {type, interfaces = type.GetInterfaces(), methods = type.GetMethods()})
        //First we only want types where they have a method which is a ‘Fact’
        .Where(t => t.methods.Select(Attribute.GetCustomAttributes).Any(attributes => attributes.Any(a => a.GetType() == typeof(FactAttribute))))
        //Then check if that type implements the type
        .Where(t => t.interfaces.All(i => i != typeof(IClassFixture<OriginalSetupFixture>)))
        //Select the name
        .Select(t => t.type.FullName)
        .ToList();

    if (typesWithFactsNotImplementingIClassFixture.Any())
        throw new InvalidOperationException(
            $”All test classes must implement {nameof(IClassFixture<O
riginalSetupFixture>)}{Environment.NewLine}These don’t:{Environment.NewLine} * {string.Join($”{Environment.NewLine} * “, typesWithFactsNotImplementingIClassFixture)}”);
}

Managed Application Framework – Part 2 – Basic Versioning!

Soooo… A post from a while ago covered the basic Managed Addin Framework (MAF from here-in) and how to set up a basic addin with host and pipeline.

One of the big problems of an Addin situation is if we change the contract between our Addins and our host. This can happen for a number of reasons – added functionality, removed functionality, the dreaded security etc… So, we change our contract and OH NOES! break all the AddIns we’ve carefully nurtured to maturity.

Luckily the guys who developed the MAF have come up with a solution to this, and it all lies with the pipeline………

Previously we had the IHelloMAF contract:

[AddInContract]
public interface IHelloMAF : IContract
{
string HelloMAF();
}

Obviously this gives us a limited set of functionality, so lets add a little bit more:

[AddInContract]
public interface IHelloMAF : IContract
{
string Hello(string name);
}

This will give us the power to accept inputs! Of course, this is just the contract, the detail is in the actual implementation itself.

If I simply update the contract and rebuild the pipeline, then my previously created AddIn will stuff up as it implements the old contract, I would have to change the AddIn to implement the new version, but I don’t or maybe can’t do that.

What does that mean for the development? Basically, we need to create another adapter, one to convert version 1 addins to work as a version 2 addin. To do this, we use the Pipeline builder, it saves a lot of time and effort in the long run. We need to be able to tell the Pipeline builder that, actually, generate a new AddInView, not overwrite the existing one. To do this, we reference in the PipelineHints dll (this is in the location you installed the PipeLine builder – in my case: C:\Program Files\Microsoft\Visual Studio Pipeline Builder\PipelineHints.dll).

Once we have the hints dll referenced we can go to our Contract file and put the following in:

[assembly: PipelineHints.SegmentAssemblyName(PipelineHints.PipelineSegment.AddInView, “AddInView2”)]

** Put this ABOVE the namespace declaration (if you have one)!! **

What this effectively does is force the Pipeline builder to create the AddInView segment for this contract, but name it ‘AddInView2’ rather than it’s default ‘AddInView’.

If we now run the Pipeline builder, we will generate some new projects, including ‘AddInView2’, note – the ‘AddInView’ project is still there, aces!

After this we need to update the host to cope with the new contract (** IF we changed the contract name, if we didn’t then no updates required **), should be pretty simple.

We can then create a new AddIn, based off of the new contract, and once we’ve done that, run the host and load up our new AddIn. All should be working!

But the version 1 addin isn’t showing – this is expected at the moment. The pipeline builder has only created a pipeline for the new style of Addin. What we need to develop is a v1 addin to v2 addin adapter. The easiest thing to do is copy from the AddInSideAdapters project.

We create a new Class Library project, calling it something like AddInV1ToV2Adapter, which gives us a good start point.
Add in references to:
System.AddIn
System.AddIn.Contract
AddInView (the version 1 addin!)
Contracts
(Again, Copy to local = FALSE!!)

Then opening the AddInSideAdapters project, copy the IXXXViewToContractAddIn.cs contents and paste them into your ‘Class1.cs’ file. Now we just need to edit the code to do our translation, so.. first things first, rename the class, doesn’t really matter what it’s called!

You should find the only thing you really need to change is the implementation of the methods, so in our example, we’d have:

public virtual string Hello(string msg)
{
return _view.HelloWorld();
}

Rebuild the entire solution and run the host… Now our host detects 2 AddIns, which is perfect!

I would attach the code to this post, but my blog host doesn’t allow attachments at the moment, I am in the process of looking into this!
If you want it, please email me: cs7kardon [-=At=-] xc7lave . c7o . uk (remove the ‘7’s and compress!)

Pulsy Button

After much umming and ahhing, and developing several versions of BrokeyButton I have the first cut of the PulsyButton.

What is PulsyButton? Well, it’s a button – that pulses. By pulsing I mean that it ‘pulses’ between the Background colour and a ‘PulseColour’ (that you set!).

Pulsy Button

Easy usage:
<PulsyButton Content="Hello" BackgroundColor="LightGray" PulseColor="Red" IsPulsing="True"/>

Obviously if IsPulsing is set to false then the button won’t pulse.
As it’s just based off the ‘Button’ base class, you can literally insert it wherever you have a Button, and all your styles etc will work fine.

I have plans to add more properties, and will over time:
* PulseTime — A TimeSpan for the pulse.
* PauseTime — A TimeSpan to pause the pulse for, i.e. pulse-paaaaauuuuusssseeeee-pulse etc

Also plans to fix some problems:
* Use StoryBoard and set the Background property directly
* Get rid of BackgroundColor property, so only Background is needed

Erm, can’t think of others at the moment.


Bit more detail -> What have I done?

Well, I had a lot of trouble getting a StoryBoard to work programmatically, I don’t know why, and I will perservere. But in the mean time, I’ve resorted to just a simple ColorAnimation.

How have I used a ColorAnimation with a Background brush?

Well, first I created a DependencyProperty:

public static readonly DependencyProperty BackgroundColorProperty
= DependencyProperty.Register( "BackgroundColor", typeof( Color ), typeof( PulsyButton ),
new UIPropertyMetadata( BackgroundColorChanged ) );

private static void BackgroundColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
PulsyButton pb = (PulsyButton) d;
pb.Background = new SolidColorBrush( (Color) e.NewValue );
}

This was my ahem workaround to the setting of the Background property directly, as the ColorAnimation will only animate Color properties (i.e. target the SolidColorBrush.Color property for the brush). By the by, it was the targeting of that property that caused me much hassle.

Anyhews, once we’re there, we should also have a PulseColor property (yes I know colour should have a ‘u’ in it, but I’ve gone all americanized :))

public static readonly DependencyProperty PulseColorProperty
= DependencyProperty.Register( "PulseColor", typeof( Color ), typeof( PulsyButton ),
new UIPropertyMetadata( PulseColorChanged ) );

public Color PulseColor { get { return (Color) GetValue( PulseColorProperty ); } set { SetValue( PulseColorProperty, value ); } }

private static void PulseColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
PulsyButton pb = (PulsyButton) d;
pb._pulseAnimation.To = (Color) e.NewValue;
}

Here I’ve included the PulseColor property, rest assured there is a BackgroundColor property as well. So, now we have the two colours to animate between, Background -> Pulse -> Background… We just need to create the animation.

private readonly ColorAnimation _pulseAnimation = new ColorAnimation();

There’s no need to recreate it, so it’s a readonly member. But when do I set this bad boy up? Not the constructor – nooooo, the colour properties won’t have been set up at that point, so I’ve gone for a ‘Loaded’ event consumer.

public PulsyButton()
{
Loaded += PulsyButton_Loaded;
}

private void PulsyButton_Loaded( object sender, RoutedEventArgs e )
{
_pulseAnimation.From = BackgroundColor;
_pulseAnimation.To = PulseColor;
_pulseAnimation.Duration = new Duration( TimeSpan.FromSeconds( 1 ) );
_pulseAnimation.AutoReverse = true;
_pulseAnimation.RepeatBehavior = RepeatBehavior.Forever;


this.BeginAnimation( BackgroundColorProperty, _pulseAnimation );
}

The animation will now begin, and the pulsy fun is nearly there!
But wait… what about turning pulse on/off?

All that is done in the IsPulsingChanged property:

private static void IsPulsingChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
bool isPulsing = (bool) e.NewValue;
PulsyButton pb = (PulsyButton) d;
if( !isPulsing )
{
pb._pulseAnimation.RepeatBehavior = new RepeatBehavior( 0 );
pb.BeginAnimation( BackgroundColorProperty, pb._pulseAnimation );
}
else
{
pb._pulseAnimation.RepeatBehavior = RepeatBehavior.Forever;
pb.BeginAnimation( BackgroundColorProperty, pb._pulseAnimation );
}
}

Now, I’m not 100% sure this is the correct way to do this, in fact I’m certain it’s not. However, it does work, which at the moment is what matters.

So there you have it, a button that pulses.

——————=====================———————–

Can’t attach the code to the post, so gonna have to past it here, sorry!!

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

public class PulsyButton : Button
{
private readonly ColorAnimation _pulseAnimation = new ColorAnimation();

public readonly DependencyProperty IsPulsingProperty
= DependencyProperty.Register( “IsPulsing”, typeof( bool ), typeof( PulsyButton ),
new UIPropertyMetadata( IsPulsingChanged ) );

public bool IsPulsing
{
get { return (bool) GetValue( IsPulsingProperty ); }
set { SetValue( IsPulsingProperty, value ); }
}

private static void IsPulsingChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
bool isPulsing = (bool) e.NewValue;
PulsyButton pb = (PulsyButton) d;
if( !isPulsing )
{
pb._pulseAnimation.RepeatBehavior = new RepeatBehavior( 0 );
pb.BeginAnimation( BackgroundColorProperty, pb._pulseAnimation );
}
else
{
pb._pulseAnimation.RepeatBehavior = RepeatBehavior.Forever;
pb.BeginAnimation( BackgroundColorProperty, pb._pulseAnimation );
}
}

public static readonly DependencyProperty PulseColorProperty
= DependencyProperty.Register( “PulseColor”, typeof( Color ), typeof( PulsyButton ),
new UIPropertyMetadata( PulseColorChanged ) );

public Color PulseColor { get { return (Color) GetValue( PulseColorProperty ); } set { SetValue( PulseColorProperty, value ); } }

private static void PulseColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
PulsyButton pb = (PulsyButton) d;
pb._pulseAnimation.To = (Color) e.NewValue;
}

public Color BackgroundColor
{
get { return (Color) GetValue( BackgroundColorProperty ); }
set { SetValue( BackgroundColorProperty, value ); }
}

public static readonly DependencyProperty BackgroundColorProperty
= DependencyProperty.Register( “BackgroundColor”, typeof ( Color ), typeof ( PulsyButton ),
new UIPropertyMetadata( BackgroundColorChanged ) );

private static void BackgroundColorChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
PulsyButton pb = (PulsyButton) d;
pb.Background = new SolidColorBrush( (Color) e.NewValue );
}

public PulsyButton()
{
Loaded += PulsyButton_Loaded;
}

private void PulsyButton_Loaded( object sender, RoutedEventArgs e )
{
_pulseAnimation.From = BackgroundColor;
_pulseAnimation.To = PulseColor;
_pulseAnimation.Duration = new Duration( TimeSpan.FromSeconds( 1 ) );
_pulseAnimation.AutoReverse = true;
_pulseAnimation.RepeatBehavior = RepeatBehavior.Forever;

this.BeginAnimation( BackgroundColorProperty, _pulseAnimation );
}
}

Managed Application Framework – Part 1 – The Beginnings!

Last week I was tasked with developing a new App for the guys I work with, (not a developers app you understand, but for actual normal users!!! Luckily it puts me smack bang where I work best – developing functional, extendable (and most importantly) Windows based apps. I’m now officially in my comfort zone!

The main difference between this app and previous apps I’ve done is the customer, normally I’m the person who writes that software tool that the other devs or system admins will use, so I can cram in shed loads of functionality and what I think are cool UI’s – usually involving liberal use of the SandDock tools (http://www.divelements.com/). This time because the users are non-expert users I’m having to really consider the design of the UI, and it is (in this case) very important – one of the specs of the app is: ‘It has to look cool’.

There is actually a reason for it to look cool – because we need it to impress management to get the go-ahead to redo an older app. Up side of this is that it’s going WPF. Aces!

Woah, I appear to have got a little bit sidelined.. I actually started this post to talk about the Managed Add-In Framework (MAF) of .Net 3.5. The MAF is a framework for using Add-In’s (or plugins as some apps call them) within .NET, but without the hassle of writing your own code to do the cool stuff (reflecting to load dlls etc).

As it happens MAF fits very nicely into the app I’m designing at the moment, so I’ve been playing around with it for a week or so now, and I have to say, I’m very impressed, the design of the MAF has been extremely well thought out, and covers a hell of a lot!

What does MAF consist of? Basically 3 broad parts, Host – Pipeline – Addin, of which the pipeline can be broken down into: HostView – HostAdapter – Contract – AddInAdapter – AddInView. The reason this is important is that the pipeline seperates the Host and AddIn from being dependent on the Contract (which in a later post will prove to be incredibly useful).

In this post (below) I’m going to explain how to set up a simple quick MAF application, just to get the swing of things, so.. without further ado: the MAF.

Firstly it’s important to know that the MAF requires a certain folder structure to work, (I think it requires it, every example, sample etc I’ve seen has it!). The structure can be seen on MSDN at: http://msdn2.microsoft.com/en-gb/library/bb384240.aspx – This is why I’ve put the fact that you need to set the output folders in the properties for projects created to point to a non-default location.

We begin creating a MAF project with a Class Library project we’re gonna call ‘Contracts’. In it we define the contract we intend to make all our Add-Ins implement.

  1. New Class Library – ‘Contracts’, set the Build Output to be: ..\Output\Contracts
  2. Add references to: System.AddIn and System.AddIn.Contract
  3. Define new interface, which must implement the IContract interface, and have the AddInContract attribute.


[AddInContract]
public interface IHelloMAFContract : IContract
{
string HelloMAF();
}

  1. Build the one project, all ok? Good, let’s mosey on!
  2. Get and install the Pipeline builder (open source) from codeplex: http://www.codeplex.com/clraddins
    (All the instructions are on the interweb at that site).
  3. Run the Pipeline builder and create the pipeline, this creates the 4 extra projects (HostView, AddInView, AddInSideAdapters and HostSideAdapters projects). This saves us the time of writing this code ourselves (which involves quite a lot of code repetition).
  4. Build the solution, you should have 5 projects now. Assuming that went ok, lets carry on.
  5. Create an Add-In —
    a) Add a new Class Library project to the solution, call it something like ‘AddInV1’
    b) Set the build output location to be: ..\Output\AddIns\V1
    c) Reference in the AddInView DLL which will be in the Output\AddInView directory.
    Set this reference’s ‘Copy to local’ property to ‘FALSE’.
    d) Reference in System.AddIn
    e) Edit the class file and create the code to implement the IHelloMAF contract:


[AddIn("AddInV1", Version="1.0.0.0")]
public class AddInV1 : IHelloMAF
{
public string HelloMAF() { return "Hello MAF!!"; }
}

In this code we’ve attached the ‘AddIn’ attribute, which takes a name (which can’t have spaces) and then a set of named properties (intellisense is your friend here). Also of note is that in our ‘Contracts’ project we called the contract: IHelloMAFContract, whereas here we’re using IHelloMAF. The code does nothing impressive, just returning a string.

  1. Build the solution, if you look in your output folder you should now have a \Addins\V1 directory with the dll in it. That’s the Add-In created.

  2. Now we’re going to create a host to actually run the Addins
    a) Create a new Console Application (call it something memorable, ‘host’ for example :))
    b) Reference the HostView dll (copy to local = false) and the System.AddIn dll.
    c) Set the build output location to: ..\Output
    d) In the Program.cs file, put in the following:


public static void Main()
{
string path = Environment.CurrentDirectory;
//Update the AddInStore looking for the AddIns.
AddInStore.Update(path);

//Get the tokens from the AddInStore.
Collection tokens = AddInStore.FindAddIns(typeof(IHelloMAF), path);

Console.WriteLine("Found " + tokens.Count + " addins, activating them....");

foreach(AddInToken token in tokens)
{
//Activate a given token.
IHelloMAF addin = token.Activate( AddInSecurityLevel.Internet );
Console.Write( "\tAddin: " + token.Name + ", version: " + token.Version + " --> " );
Console.WriteLine( addin.HelloMAF() );
}

Console.WriteLine();
Console.WriteLine( "Fin. Press ENTER to exit." );
Console.ReadLine();
}

What we have here are 3 main points, firstly where we do: AddInStore.Update(path); We’re telling the AddInStore to update itself and look for AddIns with the given root path.

Next point is the AddInStore.FindAddIns(typeof(IHelloMAF), path); line, which basically asks the AddInStore to find the AddIns available of a given type.

The final point is the activation of the AddInToken – token.Activate( AddInSecurityLevel.Internet );. At this point we’re activating the Add-In, and in the next lines calling methods on it.

  1. Build the solution.
  2. Start debugging (F5).

Running this should now give us:

> Found 1 addins, activating them....
> Addin: AddInV1, version: 1.0.0.0 --> Hello MAF!!
> Fin. Press ENTER to exit.

That’s the basic Host Pipeline AddIn structure, and will provide you with a good basis, the next step is to consider what to do in the event that we want to change the contract…

Printing a word document from C# – how the **** do you change the paper type???????

You wouldn’t have thought it would be that hard to print word documents from within C# – hook up the project to the Word Interop dlls – open the document and print. Easy.

In fairness – a lot of it is like this – and setting up a printer is pretty easy;

PrintDocument pd = new PrintDocument();
pd.PrinterSettings.PrinterName = printerName;
word.ActivePrinter = printerName;
word.PrintOut(....)

Even selecting a given tray is manageable – either via the ‘WdPaperTray’ enum – or even searching for it via a string.
But try as I might – I cannot find a way to change the paper type – and by that I mean from ‘Plain’ to ‘Preprinted’.

The basic problem is that I need to print to (say) ‘Tray 1’ which contains ‘Preprinted’ paper – and is set up as so on the printer. Attempting to print a plain paper printout gets stuck at the printer with a Paper type is mismatched error – which is fair enough.

Does anyone know how to do this????