Mixing Generics, Inheritance and Chaining

In my last post on unit testing, I had written about a technique I’d learnt forsimplifying test set ups with the builder pattern. It provides a higher level, more readable API resulting in DAMP tests.

Implementing it though presented a few interesting issues that were fun to solve and hopefully, instructive as well. I for one will need to look it up if I spend a few months doing something else – so got to write it down :).

In Scheduler user portal, controllers derive from the MVC4 Controller class whereas others derive from a custom base Controller. For instance, Controllers that deal with logged in interactions derive from TenantController which provides TenantId and SubscriptionId properties. IOW, a pretty ordinary and commonplace setup.

   class EventsController : Controller
    {
        public ActionResult Post (MyModel model)
        {
        // access request, form and other http things
        }
    }

    class TenantController: Controller
    {
        public Guid TenantId {get; set;}
        public Guid SubscriptionId {get; set;}
    }

    class TaskController: TenantController
    {
        public ActionResult GetTasks()
        {
            // Http things and most probably tenantId and subId as well.
        }
    }

So, tests for EventsController will require HTTP setup (request content, headers etc) where as for anything deriving from TenantController we also need to be able to set up things like TenantId.

Builder API

Let’s start from how we’d like our API to be. So, for something that just requires HTTP context, we’d like to say:

    controller = new EventsControllerBuilder()
                .WithConstructorParams(mockOpsRepo.Object)
                .Build();

And for something that derives from TenantController:

    controller = new TaskControllerBuilder()
                .WithConstructorParams(mockOpsRepo.Object)
                .WithTenantId(theTenantId)
                .WithSubscriptionId(theSubId)
                .Build();

The controller builder will basically keep track of the different options and always return this to facilitate chaining. Apart from that, it has a Build method which builds a Controller object according to the different options and then returns the controller. Something like this:

    class TaskControllerBuilder()
    {
        private object[] args;
        private Guid tenantId;
        public TaskControllerBuilder WithConstructorParams(params object args )
        {
            this.args = args;
            return this;
        }

        public TaskControllerBuilder WithTenantId(Guid id )
        {
            this.tenantId = id;
            return this;
        }

        public TaskController Build()
        {
            var mock = new Mock<TaskController>(MockBehavior.Strict, args);
            mock.Setup(t => t.TenantId).Returns(tenantId);
            return mock.Object;
        }
    }

Generics

Writing XXXControllerBuilder for every controller isn’t even funny – that’s where generics come in – so something like this might be easier:

    controller = new ControllerBuilder<EventsController>()
                .WithConstructorParams(mockOpsRepo.Object)
                .Build();

and the generic class as:

    class ControllerBuilder<T>() where T: Controller
    {
        private object[] args;
        private Guid tenantId;
        protected Mock<T> mockController;

        public ControllerBuilder<T> WithConstructorParams(params object[] args ) 
        {
            this.args = args;
            return this;
        }

        public T Build() 
        {
            mockController = new Mock<T>(MockBehavior.Strict, args);
            mockController.Setup(t => t.TenantId).Returns(tenantId);
            return mock.Object;
        }
    }

In takes about 2 seconds to realize that it won’t work – since the constraint only specifies T should be a subclass of Controller, we do not have the TenantId or SubscriptionId properties in the Build method.

Hmm – so a little refactoring is in order. A base ControllerBuilder that can be used for only plain controllers and a sub class for controllers deriving from TenantController. So lets move the tenantId out of the way from ControllerBuilder.

    class TenantControllerBuilder<T>: ControllerBuilder<T>  
         where T: TenantController          // and this will allow to
                                            // access TenantId and SubscriptionId
    {
        private Guid tenantId;
        public TenantControllerBuilder<T> WithTenantId(Guid tenantId) 
        {
            this.tenatId = tenantId;
            return this;
        }

        public T Build() 
        {
            // call the base
            var mock = base.Build();
            // do additional stuff specific to TenantController sub classes.
            mockController.Setup(t => t.TenantId).Returns(this.tenantId);
            return mock.Object;
        }
    }

Now, this will work as intended:

/// This will work:
controller = new TenantControllerBuilder<TaskController>()
            .WithTenantId(guid)                             // Returns TenantControllerBuilder<T>
            .WithConstructorParams(mockOpsRepo.Object)      // okay!
            .Build();

But this won’t compile: 😦

controller = new TenantControllerBuilder<TaskController>()
            .WithConstructorParams(mockOpsRepo.Object)  // returns ControllerBuilder<T>
            .WithTenantId(guid)                         // Compiler can't resolve WithTenant method.
            .Build();

