Moving from Canada to London to Work as a Freelancer

Earlier this year I’ve moved from Canada to London, UK. I moved for the great tech industry here in London and also for my love of Europe. I’m here on an Ancestry Visa, but upon arriving there was a lot more setup work to get established in England than I had originally expected… so I’ve decided to blog about it!

The first thing I did upon arrival… was get a SIM card! I had previously been with Vodafone when I lived in Europe before, so I got a pay as you go account with them here in the UK with an unlocked mobile I had previously owned. If you have credit in England and want a good priced contract phone, I’ve been recommended Carphone Warehouse.

Almost everything here requires an address. The best flat finding site I used was SpareRoom. Other popular sites include rightmove and Gumtree. Be aware of SCAMS however, it’s a problem in London. Initial deposits for a room or entire flat can be quite large, but it tends to range from around 1-1.5x what a month of your normal rent would cost. It’s common to pay either per week (pw) or per month (pm) with either cash or bank transfers.

Once you get an address, if you’re on a visa which allows work, you can apply for the National Insurance (NI) number. This is the number you will give an employer and is equivalent to a SIN number in Canada. You must phone first and give all your details to get an application started. The application package will take up to 2 weeks to be mailed to your address. Once you receive the package, you must complete it within the time required and then mail the application back in the envelope provided. Up to another 4 weeks can go by before you receive  your NI number in the mail, however, you’re able to start work without an NI number if you can show an employer that you have the right to work in the UK.

Opening a British bank account was a bit harder than I had anticipated. You must make an appointment first to open an account at a branch. Some nationalities will have to have proof of permanent address before opening a bank account, which can include a recent utilities bill, bank statement, or something similar that has been mailed to you within the last 3 months. If you’re just moving a good thing to use can be your NI letter you received with your application package. I went with Lloyds Bank after receiving good recommendations from people I know and also because at Lloyds, Canadians, along with several other nationalities, do not need proof of permanent address. You do however need an address that your bank card and PIN number can be mailed to. I would suggest opting into paper statements to start as a way to collecting proof of your address. Long-term proof of address can be required for things like exchanging your driver’s license for a UK license.

It’s a good idea to register with a GP in your area once you have found a permanent address. There are many NHS clinics around town, so you must live in a catchment area of a clinic in order to be able to register there. Most clinics will show on their website which areas they provide service to. Once you have registered with a clinic, you will be mailed an NHS info card within 4-6 weeks which will have your NHS number.

The final step to working for yourself in the UK is to register as a sole trader with HM Revenue & Customs (HMRC) taxes. This at least is a simple online application, but it will require your NI number. Once the application is submitted they say it will take about a week to receive your info in the mail, which will include your business number.

Phew! It can be tiring to get setup in England! I’m glad I’m on my way there and hope this can help any other new arrivals through the process!

Advertisements
Moving from Canada to London to Work as a Freelancer

Promise Me It’s Over: A Web Audio Node Thing

Recently while working on Waveform Playlist, which can schedule multiple audio tracks playing with the web audio API, I ran into the problem of being able to stop and start my web audio playout in quick succession in javascript. This was needed when a user seeked to a different part of the playlist while it was currently playing. In brief, the code I had in Waveform Playlist to accomplish the above had looked something like this:

this.stop();
this.start(newStartTime);

The stop method was responsible for stopping each track in the playlist and clearing the old node graph, while the start method setup a new web audio node graph to continue playout from the new chosen starting time.

The result I got was

  1. playlist stopped
  2. playlist started
  3. … then playlist immediately stopped again?

I was confused for a moment, but then realized I had just refactored the project to use the newer onended callback provided by AudioBufferSourceNode to better manage cleanup when the audio had stopped/ended. Originally when the project had started in early 2013, this callback wasn’t available. This incorrect behaviour was the workings of the javascript event loop. For those needing a refresher on how the event loop schedules tasks to execute, this great article from last week can catch you up.

It turns out now, my stop function was called, then my start function, but then all the onended callbacks would execute right afterwards. To get around this problem and make sure I knew the moment when every track in the playlist had stopped, I wrapped the web audio nodes setup into a Promise. Again if you’re new to promises, here’s a great article to get started with.

