Chromecast crash

Having problem with your Chromecast rebooting as soon as you stream anything from Netflix?

Then it night be that you need to swap the USB charger (.850ma) to a one producing more power. I took one of my phonechargers (1.2A) and have not been trubbled with any reboots since :)

flattr this!

Bad design decisions .Net developers have to cope with

Today I wasted aprox. 1h of debugging ASP.NET code. Only to discover that the cause of the bug was a flaw in the design of the ASP.NET API. First of all, older ( < 4.0 ?) .NET code seldom use DI and often depend on inheritance, which is bad practice to begin with. As a consequence of not using DI you often see static reference calls (which makes unit testing a living hell). In ASP.NET one has used a desktop metaphor for the web development, which makes it easy for experienced desktop developers to transition to Webb. However to do anything else than the simplest input form forces you the bend the desktop metaphor over backwards. Ajax functionality is such a gymnastic event in ASP.NET. One has to depend on a "ScriptManager" (which is referenced statically). This scriptmanager also behaves differently depending in which context it is used in. As with many .NET API methods the method names of the scriptmanager is ambiguous which make you as a developer guess what a method call does (and since it is not open sourced there is little to do, except to experiment to know). Take my issue from today as a example.

In my project we had started to implement some logic in a ordinary .aspx file however as the requirements has increased we now needed similar functionality in multiple places. To accomodate this we needed some kind of template engine, since were working in ASP.NET 2.0 we migrated our .aspx code into a ASP.NET "Master page" all worked as expected until we suddenly realised that some of our AJAX functionality stopped working? It turns out that when using a Scriptmanager in a Master page you cant pass "this" as the first argument to the RegisterStartupScript method instead you need to pass the "Page" property.

In ordinary .aspx

ScriptManager.RegisterStartupScript(this, this.GetType(), scriptKey, javaScript, true);

In Master page

ScriptManager.RegisterStartupScript(Page, typeof(Page), scriptKey, javaScript, true);

So how is this bad?
Well a API should be intuitiv for me as a developer to use and a API should be easily mockable. Any method with a signature of more than two arguments is a strong indication that the object modell is broken and any object named XXXMangager is a indication that a bunch of logic has been grouped together, that should have been separated into multiple classes. Why? Well it comes back to the intuitiveness again.. If you cant deduce what the arguments is used for in the method chances are that you will use the method in the wrong way. It should be easy for a developer to understand the outcome of a method only reading the name of the method (and class) and its arguments. Finally any statical reference is unmockable.. making the testing of the code practically impossible.

flattr this!

mySQL errno: 160 add foreign constraint error

Tried to alter a mysql database table like and gotten a error like so?:

ALTER TABLE table1 ADD CONSTRAINT fk_constraint_1 FOREIGN KEY (fk_key_column) REFERENCES table2 (id);ERROR 1005 (HY000): Can’t create table ‘mydatabse.#sql-1111_17b6′ (errno: 150)

Make sure that both tables use the same engine!
In my case one of the tables used the InnoDB engine and the other used the MyISAM which cant reference each other with foreignkeys constraints.
To fix this you need to migrate to InnoDB on both tables, this is done like so:

ALTER TABLE my_table ENGINE = InnoDB;

flattr this!

GWT Super-dev-mode groovy startup script

Are you like me using Grails in junction with GWT?
Have you also migrated to GWT 2.5 RC1?
Are you like me tempted to use the new Super Dev Mode when developing GWT?

Then I got a treat for you !

This short groovy script will launch the Super Dev Mode for you just entering:
“grails gwt-super-dev-mode name-of-my-gwt-module”

All you need to do is to put the script in a file called GwtSuperDevMode and put it in the scripts folder.. and voila your done.

import org.codehaus.gant.GantState

includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsArgParsing")

