Monday, 8 February 2016

PeanutButter is updated to NUnit 3

NUnit (https://github.com/nunit/nunit) has been updated to version 3 for a little while now, so I thought it best to move PeanutButter forward as the test utilities which use NUnit for assertions and such have required the user to explicitly install NUnit 2.6.4.

In particular, this will affect any new installations or updates to projects using the following:
  •  PeanutButter.TestUtils.Generic 
    •    Which includes PropertyAssert
  • PeanutButter.TestUtils.Entity
    • Which includes the helpers around testing database persistence of your entity models
What this means is:

  • If you’re not depending on any of these PeanutButter modules, of course nothing changes for you. Though I’d still recommend moving forward to NUnit 3 at some point when you have some time. There are some changes and some things to deal with, so don't rush it.
  •  If you have a project which is currently stable and not in active development, don’t bother updating anything unless you really want to stay up-to-date.
  •  If you’re going to install-package PeanutButter.<something>, you may find that you’re automatically updated to NUnit 3. Mostly, it’s not a problem and the differences are easy to work around. If you get a PeanutButter package with version 1.1.x instead of 1.0.x, you’re going with NUnit 3. If you don’t want to go this route, install the last 1.0.x version: 1.0.155. You may have to specify an NUnit version to install, ie:
    install-package NUnit –project <your project> -version 2.6.4.
    I used to make my packages not depend on specific versions of anything, but I’ve recently started adding minimum versioning to packages to try to alleviate some of this headache.


Friday, 30 October 2015

Razor views and publishing woes



If you've done any ASP.NET MVC work, especially in VS2015, you may have encountered this:

  •  You’re devving away on a controller and return View(withSomeNiftyModel).
  • You alt-enter or alt-. to get VS to create the view
  • You make some amazing html view. It has tags and content and everything!
  • You test the view using an F5 or Ctrl-F5 and it’s doing what you want and looking how you want (though your designer, who may or may not be named Jess, probably has sterner words about how it looks)
  • Some time later, you build a deployment package and upload to the client.
  • If the internet gnomes are with you, soon you will deploy at the client. If not, you’ll wait… and then deploy at the client
  • And then you get the dreaded “view not found error page”:







Well, you don’t have to continue with this sad existence. You could add this snippet to your web project’s .csproj file:

  <Target Name="EnsureContentOnViews" BeforeTargets="BeforeBuild">
    <ItemGroup>
      <Filtered Include="@(None)" Condition="'%(Extension)' == '.cshtml'" />
    </ItemGroup>
    <Error Condition="'@(Filtered)'!=''" Code="CSHTML" File="$(MSBuildProjectDirectory)\%(Filtered.Identity)" Text="View is not set to [BuildAction:Content]" />
  </Target>

(Place it after the ItemGroup which contains your views, if you’re looking for a spot to put it)

And then, voila! Your project doesn’t build unless all views are set to build action content:



Kudos to the solution here: http://stackoverflow.com/questions/27954267/make-sure-all-cshtml-files-are-set-to-be-content-for-build-action (though I’ve upgraded from a warning to an error, because, well, it should be).


Thursday, 29 October 2015

Please welcome PeanutButter 1.0.118!

 (if you don't know what PeanutButter is -- apart from a yummy spread and a rather silly name for an open-source project -- have a gander here: http://davydm.blogspot.co.za/2014/06/introducing.html)

What's new:
  • Updates to DatabaseHelpers:
    • Fluent syntax for conditions (.And() and .Or() extension methods)
    • EqualityOperators changes
      • Like_ is deprecated (but still functions). It is replaced by Contains, with the same functionality
      • Like is new: does not insert any wildcards -- that's up to you! (also, finally, has a reasonable name, now that I know how to use keywords as identifiers in VB.NET. Yes, the DBHelpers are written in VB.NET. Get over it.)
      • StartsWith: does what it says on the tin
      • EndsWith: also does what it says on the tin
    • Added ConcatenatedField for when you want some composite result from a few fields
    • Updated CalculatedField: All *Fields now implement IField, so all of the existing funcationality which SelectFields could give you can also be found for the others (conditions, etc)
  • Enumerable convenience functions
    • And() -- like Union() but produces an Array
      • eg new[] { 1, 2 }.And(3) is equivalent to new[] { 1,2,3}
    • ButNot() -- like Except(), but produces an Array
  • RandomGenerators:
    • RandomValueGen.GetRandomCollection
      • Takes a factory function and optionally min/max number of items
      • eg to get a random-sized IEnumerable<int> of random ints, do:
        RandomValueGen.GetRandomCollection(() => RandomValueGen.GetRandomInt())
    • RandomValueGen.GetRandomSelectionFrom
      • picks some random items from another collection
  • ExpressionHelper: 
    • GetMemberPathFor:
      use to get full property paths from lambdas, eg
      ExpressionHelper.GetMemberPathFor<Foo>(fooItem => fooItem.SomeProperty.SomeValue)
      gets you
      "SomeProperty.SomeValue"
      Useful for testing or somewhere where you need to get to properties dynamically
    • GetPropertyTypeFor:
      Similar usage to GetMemberPathFor, but returns the property type
  • Of course, there are some bugfixes
  • And probably other stuff I forgot... It's been a while since I tooted on the PeanutButter horn.
 Like other PeanutButter bits and pieces, these have been born out of a desire for convenience, cleaner code and/or getting the compiler to check stuff before hitting the runtime. I hope they benefit others -- I know that I use a little PB every day (:

As always, usage, source availability and distribution remain totally free.

Monday, 10 August 2015

Introducing... Splunk4Net!

 

One of the cool parts of working for Chillisoft is that we have time set aside by the company for learning and experimenting. We call those times "Intentional Learning" and "Deliberate Practice". Think "Google 20% time", but with a little more focus.

The last round has been focused on tinkering on projects of interest to people working at the company. One of my colleagues is working on using Unity to build a virtual world interface to a part of an existing product. Some others have worked on a Neo4J .NET connector. There are some cool things which emerge from these processes!

I had recently dealt with Splunk, a remote hosting for logging which not only provides a rich query language to deal with the collected data, but also provides graphing mechanisms for making your data come alive visually. They have many different pricing structures, starting at a free version which is probably enough to cover the needs of quite a few projects and teams, right up to enterprise editions which cope with high volumes of data and provide rich security features.

A lot of the .net world has already dealt with the great log4net library: an open-source logging framework which supports writing to a diverse plethora of targets, such as log files (with rotation even!), Windows Event Log and many, many more.

So log4net is cool, Splunk is cool -- how about making it easy to log to Splunk using known log4net skills?

Well, now you can, with Splunk4Net, which is available via nuget. Thanks to the community-oriented thinking at Chillisoft, this library is not only free as in beer, but you have full access to the source -- you can build it, you can change it, you can redistribute it.

I hope this provides some value to people looking to log to an external service, especially to be able to harvest valuable information from that logging. You could use this to keep on top of error conditions in your client code or websites. You could use this to gather metrics about application usage to guide further development. You could just use this as a diagnostic tool to figure out why client apps are falling over. How you use it is up to you -- feel free (:

Friday, 10 July 2015

Using an aging Android phone

I can't help it: I love Android. It has quirks. It has rough edges. It has a million versions and many of them are dead-end forks by vendors who just don't care. It also has Linux at it's heart, and, with a little nudging, it can act like it too...

I use a Samsung Galaxy S3 (i9300). This is quite blatantly "old tech" -- the S3 is well over 4 years old and Samsung, like most vendors, has long ago spurned it when it comes to the concept of OS updates. For a long time, CyanogenMod was the answer, until the fateful day that the i9300 maintainer decided he had a life and wanted to spend more time doing that.

Phooey. But, srsly, good for him and his family.

Still, that leaves the i9300 user in a pickle. CyanogenMod has quite a strict rule about what devices are supported: basically, there has to be a sanctioned maintainer for that device who is willing to take responsibility for it. With no maintainer, the i9300, one of the most popular handsets ever sold, started fading into obsolescence.

There were (still are) some rather hearty movements to revive CM on the i9300. I have followed at least two of them for a while, updating from them. Alas, they all appear to fizzle out over some time.

One supporting ROM which doesn't seem to be willing to let go of this dog just yet is Resurrection Remix. Yay for me. Unfortunately, RR is a conglomerate built from a number of sources including CM. I say "unfortunately", because this means that when something breaks, trying to get someone to care about it enough to fix it is not a trivial exercise. Don't get me wrong: I appreciate all the work the devs involved do (for free), so I can avoid paying for another device (and adding my iota to the e-waste that abounds -- whilst my phone lives, it shall work for me!).

But there are still some issues (including, but perhaps not limited to):
  1. The flashlight function works whilst the screen is on, but switches off when the screen is off );' This is common on most ROMs which support the i9300 and appears to come down to a philosophical choice on the part of CyanogenMod to flip the bird an i9300 users.
  2. The vibration intensity by default is so low that it's pointless. Again, I'm quite sure someone, somewhere is giggling about how absurd this is for i9300 users and muttering something along the lines of "just upgrade to a new device already". Fuck 'em.
As far as (1) goes, this is just accepted as a broken feature of the phone. I've seen quite a few people just throw their arms in the air and say "so what do you expect me to do about it?". For most people, it's probably insignificant -- but I use my phone every night as a flashlight and having to keep the screen on during use is, well, sub-optimal.
As for (2), many ROMs provide a mechanism to set this. RR has one -- but it has often crashed the Settings UI when I try to use it (depending on the build). So I got tired of that. I want updates, but I also want my phone's vibration to shake the very foundations of the universe when someone whatsapp's me an nsfw image.

So here's my little useless collection of shell scripts to fix this:https://github.com/fluffynuts/i9300_hax.git

So far, in there, you can find:
  1. toggle_flash.sh, which toggles the flash as a flashlight.
  2. v11.sh which "set vibration to 11", ala Spinal Tap. This sets your i9300 vibration to max (100%)
Both of these require root as they mess with stuff under /sys. Both are easier to run via $cripter. To use, clone somewhere and copy the scripts into the folder you've configured $cripter to use as a scripts home.

To use, I bind toggle_flash.sh to a double-tap on my home screen, via Nova Launcher (but I'm sure you can do this with other launchers or in other ways) and I set v11.sh to run at boot via Llama.

I hope this can help someone else with an i9300, especially if they are holding back on upgrades for the same reasons I am:
  1. Damn the man: I refuse to pay just to get a newer, shinier toy.
  2. The world has enough e-waste as it is. I'd like to be able to say to my boy someday that I did what I could to slow down the destructive nature of man, no matter how inconsequential my actions were.
 Any other useful hax that I contrive for this phone will end up there. Licensing is BSD ("if it breaks, you can keep both pieces"). You're welcome to use, distribute and mock. I don't care if you don't like it. I do care (a lot) if you do (:

Thursday, 9 July 2015

Callbacks suck

Problem: Javascript is essentially run on one thread and some things take time, blocking other requests.
Solution: make everything asynchronous and provide a callback mechanism.
Problem: I now have plenty of asynchronous calls which come back to a callback which does another async call and so on and so forth. Since I didn't really think this through to start with (!!), I now have something like:


This code is an unmaintainable mess and something has to be done about it.


There are a few ways to slay this beast:

#1 Refactor
You could refactor your code to pull out methods and reference those. Chances are you end up with something a little spaghetti-like: now you have all these neat little functions but actually determining the call order is an exercise in using your IDE's "go to definition" function, or at the very least, VIM's * and # commands. Not ideal, at least not from where I stand. Refactoring is a good process but I don't think it's the right tool to fix this.

#2 Node async module
You could alter your programming pattern and make use of the (rather cool) async node module. Off the top, it looks like it has some interesting solutions to some of the most common logic patterns, but I'm still not 100% sold. There's nothing intrinsically wrong with the module -- it just doesn't seem like the best fit (to me).

#3 Promises (to the rescue, again)
Promises have been around for a while and they're not going away. Indeed, ES6 brings promises right into the core language. If you aren't using them, it's at least time to start looking at them. And if you do, and you happen to stumble across one of the grandfathers of the promise library offering, Q, then you will be pleased to find that Q has support baked in to provide a promise-based wrapper around the typical NodeJS async callback: Q.nfbind, or, as I prefer, the alias: Q.denodeify.

You can just do something like:



var promiseBasedFunction = Q.denodeify(someAsyncFunction);
promiseBasedFunction('arg1.level0', 'arg2.level0').then(function(result) {
// first call succeeds, let's carry on
  return promiseBasedFunction('arg1.level1', 'arg2.level1');
}).then(function(result) {
// second call succeeds, let's forge on forward
  return promiseBasedFunction('arg1.level2', 'arg2.level2');
}).catch(function(error) {
// handle errors
  console.log('FAIL: ' + error);
}).done(function() {
// this is always run
  console.log('Exiting now...');
});
 
 

Some wins you get out of this:
  1. No deep nesting. There is a nice follow-on of functionality, something you can read top-down and which someone else could probably get into a little quicker. Code readability consistently ranks highly when programmers are asked to list aspects of quality code. Remember that the code you expertly write today will be visited by a complete stranger some time in the future. That stranger may even be you.
  2. No need to handle errors at every asynchronous turn. The first one that fails ends up in the catch area and you can deal with it there
  3. A defined end-point that is easy to deal with (the done handler)
But wait, there's more!
The async node module has some interesting techniques for dealing with simultaneous async calls (think: I need to get data from three web services and provide a consolidated answer -- I'd prefer to make those calls in parallel and consolidate once) -- but so does Q, with Q.all(). Q offers a lot, and one of the main benefits it offers is helping to wean you off of the callback tit. As I've shown in my promises tutorial, different promise libraries play together fairly well, so even if you decide to switch to another (or the ES6 built-in Promise), you have to freedom to do so.

Not that I suspect Q is going anywhere any time soon.


Footnote: this journey started when I had the brainfart that it would be great if there were a node module that provided functionality to wrap existing async calls in the promise lingo. I was about to embark on writing one when a friend suggested that I check out some of the functionality in Q that I wasn't already using. That's a reminder to check if a problem has already been solved before running off to write code -- though the process (like the process of writing my own promises implementation) would have probably been enlightening. It's also probably a reminder that it can be quite beneficial to skim over the full documentation for a library to discover useful gems.

Wednesday, 3 June 2015

A little PeanutButter housekeeping

PeanutButter, that collection of libraries that does a whole bunch of stuff, has always been extended with the philosophy that it would be better to have a bunch of small libraries each with only their own dependencies rather than a monolithic installation of a bunch of crap you'd never want.

Well, with the exception of PeanutButter.TestUtils.Generic, which is where interesting test helper code went to lurk and generally be useful. This was where the first incarnation of TempDb was born. It was either Sqlite or SqlCe, I don't remember, but whichever it was, the other was soon to follow, in the same package. So if you wanted a temporary SqlCe database, you ended up getting all of the Sqlite dependencies smooshed into your project. Boo!

I recognised this as sub-optimal, but left it just so, partly because I'm a lazy bugger and partly because I was afraid of fallout for anyone who might upgrade packages and find stuff to be no longer working as it had been moved out into another package.

Not too long ago, I got the itch to add LocalDb support and, of course, it ended up in the same assembly. I was getting less stoked, but remained at the same level of lazy.

Finally, tonight, I got my ass in gear and split these out. So there are 4 new packages:
  • PeanutButter.TempDb
  • PeanutButter.TempDb.Sqlite
  • PeanutButter.TempDb.SqlCe
  • PeanutButter.TempDb.LocalDb
The first contains the generic TempDb<> logic and the remainder are concrete implementations. PeanutButter.TestUtils.Generic no longer provides these classes (and no longer spams your projects with the unused dependencies). Apologies if this causes some "WAT?!" for anyone, but the split was inevitable. As a bonus side-effect, PeanutButter.TestUtils now depends on NUnit, so installing the former will bring in the latter -- which is actually less WAT because of funky things like PropertyAssert.

Anyway, as always, they're totally free. So if they break, you can keep all the pieces.

What's new in PeanutButter?

Retrieving the post... Please hold. If the post doesn't load properly, you can check it out here: https://github.com/fluffynuts/blog/...