Friday, 14 December 2012

Anchors lost on Safari when rewriting from https to http

Had an annoying problem today that I couldn't find a fix for. We have some rewrite rules that take care of enforcing which pages should be served over https and which over http. We have a link from one of the secure pages to an anchor (#myanchor) on an unsecured page.

Safari strips the anchor from the end of the URL when navigating this link. It forgets it was ever requested, presumably because the change from https to http is actually seen as a fundamentally different URL. I'm sure this is a Safari bug but intend to do a bit more digging when I have a moment, and my MBP at hand, and am not limited to working on an iPhone.

My hacky fix was to allow this unsecured page in particular to be served over HTTPS.

Monday, 10 December 2012

CKEditor placeholder text

I had to implement some placeholder text in CKEditor recently. It's more complex than you might think, and after some quick consideration I sought a plugin for it. I ended using this one, which was dead easy to implement and worked without any problems at all.

Tuesday, 20 November 2012

Easily attach to IIS process in Visual Studio

Perhaps I'm a bit late to the party here but I just discovered VSCommands which has just come in particularly handy for my current project, which involves attaching to IIS when debugging.

This tool has turned a rather laborious 4-click menu-based process into a one-click dream from my toolbar. It looks like there's plenty more than this available too but for now I'm happy with this little godsend.

Update: VSCommands just stopped me completely screwing up a project with an accidental drag and drop of a folder in my Solution Explorer. This is cool stuff:


Wednesday, 10 October 2012

Return content in ASP.NET with 503 Service Temporarily Unavailble

I tried to do this today on a nice looking holding page while we were doing some site maintenance:
Response.StatusCode = 503;
HttpContext.Current.Response.StatusDescription = "Service Temporarily Unavailable";
The problem was that my nice-looking content never got displayed. Instead, the user was presented with an ugly "The service is unavailable." page. To overcome this is a one-liner:
Response.TrySkipIisCustomErrors = true;

Wednesday, 26 September 2012

UITableView with static cells not showing

I'm still a noob at Xcode iOS development, and today I was trying to build a nice-looking input/edit form using a UITableView with grouped static cells. It looked good on my storyboard but when debugging the cells just wouldn't show up. The reason? I was implementing three methods that shouldn't be there at all when using static cells. I deleted them and bingo, it worked. Here they are:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
}

Friday, 14 September 2012

Can't install Xcode from Mac App Store

I needed to do some iOS development yesterday which required direct testing on my iPhone, but since I last connected my phone to Xcode it's OS has been updated which means I need the new iOS SDK, which comes with Xcode.

So I went to the Apple Developer centre, found the download link that opens up the Mac App Store, clicked the 'Install' link and literally nothing happened. No error messages, no download....nothing.

After some googling I pieced together some bits of advice from around the interweb and finally fixed it by typing the following into my terminal, then deleting my existing Xcode.app and Install Xcode.app, and then fully restarting my machine. None of these steps worked on their own, or without the restart!

rm ~/Library/Preferences/com.apple.appstore.plist
rm -r ~/Library/Saved\ Application\ State/com.apple.appstore.savedState
rm -r ~/Library/Caches/com.apple.appstore
rm -r /private/var/folders/*/*/*/com.apple.appstore

Tuesday, 11 September 2012

dmg image data corrupted - dowloading from Virgin Media Broadband

You've probably landed here because you're a Virgin Media Broadband customer and every time you download a disk image file (.dmg) or indeed any large file it appears to be a successful download until you try to open it. Attempting to mount or verify the image returns "image data corrupted" and the file is useless.

I've had this problem for months on my Macbook Pro, OSX Lion. Downloading from another ISP is never a problem - and today I had to download my new Ruby on Rails IDE Rubymine 4.5.4 (106MB) over 3G with Orange because Virgin Media wasn't playing ball again.

I spoke to Virgin about this problem tonight, and despite seemingly dozens of customers suffering the same problem they don't have a solution. So...it looks like I'll switching my broadband supplier soon.

