Friday, February 8, 2013

Connecting to a HiTechnic prototype board to an Arduino

Connecting to a HiTechnic prototype board to an Arduino.


If you are thinking to yourself, “ Wouldn't it be fun to take a prototype board from Hitechnic and connect it to my Arduino? I wonder if it is possible...” Well I am here to tell you that Yes, indeed it is possible, it is not only possible it works rather nicely, of course - HiTechnic doesn’t really support this and the NXT documentation doesn’t have a section called “Cutting a cable in half to connect it your Arduino” so it took a little research to make it it happen which is why I thought I would share this information with the world.


Step one - the cable 


I took a cable from my mindstorms kit and chopped one end off, I then took some nice stiff jumper wires and soldered them onto the ends so I had something that I could plug into the Arduino.

 Step two - What goes where. 


So the big question was what pins to plug it into on the Arduino. I have an Uno which means that pins A4 and A5 are the i2c SDA and SCL lines, of course power and ground and everything else is nicely labeled and documented on the Arduino,

Not so for the prototype board. Fortunately J1 was labeled on the board itself I then referenced the HDK (hardware developer kit) for the NXT. On page six there is a schematic of an input port pointing out what’s what. It’s a little backward because pin one is J7 in the drawing and the board is labeled J1 so don’t get confused (the wire closest to J1 is 6). However, the figure on page 6 doesn't tell you which is which regarding the SDA and SCL lines - I found that on page 9 the fourth bullet point if you want to see it for yourself.

Armed with this knowledge I took the plunge and plugged it into the Arduino and wrote some code which didn’t work! But nothing melted either so I guess it was a mixed bag.

Step Three - Where oh where is my i2c device? 


As it turns out HiTechnic provides a great page with the device address and the addresses for the various ports on the board etc, the only issue was that my device wasn’t at 0x10 like the site states, it was 0x08. This caused a lot of misery until I found this handy dandy bit of code to scan the i2c bus and tell you the location of anything it finds. Imagine this moment after hours of fighting with this wondering what I had done wrong / failed to understand / etc... etc.. I would go with, clouds parting to reveal the light and sounds of angels in chorus. Now I was in business.

Step Four - A simple sketch to print the version number, manufacturer and sensor type. 

Now that I could talk to the thing I just wanted to verify beyond a shadow of a doubt that is worked The following simple sketch just prints the information about the board over and over. It’s glorious.

Sunday, August 12, 2012

Making Qunit show passing tests all the time.

So I have recently started testing my JavaScript with Qunit. Yeah! I looked at Jasmine but I just liked QUnit better except for one thing. I wanted to see all the passing tests all the time. I mean you work hard to get all you code properly tested and structured you want some positive feedback right? Qunit doesn’t show your tests unless you fail – bah!

If you grab Qunit from GIT you can see that there is a config section at like, line 570 and this look like a great spot to have an option that would let you always show the passing tests in expanded form or whatever but there isn’t an option for this so I you need to add a hack for it.
At (or near) line 210 you will find the following.


That's it really - just save and you will have a screen full of happy positive feedback all the time.

I mean if you have like fatty 500+ scripts it might start to get to be too much but I just wanted people to know who to do this if the wanted the option.

Yeah!

Friday, July 20, 2012

Unit testing static methods when using Membership and ProfileBase in MVC 4

So you might be thinking that you want to use the Membership class and the ProfileBase class in Microsoft’s System.Web.Security and System.Web.Providers but then you also want to write unit tests as well so you decide to go stand in traffic instead once you are overcome by the plethora of static nonsense that is the design of these two classes. OK, so it isn’t that bad but it is frustrating however there are ways around it and I wanted to try and blog about some of those techniques in the hope that others won’t have to toil with as much frustration as I did when using these classes.

Backgound

Basically I wanted to find a clean simple way of making use of and extending Microsofts built in forms authentication. It’s easy to use, relatively secure and can save a lot of time and code, well sort of until you want to unit test. The ProfileBase class is great for extending profiles and adding custom properties so you don’t have to introduce a whole lot of redundant code. A good example of this is sites I have seen that have a “users” table in the asp.net authentication database then have some other “userinfo” table or something that you have to go do a second query on using the username once the user has logged in, this is bad because first off, it’s a second query and secondly you aren’t looking up the user using a primary key and third, it’s just extra work.

I won’t go into the details of using these two classes and setting up forms authentication there are lots of great blogs about that in the land of Google so I will let you figure that part out however I will tell you that I am using MVC 4 for this and if you user the internet project template it will set all of this up for you except the use of profileBase to create custom properties but again, it’s simple and Google has lots of howto’s on this subject.

Dealing with System.Web.security.Membership
This is the first pain in the ass, it is a static class with all static methods but this one isn’t really that hard to deal with – ProfileBase is a bigger pain because you have to inherit from it and it won’t work unless you implement certain static methods – In order to make Membership unit testable you need to do a few steps that aren’t that hard, just a little laborious. With that said I would like to postulate on the virtues of unit testing and why it is worth a little hard work to make sure your code is tested, essentially it is like this code that is unit tested doesn’t suck – code that doesn’t have unit tests is generally garbage hmm, that is all I have to say about that – Now enough digression, what do we need to do to make Membership testable?
  1. create an interface
  2. make the classes that call any methods from membership call the interface instead
  3. implant the interface – this is just a class that calls the static methods for you
  4. make sure that any classes you modified to use the interface get it injected at the time of construction