target(main: "Starts the gwt super devmode") {

    GantState.verbosity = GantState.VERBOSE
    ant.logger.setMessageOutputLevel(GantState.verbosity)
    def gwtpluginversion = metadata.'plugins.gwt'

    ant.path(id: "devmodePath", {
            pathelement(location: grailsSettings.classesDir.path)
            pathelement(location: "${grailsSettings.projectWorkDir}/gwtclasses/")
            pathelement(location: "${basedir}/src/gwt/")
            pathelement(location: "${basedir}/src/java/")
            fileset(dir: "${basedir}/lib")
            pathelement(location: "${grailsSettings.projectPluginsDir}/gwt-${gwtpluginversion}/src/gwt/")
            pathelement(location: "${grailsSettings.projectPluginsDir}/gwt-${gwtpluginversion}/src/java/")
            fileset(dir: ant.project.properties."env.GWT_HOME"){
                include(name:"gwt-codeserver.jar")
                include(name:"gwt-dev.jar")
                include(name:"gwt-user.jar")
            }

        // Fix to get this working with Grails 1.3+. We have to
        // add the directory where plugin classes are compiled
        // to. Pre-1.3, plugin classes were compiled to the same
        // directory as the application classes.
            if (grailsSettings.metaClass.hasProperty(grailsSettings, "pluginClassesDir")) {
                pathElement(location: grailsSettings.pluginClassesDir.path)
            }
        }
    )
    ant.java(classname: "com.google.gwt.dev.codeserver.CodeServer",
            failonerror: "true",
            logerror: "true",
            fork: "true",
            maxmemory: "1024m",
            classpathref: "devmodePath"){
            arg(value:args)
    }
}

setDefaultTarget(main)

flattr this!

Securing GWT command pattern in Grails

I recently worked on a project build upon Grails and GWT. With Grails comes the GWT plugin and with it the ability to communicate with Grails using the command pattern. However this pattern uses only one service / servlet facade between Grails and GWT because of this it is not evident howto use Spring security (another Grails plugin) to secure some commands and leave others public. I found a solution wich entails tinkering a bit with the GWT plugin groovy classes.

I extended the GwtActionService (could /should be done with composition as well I guess ;)) and override the execute method.
Within it I added a check on whether the ActionHandler has a Spring @Secured annotation on it if so it makes sure that the user i logged on. This using the “springSecurityService.isLoggedIn()” method and it also checks that the user has the right permission comparing the values in the annotation and the authentication object provided by spring security.

class SecureGwtActionService extends GwtActionService {

    def springSecurityService
    def grailsApplication

    @Override
    Response execute(Action action){
// Get the class name of the action, because we need it to find
        // the corresponding action bean.
        def name = GrailsClassUtils.getShortName(action.getClass())

        // Prefix the name with "gwt" and add a "Handler" suffix to get
        // hold of the appropriate bean.
        def handlerBeanName = "gwt${name}Handler"
        if (applicationContext.containsBean(handlerBeanName)) {
            def actionBean = applicationContext.getBean(handlerBeanName)
            Secured secured = actionBean.class.getAnnotation(Secured)
            if(secured == null)
                return actionBean.execute(action)

            if(springSecurityService.isLoggedIn()){
                if(secured.value().any {value->
                    springSecurityService.authentication.authorities.any {auth ->
                        auth.authority.toLowerCase().equals(value.toLowerCase())}}){
                    return  actionBean.execute(action)
                }
            }

            throw new RuntimeException("Must be authorized to access ${action.class.name}")
        }
        else {
            throw new RuntimeException("No action handler configured for ${name}")
        }

    }

}

This modification is easily injected through the resources.groovy DSL like so:

beans = {
    gwtActionService(SecureGwtActionService) {
        springSecurityService = ref('springSecurityService')
    }
}

flattr this!

Don’t forget your package!

Today I used a couple of hours to figure out the cause of a rather mysterious exception thrown when running a new spock specification.

Error running script test-app :spock: java.lang.RuntimeException: Could not load class in test type ‘spock’ 

As it turned out I had (in my cut and paste frenzy) forgotten to include the package statement in the top of the groovy class file.. go figure!

flattr this!

Guerilla agile