Below is the function used to setup the web audio node graph.


setUpSource: function() {
    var sourcePromise;
    var that = this;

    this.source = this.ac.createBufferSource();
    this.source.buffer = this.buffer;

    sourcePromise = new Promise(function(resolve, reject) {
        //keep track of the buffer state.
        that.source.onended = function(e) {
            that.source.disconnect();
            that.fadeGain.disconnect();
            that.outputGain.disconnect();
            that.masterGain.disconnect();

            that.source = undefined;
            that.fadeGain = undefined;
            that.outputGain = undefined;
            that.masterGain = undefined;

            resolve();
        }
    });

    this.fadeGain = this.ac.createGain();
    //used for track volume slider
    this.outputGain = this.ac.createGain();
    //used for solo/mute
    this.masterGain = this.ac.createGain();

    this.source.connect(this.fadeGain);
    this.fadeGain.connect(this.outputGain);
    this.outputGain.connect(this.masterGain);
    this.masterGain.connect(this.destination);

    return sourcePromise;
}

The onended callback is fired both when the track plays out naturally, as well as when it’s manually stopped. Every time I scheduled a track to play, I would keep a reference to the Promise returned from the setup, something like this.

var playoutPromise = track.play(startTime, endTime)

Within the track’s play method setUpSource was called, which created the playoutPromise. Keeping a reference to a Promise for every track in the playlist, my newly updated code from before to seek to a different spot in the audio could now look something like

this.stop();
Promise.all(playoutPromises).then(this.start.bind(this, newStartTime));

This ensures that the start method will only run after all the onended callbacks for each track has finished executing.

Those are the basics to restarting multiple sounds using the web audio API! Now go back to making music!

Promise Me It’s Over: A Web Audio Node Thing

Password Reminders with Sentinel and Laravel

Previously I had written how users could change their passwords with Sentinel when they were logged in, making sure their current password was verified before the update occurred. Now there’s the next problem about how a user can change their password if they’ve totally forgotten. Luckily that’s built into Sentinel and is easy to implement!

I decided to create a separate repository for a simple Sentinel 2.0 and Laravel 5.1 implementation, which can be found here. All code from this tutorial is available there, relative snippets will be discussed in this post.

Again, if you haven’t setup Sentinel yet, there’s info for Laravel 5 and Laravel 4. For Laravel 5.1 I’ve just made the small change in config/app.php for my imports to look like this:

$providers array

Cartalyst\Sentinel\Laravel\SentinelServiceProvider::class,

$aliases array

'Activation' => Cartalyst\Sentinel\Laravel\Facades\Activation::class,
'Reminder'   => Cartalyst\Sentinel\Laravel\Facades\Reminder::class,
'Sentinel'   => Cartalyst\Sentinel\Laravel\Facades\Sentinel::class,

Copy the providers and facades first and then run the packages’ publish command.

I’ve setup my User model for Sentinel’s multiple login attributes like I blogged about previously.

Four new routes will be required to complete this feature.


Route::get('passwordreset/{id}/{token}', ['as' => 'reminders.edit', 'uses' => 'ReminderController@edit']);
Route::post('passwordreset/{id}/{token}', ['as' => 'reminders.update', 'uses' => 'ReminderController@update']);
Route::get('passwordreset', 'ReminderController@create');
Route::post('passwordreset', 'ReminderController@store');

Most of the main code for this password reset feature can be found in a new controller I’ve named ReminderController.


class ReminderController extends Controller
{
  public function __construct(UserRepository $userRepository)
    {
        $this->users = $userRepository;
    }

    public function create() {
        return View::make('reminders.create');
    }

    public function store() {
        $login = Input::get('login');

        $user = $this->users->findByLogin($login);

        if ($user) {
            ($reminder = Reminder::exists($user)) || ($reminder = Reminder::create($user));

            Event::fire(new ReminderEvent($user, $reminder));
        }

        return View::make('reminders.store');
    }

    ...
}