Update: They sent me to their forum, where I was told to leave a comment on the wrong thread. I eventually found a more suitable thread where I left a comment. This got picked up and they sent out some new kit - a Superhub. Problem solved!

Tuesday, 24 July 2012

Using Examine and Lucene to search Umbraco content

I'm a relative noob with Umbraco, but today I was tasked with building content search functionality on the e-commerce site I'm currently building.

This post, Examining Examine, was invaluable, as was the Lucene index query tool Luke.

Got it all working in a couple of hours - job done!

Thursday, 28 June 2012

Blocking UI while loading Ajax UpdatePanel

To display a loading image and block the user interface while awaiting new content for an updatepanel you can put this JS code at the bottom of your master page. This uses the jquery.blockui.js plugin and will work site-wide:

Monday, 18 June 2012

Reverse Windows mouse scroll wheel

You're so used to the mouse wheel direction in OSX Lion that you want to reverse your mouse wheel in windows, right? Just change every entry in your registry for 'flipflopwheel' to '1' instead of '0'. Simples.

Wednesday, 13 June 2012

Elmah and MVC - 404 and 403 access and permission errors

I've said it before and I'll say it again - I love Elmah. But today I had trouble getting it to work with my latest MVC project which is due for launch. It took some googling to find out exactly what the problem was, and I had to piece together hints and tips from across the web. So, in short, take the latest Elmah.dll and drop it into your bin directory. Add this line to your RegisterRoutes method in Global.asax.cs:
routes.IgnoreRoute("elmah.axd")
Then you need to configure your webconfig file like my gist on github. Just look for all the 'Elmah' bits and do the same. Then visit http://yourserver/Elmah.axd and you'll see your error logs. Cool huh?

Monday, 11 June 2012

See 'EntityValidationErrors' property for more details

This morning I was doing a db.SaveChanges() and getting the error:
See 'EntityValidationErrors' property for more details
I'd seen this umpteen times before and always resolved it quickly without having to to look at the EntityValidationErrors property. This morning however I couldn't work our where it was failing, and what field I needed to pay attention to, so I really did need to look into this property. After a bit of googling and good old Stack Overflow, I found this to be the easiest way. Simply put the following into your watch list:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

Saturday, 2 June 2012

Using hyphenated data attributes in MVC

In .net MVC this doesn't work:
@Html.TextBox("name", null, new { @class = "input-xlarge", @data-input = "75"})
The hyphenated 'data-input' attribute causes the error "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access." Well, as of MVC 3, you can actually use an underscore instead, like so:
@Html.TextBox("name", null, new { @class = "input-xlarge", @data_input = "75"})
And it'll handle it for you, converting it to a hyphen. It knows you want a hyphen rather than an underscore as underscores aren't valid in html attributes. Lucky huh?

Wednesday, 2 May 2012

asp.net MVC 403 error when deployed to IIS7.5

Today I had to deploy my test .Net MVC app to Win Server 2008, IIS7.5, but I kept getting a 403 forbidden error when visiting the site. It turned out that despite setting my app pools to use .Net 4.0 you have to register .Net 4 with IIS. I'm not sure if I've understood it correctly or got my terminology correct, but this command-prompt solution I found on StackOverflow sure hit the spot:
cd \
cd Windows\Microsoft .NET\Framework\v4.xxx.xxx
aspnet_regiis -i
Big-up to Michael Shimmins

Monday, 30 April 2012

Twitter Bootstrap datepicker British format dd/mm/yyyy

This morning I've been using Scott Storborg's Twitter Bootstrap datepicker (which I believe he has now pulled from Github), which looks and works beautifully, but wasn't in my required date format. I couldn't find much documentation on how this might be modified, but I figured out the following works:

Friday, 27 April 2012

Cross-browser safe javascript console logging

You can keep this in your js code and it won't error on non-supporting browsers:
if(window.console.log&&window.console){window.console.log('This is safe!');}

Friday, 13 April 2012

Setting a P3P header in Rails - Session cookies in iframes in IE

Friday 13th, and today I spent far too long battling with a problem that I should have recalled from a previous skirmish. Never shall I forget again!