Hopefully you are reading that thinking, nothing to it but if you aren’t then I will go into a little more detail. First of all create an interface. I called mine IStaticMembershipService

Now that you have that you need to go to whatever classes that are calling any methods from the Membership class and first off – inject it into the ctor and secondly replace the calls with calls to your interface. Lets take an example before I show you some code. Lets say you created an out of the box MVC 4 internet app. There will be an AccountController that doesn’t have a ctor – well of course this means that it has a parameter less one but we all new that. You need to add a constructor that takes an argument and then assigns it to a private variable so you can make use of it, check out the following code snippet.

So you can notice in there I am also injecting an IProfileFactoryService too. I will get to that later. For the moment lets just concentrate on the IStaticMembershipSerivce, lets go look at how I called it.

Fairly simple right – instead of calling Membership.CreateUser I call my service which in production just uses the implementation I created that calls Membership for me, now in my unit tests I can easily mock the call the CreateUser and then verify it was called, which is what this is really all about making sure that our code does what it was supposed to do, i.e. call CreateUser(). So lets look at how I would mock and test this and then how the actual implementation works.

No lets look at the implementation of CreateUser() in my service…

So YES! There is a lot of code in that test and not a lot of code in my implementation – here is the thing, if you are saying “Why would I write twice as much code just to test that little bit of logic”? If that is the case, stop reading and go away please. If on the other hand, this makes sense to you then please – keep on reading.
Dealing with ProfileBase
So dealing with the ProfileBase class is a little harder. ProfilBase is nice because it always you to easily extend properties to users of you system, normally you would just get username and email if you used plain old vanilla .NET form authentication however if you create at class that inherits from ProfileBase you can easily add things like FirstName and LastName etc. Here is a great blog post that tells you all about it, http://weblogs.asp.net/jgalloway/archive/2008/01/19/writing-a-custom-asp-net-profile-class.aspx Real quick, take a look at my UserProfile class I want to have included in some tests.

Of course this becomes a massive pain in the ass when you want to test it because you have to implement GetUserProfile() as a static method otherwise it poops in its pants. Also you can’t mock the properties that you create. This situation caused me a little more frustration but essentially it boils down to the same thing as we did above with the Membership class. You need to once again create an interface and once again, inject it into your class you want to test, standard dependency injection. What confused me is what to do about the properties. There I created a method that in the implementation simply returns the properties for me. Here is the implementation.

Notice the properties? Instead of calling base[“PropertyName”] I use the built in methods SetProperty() and GetProperty(), I could have just as easily used the array like in the UserProfile class. Looking at them with Jetbrains decompiler you can see that in the end the just do that same this base[“SomeProperty”] – shrug – I don’t care. I have a working implementation so now I can test using the interface. So now in order to do that testing it is pretty much the exact same as the test for the account controller.

So yeah - there you go! When you boil it down it seems failry easy to get around this sort of crap but it was a little frustrating fighting with it at first so I thought I would post about it in hopes that someone else can find the information useful.
If you want a good resource on this topic take a look at http://www.manning.com/seemann/ it's a must read if you are into Dependecny Injection and you are serious about being able to create testable software.

Monday, October 17, 2011

Using callbacks with Moq to check state

Here is the scenario, I have a method that takes an object, however - nowhere in your CUT (class under test) can you publicly access this object to verify state the state of it. I run into this scenario a lot regarding view models, the view model exposes things that we need to look at and interact with as public properties but anything the user doesn’t interact with or see is private which can make testing a pain. Let’s look at an example of something we can easily test before we get to the problem.

[TestMethod]

public void SaveCommandGetsSetWhenConstructed()

{

//Arrange

var adapterMock = new Mock<INewOrderAdapter>();

adapterMock.Setup(x => x.DeclinedBuyItNowPartNumbers)

.Returns(new List<string>() { "12345" });

var vm = new PartDeclinedViewModel(eventAggregator, adapterMock.Object)

{

SelectedLineItems = new ObservableCollection<DeclineReasons>()

{

DeclineReasons.CONDITION

},

CommentsText = "Testing",

SelectedPartNumber = "12345"

};

//Act (done when the constructor is initialized)

//Assert

Assert.IsNotNull(vm.SaveCommand);

}

So - you have defined SaveCommand in your view model, it’s a public delegate command, I can easily write a test that verifies that I am setting the method when we call the constructor for our class. Look at the test below – it does just that,(there are a few things in the arrange portion of the test that are telling me my view model needs a little refactoring but ignore that for now).

Now that we have looked at that example, what if the method that the delegate command we are using for the SaveCommand calls something that changes a private property? Whatever it is isn’t visible to the user so we don’t have anything that is publicly accessible in the view model. We don’t need it. Except we want to test that our method does the right thing to this private object. We can use a callback to set a value to a variable that is scoped inside the test method and then call our asserts on the state of the object. Let me try to use some more examples.