This is basically return type covariance and its not supported in C# and will likely never be. With good reason too – if the base class contract says that you’ll get a ControllerBuilder, then the derived class cannot provide a stricter contract that it will provide not only a ControllerBuilder but that it will only be TenantControllerBuilder.

But this does muck up our builder API’s chainability – telling clients to call methods in certain arbitrary sequence is a no – no. And this is where extensions provide a neat solution. Its in two parts

  • Keep only state in TenantControllerBuilder.
  • Use an extension class to convert from ControllerBuilder to TenantControllerBuilder safely with the extension api.
// Only state:
class TenantControllerBuilder<T> : ControllerBuilder<T> where T : TenantController
{
    public Guid TenantId { get; set; }

    public override T Build()
    {
        var mock = base.Build();
        this.mockController.SetupGet(t => t.TenantId).Returns(this.TenantId);
        return mock;
    }
}

// And extensions that restore chainability
static class TenantControllerBuilderExtensions
{
    public static TenantControllerBuilder<T> WithTenantId<T>(
                                        this ControllerBuilder<T> t,
                                        Guid guid)
            where T : TenantController
    {
        TenantControllerBuilder<T> c = (TenantControllerBuilder<T>)t;
        c.TenantId = guid;
        return c;
    }

     public static TenantControllerBuilder<T> WithoutTenant<T>(this ControllerBuilder<T> t)
            where T : TenantController
    {
        TenantControllerBuilder<T> c = (TenantControllerBuilder<T>)t;
        c.TenantId = Guid.Empty;
        return c;
    }
}

So, going back to our API:

///This now works as intended
controller = new TenantControllerBuilder<TaskController>()
            .WithConstructorParams(mockOpsRepo.Object)  // returns ControllerBuilder<T>
            .WithTenantId(guid)                         // Resolves to the extension method
            .Build();

It’s nice sometimes to have your cake and eat it too :D.

Advertisements

Downloading over an unreliable connection with Wget

Rant – BSNL!!!

This is a part rant, part tip – so bear with me… My broadband connection absolutely sucks over the past week. I upgraded from 2Mbps with a download limit to a 4Mbps with unlimited downloads and since then it has been nothing but trouble… Damn BSNL!! I’ve probably registered about 30 odd complaints with them to no avail. If there was a Nobel for bad customer service, BSNL would probably win it by a mile. Some examples:

  1. They’ll call to find out what the complaint it and even when I explain what’s happening, they hardly hear me out at all.
  2. Either they call up and say ‘We have fixed it at the Exchange’ and nothing has changed
  3. They automatically close the complaints 🙂

Guess they find it too troublesome that someone who’s paying for broadband actually expects the said broadband connection to work reliably!

Anyway, Airtel doesn’t seem to be any better – they need 10 days to set up a connection and when I was on the phone with them, they didn’t seem too interested in increasing their customer count by 1 :).

I also tried calling an ISP called YouBroadband after searching some of the Bangalore forums for good ISP providers. They promised a call in 24 hours to confirm if they have coverage in my area and it was feasible for them to set up the connection and that was 48 hours ago!

