My blog just died and was brought back from the dead!

The other day I noticed that I got an error message when trying to read my blog. Basically it said that the database connection was not behaving and WordPress was unable to load my blog. Auch I thought and started to wonder what could be wrong. The thing is, I run this blog on Microsoft Windows Azure Web Sites, using the WordPress application from their gallery. I have done very little to set it up, apart from the custom domain name. The blog was running on http://noocyte.azurewebsites.net/ and I setup a CNAME record to point to http://blog.noocyte.net/. All fun and games, until the database broke down…

Another interesting tidbit; the database is mySQL and is running in Azure, but it’s operated by ClearDB, not Microsoft. And ClearDB has no integration with the regular Azure control panel. In fact I am still unaware of how to manage my database…

Anyway I went into the Azure portal and had a look at my blog web site; all peachy! The database is listed as a linked resource and all lights were green. So I googled with Bing and came up with one decent answer; the load on the database could be exceeding the allowed load by ClearDB. But how on earth this blog could attain such a load was a mystery to me… So I posted a question of my own on MSDN Forums and fairly soon a representative from Microsoft came back to me suggesting that I contact ClearDB and making them ‘adjust’ the database connections limit. So I filled out their form and waited. In fact I waited 4 days and heard nothing. On Monday I tweeted:

tweet1

They came back to me and suggested I fill out their contact form again, which I did. This time they came back within the hour and told me that my database had been “de-provisioned by a call that was made from Windows Azure on Thursday, January 10th at 15:21 UTC”! De-provisioned means deleted in my book; not cool!

Long story short, they were able to restore the database into a new database and everything was OK. They are now investigating why this de-provisioning call was made, I sure as heck didn’t make it! And the database is still listed as a linked resource in the Azure portal!

As a side note; since the blog was down anyway and I had to create a new database I finally created my own subscription in Azure, separate from my work subscriptions, to host the blog. Will cost me a bit of money, but feels good to pay for services I use!

Posted in Personal | Tagged , , , | Leave a comment

My first adventures in Git

So up until today I have only heard, read and watched Git happen. I have not yet actually tried it. So when I realized today that I actually had some spare time I thought I would dig into it and see if I could understand the hype and perhaps find it useful!

My very first step was to find a good tutorial on how to get started. I found one on Seascape Web that I found easy to follow and short enough so that I didn’t get lost. In the end I managed to setup my repo and commit my Double Key Dictionary source code (more on this later).

The next step will be to work with the code and Git to see how that feels vs. Team Foundation Service that I’ve been using so far.

Posted in Geek, Uncategorized | Tagged , , | 1 Comment

Microsoft Surface RT

For the first time I have preordered something from the US and had it brought over the Atlantic using Jetcarrier; Microsoft Surface RT. It’s a wonderful little Device! Missing some apps etc. but that should improve over time. More later.

Posted in Geek | Leave a comment

ASP.Net Web API and Ninject

For the third time I’m using the new Web API in one of my projects and again I hit the wall when it was time to hook up to mu DI framework of choice: Ninject. So this time I’m documenting it here, hopefully that will make me remember it going forward.

To make DI work with Web API there are three steps to perform:

  1. Create two classes: NinjectDependencyScope and NinjectDependencyResolver
    I used the code from Peter Provosts blog.
  2. Hook up the new classes in NinjectWebCommon:
    GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
  3. Create bindings

Fairly easy stuff if you just know how and obviously Peter knew how! There is one caveat though: the NinjectDependencyResolver class also exists in the Ninject.Web.Mvc namespace! This one inherits from IDependencyResolver and we want it to inherit from IDependencyScope. It won’t compile if you reference the wrong class though, so not a big problem really.

Posted in Geek | Leave a comment

ORMs and Performance

In one of my projects, actually Proactimas project, I’m using Entity Framework (EF) on top of SQL Azure and it works pretty well; data access is relatively fast, dead easy most of the time and the cost (in $) is OK. However I have discovered how sensitive EF is to how you write your queries. It appears to be especially true if you have several one-to-many relationships.

Just a quick introduction to Proactima Compliance; Any user has access to one or more companies, each company consists of one or more units. Units can be things like ‘Head Office’, IT-department, a ship etc. For every unit there can be one or more evaluations and each evaluation is based on a set of rules that the company measure compliance against. An example of a ruleset is the Petroleum Activities Act in Norway.

In Proactima Compliance the most frequently accessed page had an action that took about 1000ms to complete. This page allows the user to evaluate a rule and then choose ‘Save and Next’; so there are two actions involved:

  1. Save current rule and find next based on previous rules’ sequence
  2. Load next rule and display it to the user

The second action completes in 200-400ms, but the first takes from 800-1200 ms to complete. The main reason for the long processing time is what MiniProfiler calls Duplicate Readers. Basically, because of the way I had written my queries it was executing a reader querying for each rule in a ruleset! It looked like this:

Pre_Optimize