The ReminderController@create method above is used to render a form, which will ask the user to enter either their username or email to retrieve their password. Once they have completed that form, the input is sent to the ReminderController@store method. This method checks if a user with that information is present within the system, and if so creates an instance of a Reminder model. The user will have to match the code that is stored within the Reminder model, within a specific amount of time, in order to change his or her password. The method Reminder::exists($user) will return an existing Reminder object within the system if an uncompleted one already exists for that user and has not expired, otherwise it will return false. The code above will then fallback to the method Reminder::create($user) if no valid Reminder is currently present within the system for the user, which will create a new Reminder object for us to work with.

ReminderController@store throws an event which the system will listen for. A reminder email listener is registered to react to this event, which will send the user a link, to their stored email address, they can click to reset their password.


class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        'App\Events\ReminderEvent' => [
            'App\Listeners\ReminderEmailSender',
        ],
    ];

    ...
}

class ReminderEvent extends Event
{
    use SerializesModels;
    public $user;
    public $reminder;

    public function __construct(User $user, Reminder $reminder)
    {
        $this->user = $user;
        $this->reminder = $reminder;
    }
}

class ReminderEmailSender
{
    public function handle(ReminderEvent $event)
    {
        $user = $event->user;
        $reminder = $event->reminder;

        $data = [
            'email' => $user->email,
            'name' => 'Fake Name',
            'subject' => 'Reset Your Password',
            'code' => $reminder->code,
            'id' => $user->id
        ];

        Mail::queue('emails.reminder', $data, function($message) use ($data) {
            $message->to($data['email'], $data['name'])->subject($data['subject']);
        });
    }
}

Below is the email template emails.reminder. The user’s id is included in the password reset link as per Sentinel’s documentation on finding the user by id first. If you’re trying to find a user only by their Reminder code, you’ll have to write your own method to do so.

<body>
A request has recently been made to change your password.

{!! link_to_route('reminders.edit', 'Reset your password now', ['id' => $id, 'code' => $code]) !!}
</body>

When the user opens the email and clicks the link, they will activate ReminderController@edit. This action will show the user a view which will provide them an input to enter a new password, as well as a second input to confirm their new password. The Reminder::exists($user, $code) method checks if there is a non expired Reminder object for that particular user and if it matches the code that the user is sent via email. If everything goes well, the Reminder object is returned, otherwise false is returned and we’ll just exit back to the homepage.

reminders.edit View.


{!! Form::open(['reminders.update', $id, $code]) !!}
    {!! Form::password('password', array('placeholder'=>'new password', 'required'=>'required')) !!}
    {!! Form::password('password_confirmation', array('placeholder'=>'new password confirmation', 'required'=>'required')) !!}
    {!! Form::submit('Reset Password') !!}
{!! Form::close() !!}

class ReminderController extends Controller
{
  public function __construct(UserRepository $userRepository)
    {
        $this->users = $userRepository;
    }

    ...

    public function edit($id, $code) {
        $user = $this->users->findById($id);

        if (Reminder::exists($user, $code)) {
            return View::make('reminders.edit', ['id' => $id, 'code' => $code]);
        }
        else {
            //incorrect info was passed
            return Redirect::to('/');
        }
    }

    public function update($id, $code) {
        $password = Input::get('password');
        $passwordConf = Input::get('password_confirmation');

        $user = $this->users->findById($id);
        $reminder = Reminder::exists($user, $code);

        //incorrect info was passed.
        if ($reminder == false) {
            return Redirect::to('/');
        }

        if ($password != $passwordConf) {
            Session::flash('error', 'Passwords must match.');
            return View::make('reminders.edit', ['id' => $id, 'code' => $code]);
        }

        Reminder::complete($user, $code, $password);

        return Redirect::to('/');
    }
}

When the user posts back their new chosen password to ReminderController@update, again the User and Reminder objects are located by $id or $code, and if everything looks good finally the Reminder::complete($user, $code, $password); method is called to update the user’s password.

Password Reminders with Sentinel and Laravel

Changing a User’s Password with Sentinel and Laravel