At work, I’ve heard good things about ACTBroadband and they have some ads in TOI as well, but they said they don’t have coverage in my area :(.

So how do you download

Today I needed to download something and doing it from the browser failed each time since my DSL connection would blink out in between!

After ranting and raving and writing the first part above and still mentally screaming at BSNL, decided to do something about it… Time for trusty old wget – surely, it’ll have something?

Turns out that guess was a 100% on the money… it took a few tries experimenting with different options, but finally worked like a charm

wget -t0 --waitretry=5 -c -T5 url
    where
    -t0 - unlimited retries
    --waitretry - seconds to wait between retries
    -c resume partially downloaded files
    -T5 - set all timeouts to 5 seconds. Timeouts here are connect timeout, read timeout and dns timeout

Yoohooo!! Successfully compiled Android from source

Finally!!!

So my last weekend project had been to compile Android ICS from source. Given that the size of the repo itself is in excess of 6Gigs, just getting it down itself took the better part of Friday night and Saturday night. When I got down to running make on it, it was Sunday afternoon.

Needless to say, things didn’t work too well. I’m running this on a 32 bit Ubuntu 10.04 Virtualbox with a piddly 1GB RAM. When make failed the first time, realized that swap was a measly 300Mb. First steps first, went on to increase memory to 2GB (that’s all I can spare) and increased swap to 2Gs.

Compilation next round started and that failed too – ran out of disk space – and this was Sunday night. Things kind of stayed there and finally this evening, resized the disk in virtualbox to 50Gigs. Again started the compilation and this time ran into linker errors when building webcore. One more round of troubleshooting involved deleting the previously built static library and then running make again. Surprisingly, this time make completed successfully – to the point where I wasn’t sure if it had succeeded or just failed silently on something else.

The next step was to run the emulator to see if it really would boot up. Over at source.android.com, they oversimplify it when they say that you just run emulator from the android root folder. That didn’t work for me – and this time it was because I hadn’t sourced the envSetup.sh file… this thread http://groups.google.com/group/android-platform/browse_thread/thread/91ff18e034acf951 helped in tracking that one down.

So finally, after all that trouble, I have my very own ICS build running!!!!

For now, its onward ahoy to setting up Eclipse and starting with a fix I’ve been mulling about for sometime now..

Signing off from cloud nine
R

Unit testing Apache CXF RESTful services – code available

So, the original post on the topic written about two and a half years ago had code snippets, but there’s been comments and PMs for the complete code. So last week, as I resurrected this blog, decided to get that code out on github. Unfortunately, that was easier said than done; it has been quite some time and frankly, I’d lost the code. I must’ve switched machines about 3 times in the interim and gone from SVN to github for personal projects. Some hunting around ensued and thankfully, I was able to find the actual code we wrote based on the sample I’d posted. So cleaned that up – and just extracted the unit testing example out of it and pushed it to github – get it here. I haven’t updated any of the dependencies – so this is still running against spring 2.5 and cxf 2.2.3 (I think) and things might’ve changed quite a bit since then (I haven’t used the JAXRS bits of CXF much after that)

Running tests:

        mvn test

Running the server:

        mvn jetty:run

Creating an interstitial login page with JqueryMobile

So, at work, we’re building a mobile website using JqueryMobile. The app has a bunch of publicly visible pages however, other pages require the user to be authenticated. We didn’t want the user to be forced to login on the first page. Instead, whenever a protected page is accessed, and if the user insn’t logged into the app, we’d like to take him to the login page. Once he’s successfully authenticated, then take him to the page he was navigating to. Doing this in a normal webapp is quite standard – however, with JqueryMobile, query params meddle with the hash navigation model. Also, the page that the user tries to access could be a div in the same physical page or a different url that needs to be fetched.

Trying to solve this was interesting as we were all really just getting started with JqueryMobile – so finding the ideal solution required a few tries. The solution takes a leaf out of JqueryMobile’s approach. The outline of the solution is:

  1. Any page div that’s a protected resource is marked with a data-needs-auth="true" attribute
  2. We hook into the document level pagebeforechange event to see if the user is trying to transition to a page requiring authentication. If so, then check if we have the user’s authenticated context available.
  3. if the said context isnt available,
    1. Cancel default event handling since we’re now going to navigate the user to the login page.
    2. save the toPage object – so once the user is logged in, we know where to take him.
    3. navigate to the login page.
  4. In the login page, the page can call the server apis to autheticate the user. Once the user is authenticated, then
    1. See if there’s a valid returnTo object, if so, take the user to the page.
    2. If not, take the user to a ‘default’ page – in our case, this is the app dashboard page.

Code below

    var pageVars = {}
    $(document).bind("pagebeforechange", function (event, data) {
        if (typeof data.toPage == 'object' &amp;&amp; data.toPage.attr('data-needs-auth') == 'true') {
            if (!sessionStorage.getItem("TokenSSKey")) {
                if (!localStorage.getItem("TokenLSKey")) {
                    pageVars.returnAfterLogin = data;
                    event.preventDefault();
                    $.mobile.changePage("#Login_Page", { changeHash: false });
                }
                else {
                    sessionStorage.setItem('TokenSSKey', localStorage.getItem("TokenLSKey"));
                }
            }
        }
    });

The login event handler that handles the server response that’s received once we pass the username and password

    function SuccessLogin(data) {
        if (data != null &amp;&amp; data.LoginResult != null) {
            if (data.LoginResult.Code === 0) {
                localStorage.setItem('UNameLSKey', data.LoginResult.User.AccountName);
                if ($("#RememberMeChkBx").is(":checked")) {
                    ErrorPanel.html("");
                    localStorage.setItem('TokenLSKey', data.LoginResult.Token);
                    sessionStorage.setItem('TokenSSKey', data.LoginResult.Token);
                }
                else {
                    ErrorPanel.html("");
                    sessionStorage.setItem('TokenSSKey', data.LoginResult.Token);
                }
                if (pageVars &amp;&amp; pageVars.returnAfterLogin) {
                    $.mobile.changePage(pageVars.returnAfterLogin.toPage);
                }
                else {
                    $.mobile.changePage("#DashBoard_Page", { changeHash: false });
                }
            }
        }
    }

Learning Vim

Is it worth it?

Definitely seems to be. I’ve looked at VIM in the past, tried it out too a couple of times or more, failed miserably(mostly within a day or two) and then wondered Why nutheads use VI. This would usually be followed with going back to the comfort of Emacs. I think over the years, I’ve spent more time customizing Emacs than actually getting any work done with it. And somewherethat felt wrong. In light of that, the minimalistic VIM looked attractive and worth another try.

So what about this time?

So this time things worked out a bit better. Rather than firing up VIM, spent some time reading through other’s experiences on picking up VIM. And the first thing I did right was to disable the arrow keys in normal mode (I still have them in insert mode)

    " disable arrow keys
    noremap   <Up>     <NOP>
    noremap   <Down>   <NOP>
    noremap   <Left>   <NOP>
    noremap   <Right>  <NOP>

Once you have that bit, you’re forced to use h/j/k/l. And while h/j/k/l muscle memory is built up within a week, the nice thingthat really happens is that you dont use h/j/k/l much – instead you move to using more efficient movement commands. There’re aton of resources/cheatsheets on the web – but the approach I followed was to figure out some small keystroke when I needed it.What that mean’t was that I could get work done – but at the same time get more efficient gradually.

customizations

VIM out of the box is pretty badly configured – and that’s part of the reason that people seem to shy away from it. In fact, all the times that I tried out VIM before, I didnt even come close to cusotimizing my .vim. There are folks who have curated vim dotfiles on github etc – but my advice is to stay away from them. You should know what goes in your .vim and be in control of thatrather than getting a bunch of things in your .vim that you dont understand. Just so you know, looking at the github history for my vimfiles repo – the initial commit was 3 months ago – but after that, all the commits have come in only in the last 4 weeks.What that means is that while I put in a vim file initially, I didnt do much with it initially since I was just getting a hang of the basics. Once one becomes comfortable with the basics, one moves to customizing the vim environment more and more.

Parting words

To summarize, VIM definitely seems nice once you invest into it. It’s easy to drop off in the initial stage and not go any further – and I believe this is what happens to the vast majority of folks who try it out. However, once you build that initial comfort level,it feels light, fast and easy.Start easy, persist, and customize bit by bit – you’ll feel yourself going from struggling with Vim to feeling comfortableand then to customizing your environment for an even better experience with VIM.I’ve definitely been more productive with VIM than I ever felt I was with Emacs – and these posts to my blog from Vim part of that.Besides that, I’ve used VIM effectively with a decent sized js code, html markup etc and felt the speed of editing inspite of still beinga noob in Vim terms.

Blogging with Vim

So now I’m in Vim land and this is the first time I’ve gotten far enough to feel a bit comfy. Decided to dust off my blog and start at it again – what better to do it in than in VIM.

So – TA-DA – here’s the first post – courtsey VIM on ubuntu. However, as usual, it was rougher than it’s supposed to be. IN any case, I’ll forget how I got this far the next time so the next few posts will be around recording how to get VIM to post to WP.com blogs.

But before that – the first thing to to is to get the VimRepress plugin. Better if you have pathogen installed, in which case you can do

    cd .vim
    git submodule add https://github.com/raghur/VimRepress bundle/VimRepress.git

That’s my fork on Github of https://github.com/connermcd/VimRepress.git which fixes a few things:

  • Makes VimRepress work properly through a proxy
  • Changes the attachment filename to a ‘.odt’ since WordPress.com doesn’t allow a text file attachment.

I still dont have a clue if doing this will break the plugin – but nevertheless, basic case of posting to my blog works and at this stage that seems good enough for me.

PS as you can see from this post – I’ve not yet got a hang of markdown syntax 🙂

Dec 29th – PPS a couple of posts and one more tip for WordPress.com. WP.com does <br/> for hardbreaks in the markdown text. Obviously, this doesnt leave the post looking very good. I have the following in my .vimrc to get around this

        augroup Markdown
            autocmd FileType markdown set wrap 
                                    \ linebreak
        augroup END

PPS
You will also need to have python markdown installed once you have VimRepress running.

    easy_install markdown