Some versions of IE, on some versions of Windows, have stricter policies regarding 3rd party content served through an iframe. Confusingly, the same browser (IE8 for example) will behave differently on different Win versions: some will allow session cookies, and some won't. You know you've been nobbled when you see the evil eye at the bottom of the browser with a red sign on it.

The way round this is to send a P3P header with a compact privacy policy in your iframed content:
class ApplicationController < ActionController::Base
...  
  before_filter :set_p3p
...
  private
    # for IE session cookies thru iframe
    def set_p3p
      headers['P3P'] = 'CP="ALL DSP COR CURa ADMa DEVa OUR IND COM NAV"'
    end
end

Thursday, 22 March 2012

Rackspace cloud Ubuntu install LAMP

Everything up to date with package manager:
apt-get update
apt-get upgrade --show-upgraded

Install everything:
apt-get install apache2 php5 libapache2-mod-php5
apt-get install mysql-server mysql-client php5-mysql
mysql_secure_installation
apt-get install phpmyadmin

Restart Apache:
/etc/init.d/apache2 restart

Check ImageMagick configuration

$ convert -list configure

Wednesday, 21 March 2012

Specifying the endpoint when accessing Amazon AWS S3 bucket

"The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint."

I got this error today when using the aws-s3 Gem. Perhaps it works out-of-the-box for those in America, but I chose Ireland to store my images, and the solution to the above was this line:
AWS::S3::DEFAULT_HOST.replace "s3-eu-west-1.amazonaws.com" 

Friday, 9 March 2012

Setting up Sendgrid mail for Spree on Heroku

The free mailing functionality for Heroku is provided by Sendgrid.net, and allows your site to send up to 200 emails a day for no charge. Just perfect for my new low-traffic Spree e-commerce site that I've just built, but I did have some trouble working out to set it up. Here's how I got it working.

Firstly, enable Sendgrid on your Heroku app:
$ heroku addons:add sendgrid:starter
Then, run:
$ heroku config
this will reveal the SENDGRID_PASSWORD and SENDGRID_USERNAME values which you need for the next step:
SENDGRID_PASSWORD   => dju45yhb
SENDGRID_USERNAME   => app37263528@heroku.com
Now go to the Configuration pages in your Spree admin interfaces and add a new mail method. Take a look at this screenshot to see what settings I used:

Tuesday, 6 March 2012

Datetime field presentation in ASP.NET MVC and Rails views

There are plenty of similarities between ASP.NET MVC and Rails, but I do keep stumbling across things that set them apart.

I used MVC's scaffolding today to build me the standard CRUD-y interfaces. Some of my fields were datetime fields, and to my disappointment the interfaces I was given provided simple text input fields which clearly I'll have to modify to restrict entry to a date format.

This is in stark contrast to Rails, with which only last week I was doing the same thing - and the date fields were dd/mm/yyyy drop-downs. Nice.

Friday, 2 March 2012

Using the @ symbol in content with ASP.NET MVC3's Razor

Razor’s language parser is clever enough in most cases to infer whether a @ character within a template is being used for code or static content.  For example, below we're using a @ character as part of an email address:
An email was sent to edpitt@edpitt.com at: @DateTime.Now 

When parsing a file, Razor examines the content on the right-hand side of any @ character and attempts to determine whether it is C# code (if it is a CSHTML file) or VB code (if it is a VBHTML file) or whether it is just static content.  The above code will output the following HTML (where the email address is output as static content and the @DateTime.Now is evaluated as code:
An email was sent to edpitt@edpitt.com at: 3/2/2012 1:23:24 PM

In cases where the content is valid as code as well (and you want to treat it as content), you can explicitly escape out @ characters by typing @@.

Thursday, 1 March 2012

Spree performance in development mode - precompiling assets

Important note, borrowed directly form the Spree help docs. Rails 3.1 introduced the concept of the asset pipeline. Unfortunately this causes some significant performance issues when running Spree in development mode. The good news is you can improve performance significantly by using a special precompile task.

$ bundle exec rake assets:precompile:nondigest