Today I was throwing together a change password page (NOT a forgot password page, I’ll write that tutorial up shortly…) in an application using Sentinel and Laravel and thought I might as well post another tutorial on Sentinel as examples are rather hard to come by currently.

Two new routes are added to routes.php for the feature. The /resetpassword route will render our form and we will post our new password information to route /resetpasswordcomplete. These routes should only be available to users that are currently logged into the system. You can achieve this with either route filters in Laravel 4 or middleware in Laravel 5.


Route::get('resetpassword', array('as' => 'reset.password', 'uses' => 'PasswordController@edit'));
Route::post('resetpasswordcomplete', array('as' => 'reset.password.complete', 'uses' => 'PasswordController@update'));

We’ll start creating a view. This example looks for a view at views/passwords/reset.blade.php. I’m using Blade templates so it looked something like this:


@if (Session::get('error'))
  <div class="alert alert-error">
    {{ Session::get('error') }}
  </div>
@endif

{{ Form::open(array('route' => array('reset.password.complete'))) }}
  {{ Form::password('old_password', array('placeholder'=>'current password', 'required'=>'required')) }}
  {{ Form::password('password', array('placeholder'=>'new password', 'required'=>'required')) }}
  {{ Form::password('password_confirmation', array('placeholder'=>'new password confirmation', 'required'=>'required')) }}
  {{ Form::submit('Reset Password', array('class' => 'btn')) }}
{{ Form::close() }}

There’s a form field for the user’s current password, the user’s requested new password, and a confirmation for the new password.

Below is a snipped of what our PasswordController would look like, with its edit and update actions as necessary. The Sentinel facade provides the method Sentinel::getHasher() to retrieve the application’s current hashing strategy. Sentinel provides several hashing strategies documented here. The edit action just provides the form needed to reset the password and the update action checks the received info and makes sure the user entered their current password correctly as well as entered the same password in form fields password and password_confirmation.


    public function edit() {
        return View::make('passwords/reset');
    }

    public function update() {
        $hasher = Sentinel::getHasher();

        $oldPassword = Input::get('old_password');
        $password = Input::get('password');
        $passwordConf = Input::get('password_confirmation');

        $user = Sentinel::getUser();

        if (!$hasher->check($oldPassword, $user->password) || $password != $passwordConf) {
            Session::flash('error', 'Check input is correct.');
            return View::make('passwords/reset');
        }

        Sentinel::update($user, array('password' => $password));

        return Redirect::to('/');
    }

That’s all for letting a user change their password while they are logged in and can remember their password. Next up I’ll write a short tutorial on how to use Sentinel’s Reminder capability for users who have forgotten their passwords.

Changing a User’s Password with Sentinel and Laravel

Thoughts on the Book “Instant Audio Processing with Web Audio”

I’ve recently just finished reading Packt Publishing’s book Instant Audio Processing with Web Audio by Chris Khoo.

Earlier this year I started looking into the new Web Audio API as I was busy researching how to build a timing-precise audio preview javascript library for work, which is available on my github account here. Web audio has opened many new possibilities in the browser and is quite exciting if you have any type of project that is sound-based or will incorporate a lot of audio.

As the API is relatively new and is currently being standardized, it is harder to come across a variety of useful examples to get started with. This book can get you up and running with many shorter code examples all set up with HTML/CSS. Overall it is a relatively short book at 76 pages, but provides a bonus section for download including another 26 pages of material.

I thought it was a little strange that the bonus section included the basic material such as initializing and playing back a sound sample. My first opinion was that the book spent too much time diving into talking about the “custom framework” that was used as scaffolding for the variety of examples included, and also diving immediately into UI presentation and function of the examples with HTML/jQuery. The basic usage of the API could have just been shown in the book via direct sequential javascript calls to get the fundamentals in mind first. The book becomes more valuable in its later chapters, however, when explaining and presenting ways to achieve audio ducking and build a 5-band equalizer. More visuals are then used to teach different types of audio fades and explain the examples using a graph of Web Audio API nodes.

Overall this book is a good place to refer to for more in-depth examples when learning the API and reading Web Audio’s working draft.

Thoughts on the Book “Instant Audio Processing with Web Audio”