One upon a time I together with a small team was asked to improve a poorly maintained code base. It contained methods with 200+ lines of code, unused methods and variables, commented out code and a hand full of unit tests no longer running, you get the picture. On top of this we was forced to use a old centralised versioning system (even older than subversion ;)). The code base was in such as condition that the most simple feature would cause you to create a refactor rash throughout miles of code and the old versioning system did not do much to help us keep track of changes it rather place a mine field of latency and corrupt merges on our war path. With the lack of a proper VS It fast became impossible to remember all changes done during the addition of the new feature. The team soon resorted to locking files on edit to ensure that they did not have to spend hours merging in their changes (since the code base was so encoupled it allmost happened on each commit). It even got to the point were the team had to email files back and fourth since it was easier to manually merge the changes than using the VS. Each time we had to do a manual merge we also knowingly committed a pandoras box of potential bugs. One day I started our scrum meeting playing “Eve of destruction” on the boombox, since it felt more and more like the appropriate sound track of our system. To cope with this gory trench war of badly maintained code we became guerilla-agile.

I will in a coming series of posts tell our story of how we coped with this situation.

To be continued.. next up Using Git from behind enemy lines

flattr this!

OpenID & Google pitfall

Today I learn something useful.
Apparently Google (perhaps all openId providers) as a open id service provider do not consider these two realms to be the same http://subdomain.domain.com and http://*.subdomain.domain.com . This is a major pitfall since it might cause you (as it did for me) to make users start using your service with a faulty realm. Which later on might cause them / you a substantial hassel when their openID is not linked to any user account (since the realm changed).

flattr this!

GWT selling points

I would like to state for the impatient reader that THE main reason for choosing GWT in front of plain Javascript (home brewed) is “Compile time checking” and “Static typing”. So if these are features that you feel are crucial for the success of your project you have found your tool. However if you feel that “Static typing” and “Compile time checking” do not completely convince you as selling points or rather you dont understand how they can be the main reasons for GWT since you hate them and they are the main reasons for your life being miserable, keep on reading.

I came across GWT late 2009 and I did not initially understand what the purpose of it was. However since then I have used it in projects with both failure and success as a result. Since my technical domain usually is the web new technologies such as GWT is discussed on architectural project upstart forums. I have from time to time in such forums been asked to present some of the pros and cons that I have encountered using GWT. I though it might be of interest for someone else so here it goes..

Misconceptions

Often (mistakenly) the main reason for choosing GWT is that it solves the awkward browser quirks, we as web developer have to cope with. Since these quirks are such boring and cumbersome tasks for web developers to solve, we soooo eagerly want to believe every attempt and product sales pitch that argues that it have solved it. However I have yet to se such a product that works flawlessly GWT is no exception! Choosing GWT will not solve this problem completely for you!! It will however give you standardized framework to plugin your own fixes for each quirk using what GWT calls “deffered bindings“.

Another misconception about GWT is that you will not need to know anything about javascript to use it. Unless your future application is anything more complex than the example application google provides (and if your application is that simple I cant really motivate the GWT choise), you will need to understand some basics of javascript. You will need to solve some problems with JSNI Javascipt Native Interface which relies heavily on knowledge about javascript.

Nice features

GWT has a few rather nice features that is to seldom promoted.

Resource bundles

Resources on the web is scarce one of the most scarce resources is the capacity of the network it self. As processor resources follow more’s law networks do not. As processors gets faster and therefore also cheaper we are getting more and more competent devices in our hands. All this computing power gets rather dull if not utilized in a network however since the network do not follow the same progress as processors we need to utilize the network as smart as possible. This has been done for quite some time in the web with the technique of using css sprites. So if this has been around for some time what is the deal with GWT and resource bundles? Well as nice as css sprites are they are not real easy to create. For them to work you first need to create a large sheet with all (or some) of your images then calculate and position them with css. This has to be repeated each time you add a new image to your site, it tends to get rather cumbersome. What GWT does is at compile time do this for you.

Name spaced css with strict scoping