Using the precompile rake task in development will prevent any changes to asset files from being automatically included in when you reload the page. You must re-run the precompile task for changes to become available.

Rails also provides the following rake task that will delete the entire public/assets directory, this can be helpful to clear out development assets before committing.
$ rake assets

Wednesday, 22 February 2012

Gov.uk portal - the poster child for Agile Railers and Responsive Designers



The new Gov.uk portal is still in Beta, but already we can see that the Government Digital Service really are doing things differently to what we might have come to expect of government IT projects. An in-house team with good leadership have been given the freedom to use a leading-edge approach to design and build. They are Agile, they use Ruby on Rails, they are on GitHub, and their interface uses responsive design.

Rapidly disappearing are the days when big organisations demand MicroSoft. That Marketing Director with the six-figure budget no longer needs to fear open source technology - if the Government uses it, it must be ok!

Digital agencies that use open source technologies will start to get pitches for the bigger projects they may have been previously excluded from, and Gov.uk will no doubt become the poster-child of open-sourcers, agilers, railers and responsive designers in the UK and possibly worldwide. Rightfully so. Big-up the GDS!

Thursday, 16 February 2012

Flurry analytics gathering UDID - as seen in mitmproxy

I had a play with mitmproxy today and opened a few apps on my phone to see what kind of traffic was going on. An interesting point of note was the use of Flurry in the Met Office app, and the fact that it sends my UDID over the network to a mahoosive database. Flurry and other mobile analytics tools are quite commonplace so there's nothing sinister about the Met Office app in particular (Rightmove and Pinterest are two others on my phone that I could have picked on), but the UDID can reveal a lot about a user and ultimately identify them. For identical privacy concerns Google Analytics stopped revealing visitors' IP addresses several years ago, if my memory serves me correctly. Anyhow, here's a snapshot from mitmproxy:








It's worth noting that Apple have deprecated the use of UDID in iOS5 and it'll presumably die sometime in the not too distant future. Just like losing IP addresses was no biggy for Google, losing UDID will surely be no biggy for the likes of Flurry.

Bigger losers might be some app developers that have used UDID in some fundamental manner to identify users - not for any creepy tracking or marketing way but as a convenient (lazy?) means of identification or authentication.

I'm pretty sure I wasn't asked about sharing data with Flurry when I installed any of my apps, but I did find this link where you can tell Flurry you don't want your activity monitored.

Switching Rails app from SQLite to Postgres

I decided that my new Rails app was to be hosted with Heroku, but I decided it a little too late, having already built most of it using, by default, SQLite. I tried to wing it and hope that there would be no compatibility problems, but I was getting errors in some db queries on Heroku that I wasn't seeing locally on SQLite.

So, time to switch my app to Postgres. This Youtube video gave me most of what I needed about installing Postgres on my Mac, but because I'm running Lion I then needed to consider this stackoverflow thread too, as only at this point did I learn that postgres is bundled into Lion already.

Once postgres was installed and running I created a database named myRailsApp_development and gave it a user (all shown in the youtube video linked above), and modified the database.yml file in my Rails app thus:

development:
  adapter: postgresql
  encoding: utf8
  database: myRailsApp_development
  pool: 5
  username: myUser
  host: localhost

Then I ran rake db:migrate, and it all worked!

Tuesday, 14 February 2012

NSDate from Rails datetime via JSON

I'm building an iPhone app that uses a Ruby Rails JSON api and frequently I need to convert the Rails datetime string into an NSDate object. Here's how its done:

NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSDate *myDate = [formatter dateFromString:@"2012-02-14T12:01:41Z"]; 

and then if you need to display this later, you can convert it back to a string like this, where I display it in a British dd/mm/yyyy format:

[formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
myLabel.text = [formatter stringFromDate:myDate];

Wednesday, 8 February 2012

Environment-specific configuration in iOS / Xcode

Specifying different config values for your different environments in Xcode (Debug, Release etc) can be achieved in different ways, but this great blog post explains one method in detail.

In summary this approach adds a new Configuration/${CONFIGURATION} Key/Value to the main plist file, a new plist file specifying values, and a singleton to load up and share the values throughout your code.

I won't repeat it in detail. Take a look yourself.

Tuesday, 7 February 2012

Emails from Devise on localhost

Need to get your Devise email notifications working in your development environment on localhost? Just drop this into your development.rb config file:

  config.action_mailer.default_url_options = { :host => 'localhost:3000' }

  config.action_mailer.delivery_method = :smtp

  config.action_mailer.smtp_settings = {
    :enable_starttls_auto => true,
    :address => "smtp.gmail.com",
    :port => 587,
    :domain => "gmail.com",
    :authentication => :login,
    :user_name => "test@example.com",
    :password => "Test123",
  }

Adding 'confirmable' to Devise

I found myself needing to add 'confirmable' to Devise today, and I wish I'd installed it in the first place. For this you need the following migration:

class AddConfirmableToUsers < ActiveRecord::Migration
  def change
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime
    add_column :users, :unconfirmed_email, :string
  end
end
Initially I missed out the 'unconfirmed_email' column, but it transpired I needed it - I'm not entirely sure why because I've yet to see any emails go into there, even unconfirmed ones. Not including it produced errors. And of course you need to add ':confirmable' to the list of modules specified in your user.rb model. Mine looks like this:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable,
         :registerable,
         :recoverable,
         :rememberable,
         :trackable,
         :validatable,
         :token_authenticatable,
         :confirmable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
end

Wednesday, 1 February 2012

TestFlight for distributing and testing beta iOS apps

Just had my first play with TestFlight. It's an online service that takes the pain out of distributing for testing iOS apps. I'm mighty impressed, even though all I've done so far is recruit a single tester and upload and distribute a simple test iPhone app (.ipa file) to him and myself. The process went like a dream and the information and control you get is amazing.



There's loads more to it - for example download the TestFlight SDK and it'll give you full diagnostic info about crashes as well as details about your testers' usage sessions. And all for free (for how long I wonder?). Amazing!

Tuesday, 31 January 2012

AudioToolbox.framework missing required architecture i386 in file

"AudioToolbox.framework/AudioToolbox, missing required architecture i386 in file"

Had this error today when building to iPhone 5.0 Simulator. I fixed it simply by removing and re-importing the AudioToolbox framework into the project.

Weird.

Friday, 27 January 2012

iPhone keyboard - hide when done

Ever got stuck in a form using an iPhone app? You've edited a text field but you're left with the keyboard hiding the form submit button. I have, and its bloody annoying (most recently in the otherwise excellent pixlr-o-matic app), and it almost feels like some fundamental Apple design flaw. But you should blame the developer, because what he/she forgot to do was tie an action to the text field's 'Did End On Exit' event.

The keyboard hiding method declared in the action just needs to do one thing - resign the text field as first responder, like so:
[yourTextField resignFirstResponder];
And, to make things even better for your user, change the return key to 'Done' in your Attributes Inspector.

And even better still, create a big invisible custom button behind all your other controls and attach it to your keyboard hide method too. This will comply with the common convention that a touch outside of any controls kills the keyboard.

Tuesday, 24 January 2012

Return user to paginated list page after delete or edit event

The easy way to send your users back the same list page (page number, ordering) they were on prior to selecting an item for edit (or deleting it non-ajax style with full postback) is to store the referring path in session and redirect to it when the task is done, like so:
def destroy #or whatever you're handling
  session[:return_to] = request.referer
  #do whatever you need to do here
  redirect_to session[:return_to]
end

Friday, 20 January 2012

Regular expression regex for validating email addresses

I've seen a few of these in my time, but this one has been serving me well...found in Michael Hartl's Rails book:
/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

Wednesday, 18 January 2012

Using the Visual Studio 'Consolas' font in RubyMine

The default font in Visual Studio 2010 is the lovely 'Consolas'. So lovely in fact that I wanted it on my Mac, specifically for my Rails IDE, RubyMine. After a little googling I found the answer here.

The gist of it is
  • Download the Open XML File Format Converter for Mac
  • Open its contents, and find and install the package 'OpenXML_all_fonts.pkg'