It’s running 103 (!) queries just for that one action, that’s terrible! The actual query looked like this:

var rules = from r in evaluationRule.Evaluation.Rules
                 where r.Rule.Sequence > currentSequence 
                 orderby r.Rule.Sequence 
                 select r;

The variable ‘evaluationRule’ was already fetched from the database and so I was just navigating to its Evaluation (remember how an evaluation is based on a ruleset which in turn consists of individual rules) and then the ruleset for that evaluation. Then I set up the where clause to make sure we can only get a rule with a sequence higher than the current rule. Finally I do an order by and select, from this I will only choose the first rule thus getting the next rule based on sequence. Possible bug here; sequences could potentially be same, but I’m 100% in control of the sequences so that’s really not an issue.

I won’t show the rendered query from this, it’s a nightmare, but the end result is correct and dead slow… So I had to fix this! I tried to manipulate the query in a try-fail-retry pattern; no success at all! I figured after awhile that I was addressing the issue from the wrong end; I was just thinking of the code. Thinking back on previous issues I’ve had with generated Sql (from other ORMs) I remembered (finally!) an old lesson; start by writing the query manually in the best possible way you can and then try to express that same query using the ORM! So that’s what I did! I fired up Sql Server Management Studio Express 2012 Deluxe Gold Plated Edition, or whatever it’s called and thought really hard about what I really needed. What I ended up with was this:

DECLARE @currentSequence int = 1;
DECLARE @currentEvaluation int = 1;

select	top 1 er.ID, 
	er.RuleID,
	r.Sequence,
	er.EvaluationID
from	EvaluationRules er,
	Rules r
where	er.RuleID = r.ID
and	er.EvaluationID = @currentEvaluation
and	r.Sequence > @currentSequence
order by r.Sequence;

Not that hard to write at all. Now all I needed was to convert it to EF code:

var rules =
    (from er in Database.EvaluationRules
        join r in Database.Rules on er.RuleID equals r.ID
        where er.EvaluationID == evaluationId
        && r.Sequence > currentSequence
        orderby r.Sequence
        select er)
        .Take(1);

It’s definitely a bit more than my original code based query, but as you can see it looks a whole lot like the manual sql query. And how does MiniProfiler now report on my page:

Post_Optimize
Please ignore the minor differences (controller name); I have done some other refactoring’s as well as the query.

What an amazing change! 900ms to 222ms! And 100+ queries to just 7! That’s performance optimizations the user notices!

But why did it all go so terribly wrong in the first place? I’m not going to over analyze the two queries or discuss how EF generates the Sql; somebody much smarter than me can probably do that (or has!). But what I learned from all this is that my old skills as Sql developer isn’t lost even if I am using an ORM AND the way you express a query can matter a whole lot when it comes to performance!

Posted in Geek | Tagged , , | Leave a comment

On Corporate Values and Developers

I work for a company called Proactima AS, we deliver HSE&Q/RISK consultants to our customers. But I have been hired to do some development for them. Proactima is a company that runs close to a 100% on knowledge and so our main resource is the consultants working here. As so many other companies Proactima has a set of values defined:

  • Knowledge
  • Balance
  • Integrity

And so everything we do is evaluated against them;

  • Can we work with this client?
  • Are we interested in bidding on this job?
  • Can this consultant handle more load?
  • etc.

in theory most companies operate like this, but very few actually adheres to them. We have turned down job offers because of our integrity, workload is scaled down if a consultant wants to focus more on home than job for a period etc. I myself have had issues at home where work was not my number one priority and then my manager (resource owner really) scaled down my work load accordingly. Our chairman of the board even asked me why I as in the office during that difficult time (more on this later IF I’m up for it). So you see, we live and die by our values. We do not steer the ship by financial numbers alone, but rather on how well we mange to live up to our own values.

At this point you might be wondering why I’m telling you all this? Or perhaps you’re not even reading it… The thing is, the last few weeks I’ve been evaluating myself according to these three seemingly simple values; Knowledge, Balance and Integrity. Not just myself really, but people around me as well. And the things that I do. How well does it all stack up against these values?

First of all I found that I could easily rate most people on the three values and I realized that I had more respect for those that rated high on these values vs. other values. Because, let’s be honest here, Proactima could’ve chosen completely different values! Statoil has chosen: Courageous, Open, Hands-on and Caring. All fine values, but not what Proactima chose and not what I would have chosen.

Furthermore I found that I could rate my work (programming that is) according to the values:

  • Is the code using the best components and the correct algorithms? (Knowledge)
  • Am I spending too much time on problems that does not warrant it? (Balance)
  • Will the code be maintainable when somebody else takes over responsibility for it? (Integrity)

Are you evaluating yourself and your code according to a set of values? If not; perhaps you should…

Posted in Geek | Tagged | Leave a comment

New home for my blog