Have you ever started out defining css class names at the start of a project just to go back renaming them since you realized that the names you gave them does interfere with some new features? If answered yes on that question I guess that you also remembered what a search & replace hell that was? If you answered no, might it be because you did not bear doing it, instead you keept the old names and gave the new features quirky names that did not really represent what the feature was all about?
Well GWT brings name spaced CSS to the table along with strict scoping. What is that? GWT mapps a .css file to a interface and mapps each css class name to a method. In doing so it also gets the benefits of the JAVA name spaces. If you use this feature in GWT you can in one part of your application give the “largeButton” css class the meaning of a red 100px wide button and in another part 500px wide without the classes interfering with each other. Above that GWT will at compile time tell you if a css class no longer is used or if you misspelled a css class name. This is a real time saver.

Dependency injection

This is not really plain GWT however if you include reference to the GIN modules you get an almost (It do not support all features of Guice) feature complete dependency injection framework. I cant really cover the benefits with a DI container in this post so you either already know what DI framework does or you really need to read up upon it.

Solves browser caching

GWT name all .js files baed on a hash algorithm (not sure although I believe it is MD5). This is done by using the javascript content as input to the hashing. This sort of automatically solves the issues with browsers not wanting to download changes in your javascript.

Design patterns

GWT has utilized many proven GOF and Fowler patterns such as MVP, Observer, Command etc. There are a few examples using these patterns which can help you to start of in the right direction.

Draw backs

Well no framework is flawless and they all have their trade offs.

Turn around time

The biggest trade off you need to consider is the turn around time i.e. the time it takes you to add some small feature to a UI and until it shows up on your browser. This obviously has to do with the fact that GWT compiles you JAVA source into javascript. I must say though that the guys behind GWT has improved this tremendously since the earlier releases (2.4 when writing). Now the compilation is done in parallell and utilizes all CPU cores which makes it go faster. There is also the hosted mode redering (you use this during development in conjunction with a browser plugin) which goes at lot faster although it has not always been flawless when I used it. I think that this issue must be communicated and understood by all team members prior to choosing GWT if not you might end up with a developer riot on your throat.

Complexity

GWT certainly is the enterprise way to go about javascript (read web client side ui) development. With that said you as a decision maker need to understand what kind of team your have at you hands. Are your team skilled in development with frameworks and concepts sch as JAVA EE, SPRING, MVP, TDD etc. and are your team eager to learn? If yes you will need less of an effort to be successful with GWT. If no, you will probably be more successful using a more light weighted framework such as JQuery in conjunction with home brewed javascript. Which might be the right decision either way depending on your project complexity.

java.util.Date

GWT still depends on java.util.Date for time and date logic. This is not good since many of the methods on the Date class is deprecated. read more here..

Bottom line

So how can such old and boring things as “compile time checking” and “Static typing” be the main reasons for GWT?

Well as stated above that argument is only valid if you intend to use GWT in a relative large project. To define a large I would argue that it is a project which has more than 2 active developers in it or that will result in more than aprox. 200 lines of javascript.  GWT in its core is nothing more that compile time interpreted JAVA into javascript. In doing so all benefits with JAVA comes with it. Benefits you say?
Yes a dynamically typed language as javascript has many strong sides (me not being very proficient in javascript, you might have guessed it ;), cant count them up) but refactoring and testing support is still scarce. This makes it a poor language to work on in a team setup. I guess it could work if all team members are proficient in javascript and you find your self a good testing and refactoring tooling. Although if you have this then you probably would not be looking towards GWT in the first place would you? With JAVA and all IDE’s that support it you get type safety, extensive refactoring tool support, unit testing support etc. When you are in a large project these tools is what keep your WFT count to a minimum or at lest they should help you keeping it down.

Need more input before making a decision? Read this:
http://blog.codecentric.de/en/2010/11/inner-dialog-on-gwt-benefits-and-drawbacks/

Since I first wrote this, a survey has been conducted which might answer even moore questions for you.
http://vaadin.com/gwt-report-2012-portlet/download/1144374453/Future-of-GWT-Report-2012.pdf

flattr this!