When we create the view model in the test above you can see that a mock adapter is created. This mock adapter has methods we need to mock out using Mock.Setup(), this of course means we can make them do whatever we want them too. So instead of having adapter.Save(myType, myObject) do whatever it normally does (we aren’t testing that here). We can mock it to say “Take the variable that was passed in and put it in this local variable” – that is what the callback does. See the test below which does just that.

[TestMethod]

public void LineItemIdGetsSetIfExists()

{

//arrange

DeclinedPart declinedPart = new DeclinedPart();

var lineItem = new LineItem() {PartNumber = "12345", LineItemId = 555};

var currentSaleOrder = new CreateSalesOrder();

currentSaleOrder.LineItems = new List<CreateLineItem>() { (CreateLineItem)lineItem };

var adapterMock = new Mock<INewOrderAdapter>();

adapterMock.Setup(x => x.DeclinedBuyItNowPartNumbers)

.Returns(new List<string>() {"12345"});

adapterMock.Setup(x => x.CurrentSalesOrder).Returns(currentSaleOrder);

adapterMock.Setup(x => x.SaveDeclineReason(It.IsAny<DeclinedPart>())).

Callback((DeclinedPart x) => declinedPart = x);

var vm = new PartDeclinedViewModel(eventAggregator, adapterMock.Object)

{

SelectedLineItems = new ObservableCollection<DeclineReasons>()

{

DeclineReasons.CONDITION

},

CommentsText = "Testing",

SelectedPartNumber = "12345"

};

//Act

vm.SaveCommand.Execute();

//Assert

Assert.AreEqual(declinedPart.LineItemId, lineItem.LineItemId);

}

There you have it, now you look at the local variable (the one you created in your test method) and check that your method does what you wanted it to. People will point out that you can use things like private accessors for this task however I tend to shy away from those. They don't always seem to be reliable and they tend to make the tests more confusing - in my opinion of course. at any rate - this is just another nifty little trick for examining the state of something you don't necessarily have direct access to.

Monday, February 28, 2011

Musings on using a module catalog with Prism

anyone using prism is probably familar with the bootstrapper, the documentation defines the bootstrapper as a class responsible for initialization of an application built using Prism and if you dig into the code for it you will see lots of virtual methods that you can override when setting up your application, one of those is the CreateModuleCatalog(). There are several ways to initialize your modules but using an xaml file is incredibly convenient especially if you only want certain parts of your application to load under certain conditions. Where I work we recently decided to employ this feature so that we could load a subset of the application in the warehouse and not have the sales and other modules loading up at run time, on the flip side the warehouse module doesn't load when the sales team loads the application. The great part for the developer is you don't end up with multiple code bases, your core and infrastructure is shared in one application and different people see different parts of the app depending on what is in the ModuleCatalog.xaml file.

With that said I wanted to point out a little snafu I ran into when configuring the catalog and loading it from the xaml file. most of my modules loaded just fine however one of them was not playing nicely - I was pulling my hair out looking at the module properties and examining it with RedGate but it failed to load each time so I started digging through the prism code. I noticed that inside of ModuleInitializer there was a method called CreatModule and it was calling GetType - here is the line of code

Type moduleType = Type.GetType(typeName);

Then it was checking to see if the moduleType var was null and sure enough it was. That gave me the bright idea... Why not call getType on the module itself and stick that in a variable so I could copy and paste? That is exactly what I did. Actually I think I popped a message box but whatever, once I had the exact info from get type I copied an pasted that in to the ModuleCatalog.xaml file and all my problems where gone! What you are really looking for is the
AssemblyQualifiedName. Here is a screen shot.


The information you get from there goes in the ModulesCatalog.xaml - here is a screen cap.


Just to sum it up here is a quick screen of CreateModuleCatalog

Copying items to a output directory using post-build events

Certain times you are going to need to move things to some sort output directory after they are built, for whatever reason - maybe your program is looking for a list of modules that it will load when it fires up (you can do this with prism)?

It's easy to do, just go to the "Properties" for your project and select "Build Events". in the box titled "Post-Build event command line" enter your xcopy command. Somthing like this.


xcopy "$(TargetDir)PARTSFinderModule.dll" "$(SolutionDir)\MyProject\bin\$(PlatformName)\$(ConfigurationName)\DirectoryModules" /Y


That's it.

Friday, January 14, 2011

Styling the combox box in WPF


If you want to play with the style of the combo box in WPF the easiest thing to do is use expression blend, drag a combo box control onto you project then click, "Edit Template" -> "Edit a copy"... This will take the entire default template for the combox box and put it into your XAML file.



Now go to the XAML and you can grab the entire style and do whatever you like with it... I usually put things like this into a main poject under the solution, something like "shared" is a good name for the project... One thing that is important to note though is that you have to include a reference to the PresentationFramework.Aero assembly cause you will need the Microsoft.Windows.Themes namespace.

Followers