Comments

This is the first in a series of posts I’ll be making about developing Android applications. Hopefully there will be some useful tips in this series that will help other developers to get their apps off the ground.

The first step is to get your PC setup with all the required software for writing the apps. There is a pretty good guide setting up the Android SDK on the Android developer site so I won’t go into too much detail. However, I think their steps are in the wrong order so I’ve amended them below (you should install the Android platforms before the ADT plugin):

  1. Prepare your development computer and ensure it meets the system requirements.
    • You need to install the Java Development kit here, if you just run their SDK installer it provides a link to the JDK.
  2. Install the SDK starter package from the table above. (If you’re on Windows, download the installer for help with the initial setup.)
  3. Add Android platforms and other components to your SDK.
    • I only added the 2 latest SDK platforms along with their samples, I doubt you would need the older ones unless you have to develop for some legacy device.
  4. If you don’t already have it, download Eclipse and install it
    • While the platforms are downloading you can grab a copy of eclipse. It doesn’t need installing as such you can just extract to your hard drive.
  5. Install the ADT Plugin for Eclipse.
    • After Eclipse has extracted and your android platforms are added, you can hook the Android SDK into Eclipse by installing the ADT plugin.
  6. Explore the contents of the Android SDK (optional).

Once all the above are done you should be ready to start developing. A good place to start is with the hello world tutorial, that takes you through setting up an Android virtual machine on your computer and getting the application to run on it.

I also wanted to see an app actually running on my phone so followed the developing on a device guide to get this up and running. I did hit a snag here with the USB drivers, my phone is an HTC desire and there is no driver to download from the HTC site. However if you download the HTC sync software then plug your phone into the USB it should install the driver for you. I had to restart the phone afterwards before it would bring up the menu to select the connection type, eventually the sync software sorted itself out and recognised the phone.

When you select to run the application in Eclipse, your phone should then appear under the ‘Choose a running Android device’ section. The app can be installed on the phone then selected from the usual apps menu.

Comments

I recently ran into an issue with a newly released web application. The test version of the application was performing fine, however the live version kept reporting time out errors. The page that was generating the time outs included a list of links to files stored in a database. After some investigation it became clear that the issue was being caused by the application loading all of these files into memory during the page load (yikes!).

It had worked fine on the test site because the bandwidth between the database and the website was a lot higher and also only a couple of small files had been stored. However the live site was hitting the HTTP request timeout (90 seconds by default) before all of the files had finished loading into memory. There was not actually any need for these files loaded at all during page load, so I set about re-factoring the domain structure to reflect this.

Hurry up and be more lazy!

The application uses NHibernate to map the domain objects to an SQL database, this is an example similar to the object that was causing the performance issue:

public class StoredFile
{
    public virtual string Name { get; set; }
    public virtual string Extension { get; set; }
    public virtual bool Saved { get; set; }
    public virtual byte[] Contents { get; set; }
}

You can see here that the FileContents property is an array of bytes, which will be loaded into memory when the StoredFile object is initialised. However the only properties we need to access during the page load are the FileName, FileExtension and FileSaved properties.

If the FileContents property is moved to a separate object and then NHibernates lazy loading feature can be leveraged to only load that object if it is accessed. The revised domain structure looks like this:

public class StoredFile
{
    public virtual string Name { get; set; }
    public virtual string Extension { get; set; }
    public virtual bool Saved { get; set; }
    public virtual StoredFileContents FileContents { get; set; }
}

public class StoredFileContents
{
    public virtual byte[] Contents { get; set; }
}

NHibernate Mapping Issues

You may have noticed that the StoredFileContents class above does not include a reference to the parent StoredFile object. Originally I had included this reference and attempted to map it following Ayende’s one-to-one mapping blog post. However I hit problems when trying to save, as each record needed to know the primary key of the other record. This was only workable if one of the foreign key tables was set to nullable. In this case, as I don’t foresee there being a need to access a StoredFile from a StoredFileContents instance, I decided it was better to keep the foreign key as non nullable and only map the relationship in one direction.

In case you’re wondering what effect the change had on the application, the page load time was reduced to a couple of seconds (and even less on a decent connection), sorted!

Comments

When developing forms for websites it is good practice to guard against cross site request forgery attacks. In MVC it is straightforward to do this using the AntiForgeryToken() helper method and the ValidateAntiForgeryToken attribute (as explained by Steve Sanderson). However a side effect of this is that an HttpAntiForgeryException like this will be thrown whenever a forgery attack is prevented:

System.Web.Mvc.HttpAntiForgeryException: A required anti-forgery token was not supplied or was invalid.

This is not generally a problem unless the site has been setup to notify you of any exceptions by email. Then you may find that your inbox quickly fills up with spam error reports and I think there is already quite enough spam in the world! The fix for this is to catch the exception before it makes it out of the application and into your inbox. The exception can be caught by adding the HandleError attribute to the controller class declaration as shown below:

[HandleError(ExceptionType=typeof(HttpAntiForgeryException), View="Unauthorised")]
public class MyController : Controller
{
  ...
   public ActionResult Unauthorised()
  {
     return View("Unauthorised");
  }
}

Once the attribute has been added the Unauthorised view should be shown if a forgery attempt is intercepted. However in my case a different exception of the type shown below was thrown instead:

The model item passed into the dictionary is of type ‘System.Web.Mvc.HandleErrorInfo’ but this dictionary requires a model item of type ‘Core.Web.ViewModels.ISomeViewModel’.

This exception is thrown because (as described in this work item on the MVC issue tracker) the default view model has been replaced by a HandleErrorInfo object and our master page is trying to access properties in the normal view model. So the straightforward fix for this is to remove the dependancy on the master page from the Unauthorised view.

Comments

I’ve been working with domain objects for a while now and these are simple tips I automatically follow on new objects. In my case the domain objects are setup to be mapped to a database by NHibernate, however most of these optimisations would be valid for a domain object used with any mapping tool. I’ve found that these changes are quick to implement but can save a lot of hassle in the long run!

1. Make the parameterless constructor private

Obviously you will need a public constructor as well, however this should take parameters. These should be the minimum set of properties that make the domain object valid. In this way you can be sure that whenever you encounter one of these objects in your code it will not have random null properties and cause unexpected null references.

private Customer() {}

public Customer(string firstName, string lastName) {}

2. Add precondition checks in the constructor

The main advantage of this is to ensure that the constructor is used as intended. The precondition checks can be used to make sure that no null or empty parameters are passed into the constructor. When used in tandem with the first tip, you can be sure that you will not encounter any invalid domain objects in your code.

public Customer(string firstName, string lastName)
{
   Check.Require(string.IsNullOrEmpty(lastName) == false,
      "lastName must be provided");
}

3. Initialise your lists properties in the constructor

This particular change may only be needed for NHibernate. A list property can be used to represent a one-to-many relationship between to different classes. For example, typically a Customer object could be related to multiple Order objects, so this would be represented in the Customer class as a list of Order objects. However, if the customer had not placed any orders yet and you tried to access the orders list, without first initialising it, you would get a null reference.

private Customer()
{
   Orders = new List();
}

You will not get this problem if the list is always initialised in the constructor. NHibernate populates the list after the constructor has been called so no actual data will be lost when the list is initialised.

4. Make any Status properties private

A convention we commonly use with domain objects is to represent its state with an enum property. For example an order could be New, Pending or Complete. If the Status property is private then it can only be changed by Methods in the domain object itself. This has two main advantages, firstly any logic that needs to be associated with the status change can be included in the same method. In this way you can be sure that all the required logic is run when the status is changed. For example, you may need to set the order completion date when the status changes from Pending to Complete. Secondly it makes the code much easier to re-factor in future as there will not be calls to set the property spread around the code base.

OrderStatus Status {get; private set; }

public CompleteOrder()
{
   Status = OrderStatus.Complete;
   CompletedDate = DateTime.Now();
}

5. Keep it simple!

OK I admit it, I ran out of tips after four! But I think this is a valid point. There is nothing worse than discovering a domain object of 500 plus lines of code in a project you need to maintain. It is best to keep it simple and if you find that too much behaviour is associated with one object then either split it into smaller domain objects or move the behaviour into a separate service class.

So those are my top 5 tips for domain objects. I’d be interested to hear opinions on these, along with practices that anyone else employs for domain objects so feel free to leave comments.

Comments

Last Monday I made the trip to London to take the EPiServer CMS certification exam (version 6). I passed but it was quite a tricky exam so I thought I’d post some tips that may be of help to others taking the test.

The questions are randomised so you won t get asked the same as me but the areas will probably be similar. There were 70 multiple choice questions split into four sections. I can’t remember the exact breakdown but these numbers are close:

Installation / deployment (~10 questions)

These questions are not particularly difficult but if, like myself, you haven’t needed to use the features much previously you might get stuck.

  • Deployment center make sure you know everything you can do from here
  • Initialization module What is it, when does it run etc (this is new to version 6, I missed the tech note and wished I’d read it)
  • Multi-Site installations
  • Upgrading to v6 What versions can you upgrade from, what is backed up / updated.

General Product Knowledge (~15 questions)

If you are familiar with the system and its features there is not much to worry about here

  • Load balancing
  • Page type & page template concepts
  • XForms - How to make one, how it works
  • Online center and gadgets

Standard Development (~25 questions)

Again, if you have developed a couple of sites then most of these are not too bad. However the customisation questions will be sticking points unless you are familiar with the tech notes.

  • Wiring up EPiServer / .NET web controls
  • Wiring up master pages
  • Custom membership provider
  • Custom virtual path provider
  • Globalization What language is used in various scenarios

Advanced Development (~20 questions)

These questions are really tricky, and may involve quite a bit of guess work!

  • Mirroring How is it setup / configured, what is mirrored
  • Scheduler service What can and can t be run
  • Dynamic data store
  • Page Objects (I missed this one completely)
  • Filters adding code to a filter web control
  • Quick publishing configuration
  • Plugins / Modules Installing

Preparing for the exam

To help pass I d recommend in order of priority:

  1. Install the example site and run everything you can in the deployment center
  2. Try everything out in the CMS Online center (the Start page and menu bar) editor and admin sections while reading through the editor and admin manuals (particularly the admin manual)
  3. Read all the tech notes and try to setup what they are describing. I wouldn’t worry about spending too much time on each though as long as you understand the concepts.

There are quite a lot of resources available online and it can be a bit overwhelming. But don’t despair, Jonathan’s handy exam bookmarks post is a good place to start!

Copyright © 2016 - Hook Technologies Ltd - Powered by Octopress