Inspired by Scott Hanselman’s latest blog entry I have decided to get my own domain (noocyte.net) and move the blog here. It’s currently hosted in Microsoft Azure as a web site.

Hopefully I will get back to blogging real soon now (again!).

Posted in Personal | Leave a comment

google reader updated–for the worse

So today I was notified that Google Reader has been updated with a new interface! Brilliant I thought; I love new stuff and the reader was beginning to look a little long in the tooth. But as soon as it loaded I though: dang, that’s not an improvement! It looks alright, but too much screen realestate is lost to navigation or whatever.. Take a look at the pic below:

Google Reader

There are a total of 3 rows of navigation/toolbars, that’s just too much for me! The row with the red button on (it says “Abonner”) should be merged with the one above; that would help a lot. As it stands right now I’m not happy with the new interface…

Update: It’s also dead slow and often does not respond at all… Not happy!

Posted in Personal | Tagged , | Leave a comment

ValueInjecter and Expression Magic

In a previous post I have talked some about how I use AutoMapper and I’m using it for all my “Entity To View” model mappings; works like a charm! But what it does not do is to map the other way; ie. take whatever comes from the view and apply that to an entity model. There are some discussions online on the ‘correctness’ of doing this, but I found it to be an easy and productive technique.

But since AutoMapper doesn’t handle this I had to write a lot of LHS-RHS code, right? No I didn’t! Somebody else have already solved this problem in a utility called ValueInjecter. Basically it’s capable of injecting values from one object to another, and this of course is exactly what I need! So how do I use it;

var entityObject = db.GetEntity(viewObject.UniqueId);
entityObject.InjectFrom<CustomInjectionRules>(viewObject);
entityObject.State = EntityState.Modified;
db.Store(entityObject);

The magic happens on line number two; the InjectFrom method will transfer data from my viewObject to the entityObject. The method can be used without specifying a type (generics) to assist in the injection, but I need it to allow for data type and naming variations between the two objects. The CustomInjectionRules class handles those two issues and looks a little like this:

public class CustomInjectionRules : ConventionInjection
   {
       protected override bool Match(ConventionInfo c)
       {
           return c.SourceProp.Name.Equals(“ViewProp”) && c.TargetProp.Name.Equals(“EntityProp”);
       }

       protected override object SetValue(ConventionInfo c)
       {
           return Convert.ToInt32(c.SourceProp.Value);
       }

   }

The class inherits from “ConventionInjection” and overrides two methods; one for matching properties with unequal names and the second for converting between whatever “ViewProp” is and int32 (“EntityProp”).

After writing this code I made sure it worked and then came back to look at it; could I improve it? Refactor it somehow? Not much code in there, so my first instinct was; No, this is fine. But then I looked hard at the “Magic Strings” (“ViewProp”/”EntityProp”)… I do not like magic strings! No refactor/compile time support and all that nonsense. So I had to find a better solution! I immediately thought of another blog post I’d done some time ago; MVC 3, EF 4.1 And Some More… The HtmlHelper methods appear to just take a lambda expression as input and then figures out the name of the property! Which of course is exactly what I needed! So I started Googling… I found a few examples, but they weren’t spot on before I found a question on StackOverflow! Spot on! I did some minor adjustments and not my CustomInjectionRules class looks like this:

public class EvaluationRuleTypeInjection : ConventionInjection
{
    protected override bool Match(ConventionInfo c)
    {
        return c.SourceProp.Name.Equals(GetMemberInfo<ViewObject>(r => r.ViewProp))
                && c.TargetProp.Name.Equals(GetMemberInfo<EntityObject>(r => r.EntityProp));       
    }

    protected override object SetValue(ConventionInfo c)
    {
        return Convert.ToInt32(c.SourceProp.Value);
    }

    private string GetMemberInfo<T>(Expression<Func<T, object>> method)
    {
        LambdaExpression lambda = method as LambdaExpression;
        if (lambda == null)
            throw new ArgumentNullException(“method”);

        MemberExpression memberExpr = null;

        if (lambda.Body.NodeType == ExpressionType.Convert)
            memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
        else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
            memberExpr = lambda.Body as MemberExpression;

        if (memberExpr == null)
            throw new ArgumentException(“method”);

        return memberExpr.Member.Name;
    }
}

Awesome! I immediatly moved the “GetMemberInfo” method out of this class and into a more appropriate class, but included it here to avoid expanding all the code…

Pretty happy about this change. Also loving how easy it is to get stuff such as ValueInjecter into my prosjects using nuget.

Posted in Geek | Tagged | Leave a comment

GoodleAdz

Reading Gisle Hannemyrs latest blog post on GoodleAdz I’ve been thinking if there might be something more to this… What if I became a member and had Google Ads on my page? And presumably GoodleAdz has quite a few members; if they’re all looking at my page once a day that will eventually become quite a few pageviews, will it not? I’m not saying this is a good idea, it really isn’t, but interesting thought though…

Posted in Link | 1 Comment