How I built a PWA with Angular and Firebase Part 2: Ionic and app manifest

This post is part of a series in which I will describe how I built my first PWA, Friendtainer. It will touch on many topics such as Angular 2, Ionic 2, Firebase, service workers, push notifications, serverless architectures. I hope you find it useful when building your own PWAs.

In the previous post I discussed the high-level architecture of the app and the involved technologies.

In this part of the series, we’ll look at how to create a PWA app using the Ionic 2 framework. Additionally, I will talk about the app manifest and how to use it to allow adding the app icon to the device’s home screen.

If you are interested in this topic, check out the JSPoland 2017 conference where Christian Heilmann will be giving a talk about Progressive Web Apps.


As I mentioned in the previous post, there are a couple of requirements that a web app has to comply with in order to be called a PWA. In this post we’ll focus on the items in bold.

  • Looks like a native app on mobile devices
  • Loads fast and supports offline mode
  • Can be launched from the phone’s home screen
  • Runs full-screen
  • May support push notifications (so the phone will display notifications even if the browser is not running)


Ionic is a web/mobile application framework based on Angular. It’s primary goal is to facilitate building hybrid mobile applications. Hybrid mobile apps are apps consisting of two parts – a native wrapper and a web app. The wrapper acts as a bridge between the web app and the device, providing an API to native functionalities.

Although we are not going to build a hybrid app but a PWA, we can still benefit from Ionic. It contains a rich library of UI components which help us build a web app that looks like a native app. What’s more, Ionic detects the platform it’s running on and the components look different on iOS, Android and Windows Phone.

Friendtainer on Android
Friendtainer on iPhone


Ionic comes with it’s own command line tool which you can use to generate the project skeleton as well as particular pages.

Getting started with Ionic

In order to get started with Ionic you need to download it first:

Now you can use the ionic  command line tool. Run this command to generate the project skeleton:

Now you can start adding Ionic pages like this:

Ionic page is basically an Angular component with some added functionality. Every Ionic app has a root component called AppComponent  which hosts the navigation and the current page. Pages form a stack where the topmost page is the one that’s currently visible to the user.

It’s super-easy to create pages using the rich component library provided in Ionic. The documentation is great, providing live examples which demonstrate the look and feel on all supported platforms.

Ionic make it very convenient to develop and test your app. Just run the following command to run it locally in development mode:

Building production package

Once your app is ready you need to deploy it. You need to build a package that contains optimized versions of all the JavaScript files and static assets.

Ionic’s build process is geared towards supporting different target platforms such as iOS or Android. This only applies to hybrid apps. In our case, we want to produce a package that has no dependency on the bridging API. For that we need to specify browser  as the target platform when building the package.

Before deploying your app to production, it’s highly recommended to optimize it. Optimization involves bundling and minifying the JavaScript source code, running Angular AOT (Ahead Of Time) compilation and setting the app in prod mode.

As a result, the optimized package is much smaller and has much better performance.

In order to build the app with the optimizations, use the prod  flag:

The build process can take some time. Once it’s done, you can find your package inside the platforms/browser  directory. It’s just a bunch of static files so you can just drop it on a HTTP server. Or, use Firebase hosting as I did.

App manifest

So far, Ionic helped us deal with providing native-like experience inside the app. How about some elements external to the app? Specifically, I mean home screen integration and the full-screen mode.

The web app manifest specification allows us to control those aspects of the user experience. Manifest file is basically a JSON file containing some metadata about your application. We can use this file to specify the name of the app, the icon to be used on the home screen and whether it should run full screen or not.

Once we provide all this information, some modern browsers (including Chrome) will display a prompt suggesting the user visiting your app to add an icon for it to the home screen.

Chrome home screen prompt

Ionic apps created using the CLI tool already include a manifest file so you just need to modify it. You can find it under the following path:


Below you can find the manifest file for Friendtainer. As you can see, it contains the app title, references to the icon image in several sizes and some info about colors.

Full-screen mode is achieved by setting the display  option to standalone.

Android phones will also provide a splash screen for your app based on the settings found in the manifest file. The splash screen is composed of the app title and the app image. Background and theme colors are also used when showing the splash screen.

Splashscreen based on the above manifest

The remaining two settings starting with the gcm  prefix are related to Google Cloud Messaging. I will describe them in more detail once we discuss push notifications.

To be continued…

How I built a PWA with Angular and Firebase Part 1: Introduction

This post is part of a series in which I will describe how I built my first PWA. It will touch on many topics such as Angular 2, Ionic 2, Firebase, service workers, push notifications, serverless architectures. I hope you find it useful when building your own PWAs.

I’ve spent last month working on my new project. It’s called Friendtainer and it’s a smartphone app which helps you meet with your friends regularly. You can add contacts and decide how often you want to meet. If you fail to record a meeting within given timespan you will start receiving reminders until you record a meeting.

If you are interested in this topic, check out the JSPoland 2017 conference where Christian Heilmann will be giving a talk about Progressive Web Apps.

PWAs (Progressive Web Apps)

I decided to create the app as a Progressive Web Application (PWA). What is a PWA? It’s a new term coined by Google which basically means a web application which provides a native-like experience on mobile devices.

There are a few indicators of whether a web app is a PWA:

  • Looks like a native app on mobile devices
  • Loads fast and supports offline mode
  • Can be launched from the phone’s home screen
  • Runs full-screen
  • May support push notifications (so the phone will display notifications even if the browser is not running)

What are the advantages of a PWA over a native mobile app? Discoverability! You don’t need to put your app in the App Store or the Play Store. All your users need to do is to go to a specific URL. Besides, you can use your web skills and don’t need to learn platform-specific technologies such as Swift or the Android framework.

Modern web technologies at work

As you can see, there are quite a few requirements that the app should satisfy. Let’s take them one by one.

  • Looks like a native app on mobile devices – I know Angular best so I would like to use it to build the app. Ionic 2 is an excellent framework based on Angular 2 which provides a set of UI components that make your app look like a native app. The framework detects the device it’s running on and applies different styling depending on whether it’s the iOS or the Android operating system.

  • Loads fast and supports offline mode – this part is taken care of by Service Workers. Service Workers is a relatively new technology which allows you to run JavaScript in the background. What it means is that your web app can register a piece of JavaScript code that will keep running even if the user closes the browser! Service Workers can also intercept HTTP calls made by the app. Therefore, it’s possible to implement offline caching of all calls made by the app using them.
  • Can be launched from the phone’s home screen and Runs full-screen – another technology called The Web App Manifest is responsible exactly for this. It’s quite easy to achieve – all you need to do is write a JSON file which defines various properties of the app. Given a proper manifest, Chrome on Android will show a suggestion to the user to install the app on the home screen.

  • Push notifications – I wanted my app to send friend meeting reminders to the users so Push Notifications sounds great! Thanks to Service Workers and the Push API it’s possible for a web app to produce native-like notifications on Android phones. However, something has to send the notifications. I decided to use Firebase Cloud Messaging as a transport and Webtask for hosting the code that would actually invoke the notifications.


I wanted to develop my app fast and not spend time on setting up infrastructure so I decided to go for serverless architecture with Firebase Database instead of a dedicated backend.

Firebase Database is a no-SQL, real-time database that web applications can directly connect to. It is tightly integrated with Firebase authentication and has a powerful validation rule engine. Therefore, it’s possible to avoid having a separate application server.

The app will consist of the following components:

  • The frontend written in Ionic 2 utilizing Service Workers for offline caching and receiving push notifications while the app is not in the foreground. It will also have a Web Manifest file to enable adding to the home screen.
  • The data will be stored in a Firebase Database. Validation rules will enforce that a user can only modify their own data. Firebase will also provide authentication.
  • A scheduled Webtask (function-as-a-service) will run daily, read data from the Firebase Database and send out push notifications and email reminders. Firebase also offers a similar functionality (it’s called Functions) but at the moment of writing they don’t support scheduled execution.

If you are not that familiar with Firebase or Webtasks, take a look at my previous post where I talk more about it.

Check out Part 2: Ionic 2 and app manifest

Method overload resolution in C# 6.0: an interesting bug story

Recently at work I’ve been looking into migrating our projects from VS2013 to VS2017. As part of the process we decided to move from C# 5.0 to C# 7.0. It turned out that after the switch some of our projects won’t build anymore. I spent some time investigating the issue and found the outcome interesting so let me share my story with you.


Below is the code that caused issues. It is an interface declaration with two overloads of a single  Get  method.

The code itself was fine. However, if we try to call it like this:

strange things will happen. Under VS2013 the code will compile without issues. However, under VS2017 it will cause a compile error:


Hmm, this totally makes sense. How is the compiler supposed to know which overload I mean? The solution is pretty simple – either don’t use method overloading here or provide a third overload that takes no parameter list.

I started to wonder which language feature introduced in C# 6.0 or C# 7.0 is responsible for this change of behaviour. After spending some time on fruitless thinking, I decided to ask a question on StackOverflow. Lasse in his elaborate answer enlightened me that this is not strictly a change introduced by one of the new language features but rather a stricter behaviour introduced by the Roslyn compiler which is shipped with Visual Studio starting from version 2015. I have later found this stated explicitly in Roslyn documentation.

Another problem

I decided to solve the issue by adding a third method overload taking only the id  parameter. In its implementation I picked one of the existing overloads randomly and called it with an empty parameter list:

How surprised I was to find out that some of our unit tests started to fail. After another couple of hours, I found the reason. It turned out that one of the overloads of the Get  method behaved differently with an empty parameter list (the first one would load all includes for an entity when given an empty list while the second one would load none).


This was the moment when I realized how dangerous the before-Roslyn behaviour was. Given a call that was in fact ambiguous, the compiler would choose one of the overloads in a way that is by no means clear or intuitive. If by any luck it chose the same overload that you meant (as it happened in our case) you were relying on subtle, non-documented implementation detail of the compiler .

The whole story thought me to be more careful when dealing with method overloading. The algorithm used for overload resolution is actually pretty complex and implements lots of rules (as exemplified here or in John’s Skeet C# in Depth book). Always make sure that it’s absolutely clear (both to you and the readers of your code) which method overload you mean.



JS Poland 2017 Conference: get free ticket and discount codes

I proudly announce that my blog is partnering up with JS Poland 2017!

JS Poland is a promising conference where you will learn about the current state of ES6, Angular, React, Redux, TypeScript and many more.

The conference features 15 great speakers such as Luca Mezzalira (Google Developer Expert, running the London JavaScript Community), Nir Kaufman (whose talk at NgPoland got me into Redux) and Gil Fink (a Microsoft Most Valuable Professional). There will also be 3 days of workshops.

JS Poland will take place June 19 in Warsaw. If you aren’t from Poland, it’s an exciting opportunity to visit my beautiful country! The conference is planned to host 800 guests from all over the world!

As part of my partnership with JS Poland, I’m delighted to offer you discount codes and one free ticket.

To get the 10% discount, register here and use the following code: codewithstyle. The code is valid until 2017-04-15 23:59.

Want to get the free ticket worth over 100 EUR? Share this post on Twitter and Facebook. The person with the highest count of likes under their share by the end of May will get a free ticket!

JS Poland is organized by my friend, Dariusz Kalbarczyk, who has already successfully organized NgPoland 2016 conference which gathered more than 700 hundreds developers from all over the world.

See you at JS Poland!

Setting up coverage reports on TFS with OpenCover

Code coverage is a metric which indicates the percentage of volume of your source code covered by your tests. It is
certainly a good idea to have code coverage reports generated as part of Continuous Integration – it allows you to keep track of quality of your tests or even set requirements for your builds to have a certain coverage.

Code coverage in Visual Studio is only available in the Enterprise edition. Fortunately, thanks to OpenCover you can still generate coverage reports even if you don’t have access to the Enterprise license.

In this article I will show you how to configure a Build Definition on Team Foundation Server 2015/2017 to use OpenCover to produce code coverage reports.


We are going to put some files on TFS. We will need:

  • RunOpenCover.ps1 – PowerShell script that will run OpenCover – we are going to write it in a moment
  • vsts-task-lib – a PowerShell script library which provides some helpful util functions
  • OpenCover executable
  • OpenCoverToCoberturaConverter – a tool to convert the report to a format understandable by Visual Studio
  • (optional) ReportGenerator – a tool do generate HTML reports

The last three items are available as NuGet packages. I suggest organizing all these files into the following directory structure:

Once done, check it in to your TFS instance.

I’ve put the BuildTools directory on the top level of the repository. Next, I’ve added a mapping to my Build Definition in order to make that directory available during the build.

Create the PowerShell script

Let’s now write the PowerShell script. The script is going to perform a couple of steps:

  • We would like our script to use a file pattern to scan for test assemblies in the same way that the “native” Visual Studio Tests task does. For that, we can use Find-Files cmdlet available in vsts-task-lib.
  • Next, we run OpenCover and use the list of paths with test assemblies as parameters.
  • Next, we need to convert the results file produced by OpenCover to Cobertura – a file format which TFS can understand.
  • Finally, we can use the same results file to produce an HTML, human-readable report.

The script will take a couple of parameters as input:

Next, let’s run the Find-Files utility to search against the pattern defined in $testAssembly. This code is copied from the original Run Visual Studio Tests task source code.

We can finally run OpenCover. The command to do this is pretty complicated. OpenCover supports different test runners (VSTest being only one of them) so we need to specify the path to VSTest as one of the arguments. The path below ( %VS140COMNTOOLS%\..\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe ) is valid for Visual Studio 2015 installation.

Another important argument is -mergebyhash . It forces OpenCover to treat assemblies with the same hash as one. I’ve spent a few hours figuring out why my coverage score is so low. It turned out that OpenCover analyzed few copies of the same assembly.

Next, let’s convert the results generated by OpenCover to Cobertura format.

Finally, we will generate a HTML report based on the results from OpenCover.

And that’s it.

Configure the Build Definition

We will need to add three build steps to our Build Definition. If you have a Visual Studio Tests task in it, remove it – you will no longer need it.

  • PowerShell task – set the Script Path to point to RunOpenCover.ps1 and specify the Arguments:

  • Publish Test Results task – configure it as on the image below; as a by-product of generating coverage reports, we produce test results – we need to tell TFS where to find them

  • Publish Code Coverage Results task – configure it as on the image below; thanks to this task the results will be visible  on the build summary page

And that’s it! Run the build definition and enjoy your code coverage results. You can find the on the build summary page. The HTML report is available as one of the build artifacts.

Understand monads with LINQ

This post is another attempt on explaining the M word in an approachable way. This explanation will best suite C# developers who are familiar with LINQ and query expressions. However, if you are not familiar with C# but would like to learn how powerful and expressive some of its features are, please read on!

Recap of LINQ and query expressions

LINQ is a technology introduced in C# 3.0 and .NET 3.5. One of its major applications is processing collections in an elegant, declarative way.

Here’s an example of LINQ’s select expression:

Query expressions are one of the language features which constitute LINQ. Thanks to it LINQ expressions can look in a way which resembles SQL expressions:

Before LINQ you would need to write a horrible, imperative loop which literates over the numbers array and appends the results to a new array.

Single element collection: Maybe class

It’s pretty easy to understand what select expression does in the above example: it apples a given expression to each element of a collection and produces a collection containing the results.

Let’s now imagine that instead of arbitrary collection, we are working with a special kind of collection – one that can have either one element or no elements at all. In other words, it’s either empty, or full.

How should select expression act on such a collection? Exactly the same way that it works with regular collections. If our collection has one element than apply the given expression to it and return a new collection with the result. If the collection is empty, just return an empty collection.

Note that such a special collection is actually quite interesting – it represents an object that either has a value or is empty. Let’s create such an object and call it Maybe.

Let’s create two factory methods to allow more convenient creation of instances of Maybe.

Thanks to type inference in generic method calls and the static using feature we can now simply write:

Making Maybe LINQ-friendly

Since we’ve already discussed how select would work on Maybe, let’s implement it!

Adding support for query expressions to your custom types is surprisingly easy. You just need to define a method which confirms to a specific signature (it’s an interesting design decision by C# creators which allows more flexibility than requiring the type to implement a specific interface).

What’s going on here? Firstly, let’s take a look at the signature. Our method takes a function which transforms the value contained by Maybe to another type.  It returns an instance of Maybe containing an instance of the result type.

If it’s confusing, just replace Maybe with List or IEnumerable. It makes perfect sense to write a select expression which transforms a list of ints to a list of strings. It works the same way with our Maybe type.

Now, the implementation. There are two cases:

  • If the object contains a value than apply the mapper function and return a new Maybe instance with the result
  • If the object is empty, there is nothing to convert – return a new empty Maybe instance

Let’s give it a try:

Nice! We can now use select expressions with Maybe type.

Taking it one step further

Let’s now imagine that given an employee’s id, our goal is to return the name of theirs supervisor’s supervisor. A person can but does not have to have a supervisor. We are given a repository class with the following method:

And a Person class:

In order to find the person’s supervisor’s supervisor’s name we would need to write a series of if statements:

Can we improve this code with our new Maybe type? Of course we can! First of all, since Maybe represents a value which may or may not exist, it seems reasonable for GetPersonById to return Maybe<Person> instead of Person.

Next, let’s modify the Person class. Since a person can either have or not have a supervisor, it’s again a good fit for the Maybe type:

Given these modifications we can now rewrite GetSupervisorSupervisorName in a neater and more elegant way:

Why is this better than the previous version? First of all, we explicitly represent the fact that given a person, the method might or might not return a valid result. Previously, the method always returned a string. There was no way to indicate that it can sometimes return null (apart from a comment). A user of such a method could forget to perform null check and in consequence be surprised by a runtime error.

What’s more, we avoid the nesting of if statements. In this example we only go two levels deep. What if there were 5 levels? Code without these nested if statements is much cleaner and more readable. It expresses the actual logic, not on the boilerplate of null-checking.

Making it work

If you’re copying these snippets to Visual Studio, you might have noticed that the last one won’t compile.

By implementing Select we told the compiler how to apply functions to values inside Maybe instances. However, here we have a slightly more complex situation. We take a value which sits inside a Maybe instance and apply a function to it. As a result we get another Maybe instance, so now we have a Maybe inside a Maybe. The compiler doesn’t know how to handle this situation and we need to tell it by implementing SelectMany.

The first parameter to SelectMany is a function which takes a value (which sits inside Maybe) and returns a new Maybe. In our example, that would be a function which takes a Person and returns its ReportsTo property.

The second parameter is a function which takes the original value, the value sitting inside Maybe returned by the first parameter and transforms both into a result. In our case that would be a function which takes a Person and returns its Name.

Inside the implementation we have the nested if statements that we had to write when we didn’t use the Maybe type. And this is the crucial idea about monads – they help you hide ugly boilerplate code and let the developer focus on the actual logic.

Again, let me draw a diagram for those of you who prefer visual aids:

Ok, so what’s exactly a Monad?

Monad is any generic type which implements SelectMany (strictly speaking, this is far from a formal definition, but I think it’s sufficient in this context and captures the core idea).

SelectMany is a slightly more general version of an operation which in the functional programming world is referred to as bind.

Monadic types are like wrappers around some values. Binding monads is all about composing them. By wrapping and unwrapping of the values inside monads, we can perform additional operations (such as handling empty results in our case) and hide them away from the user.

Maybe is a classic example of a monad. Another great candidate for monad is C#’s Task<T> type. You can think of it as a type that wraps some value (the one that will be returned when the task completes). By combining tasks you describe that one task should be executed after the other finishes.


I hope this article helped you understand what monads are about. If you find this interesting, check out the F# programming language where monads are much more common and feel more natural. Check out this excellent resource about F#:

It’s also worth mentioning that there exists an interesting C# library which exploits the concepts I described in this article: Check it out if you’re interested.

Firebase authentication in Angular2 application with Angularfire2

Implementing authentication in web apps is a tedious and repetitive task. What’s more, it’s very easy to do it wrong and expose security holes in our app. Fortunately, Firebase Authentication comes to rescue offering authentication as a service. It means that you no longer need to implement storage and verification of credentials, email verification, password recovery, etc. In this post I’ll explain how to add email/password authentication to an Angular2 application.

Site note: Firebase Authentication can be very useful when building a serverless application.

For reference, here is a working example illustrating this article:



Firebase offers two ways of implementing authentication:

  • FirebaseUI Auth – a library of ready-to-use GUI components (such as login/registration forms, password recovery, etc.)
  • Firebase Authentication SDK – a more flexible approach in which we need to implement above components ourselves; the role of Firebase is to store and verify user credentials; let’s focus on this one

We’ll implement three components:

  • Register component will show a registration form and will ask Firebase to create an entry for a user upon submission
  • Login component will show a login form and will ask Firebase to verify provided credentials upon submission
  • Home component will show the currently logged user (provided there is one)

We’ll use the excellent Angularfire2 library. It provides an Angular-friendly abstraction layer over Firebase. Additionally, it exposes authentication state as an observable, making it very easy for other components to subscribe to events such as login and logout.


To begin with, let’s install Angularfire2 and Firebase modules:

Next, we need to enable email/password authentication method in the Firebase console.

Firebase: enabling email/password authentication

Finally, let’s load Angularfire2 in our app.module.ts:

Login component

Firstly, let’s inject AngularFire into the component:

As you can see,  is an observable. It fires whenever an event related to authentication occurs. In our case, it’s either logging in or logging out. FirebaseAuthState  stores information about currently logged user.

Next, let’s add two methods for logging in and logging out:

As you can see, we simply propagate calls to the Angularfire2 API. When logging in, we need to provide email and password (encapsulated in model).

Finally, we need some HTML to display the form:

The form is only visible when the user is not logged in ( authState  will be undefined). Otherwise, we show the user name and the logout button.

Register component

We’ve allowed our users to logged in but so far there are no registered users! Let’s fix that and create a registration component.

Firstly, we need to inject the AngularFire service just like we did in the login controller.

Next, let’s create a method to be called when the user provides his registration details:

Finally, here goes the HTML form:


In this tutorial I showed you how to take advantage of Firebase Authentication and use it in an Angular 2 application. This example doesn’t exploit the full potential of Firebase Authentication – it can also do email verification (with actual email sending and customizable email templates), password recovery and logging in with social accounts (Facebook, Twitter, etc.). I will touch on these topics in the following articles.

Let me know if you have any feedback regarding this post – feel free to post a comment!

C# in Depth: book notes

pobraneI just finished reading this must-read position for C# developers. I believe that it’s very easy to learn a programming
language to an extent that is sufficient for creating software. Because of that, one can easily lose motivation to dig deeper and gain better understanding of the language. C# in Depth is a proof of why one shouldn’t stop at this point. There is a lot to learn by looking at the details of a language, how it evolved and how some of it’s features are implemented.

I think the book is fantastic. I loved the author’s writing style which is very precise (very little hand waving) but not boring at the same time. It feels that he’s giving you just the right amount of detail.

Here are a couple of interesting things I learned about when reading the book. The list is by no means complete but it gives a taste of what’s in the book.

  • I learned that it’s possible to support LINQ query expressions for your own types very easily. The mechanism is convention-based – there is no specific interface to implement. Your type must have methods that match some specific signatures. This didn’t sound well to me in the first place, but if you think about it, it allows for greater flexibility. For example, with such approach you can add query expression support to existing types (which you don’t have control over) with extension methods.
  • I finally understood why the keywords used to indicate variance in generic types are called out and in. Generic type parameter can be covariant if it’s used for values that are coming out of an API (something’s coming out so you can only increase the restriction on it when deriving). Conversely, when value is an input of an API it’s type can be contravariant (something’s coming in, so you can relax the restrictions when deriving). This explanation plays well with my intuition of how collections can be covariant as long as they are immutable (i.e. there are no inputs to the API)
  • I understood how dynamic typing is implemented in C# and how to create your own types which can react dynamically (with IDynamicMetaObjectProvider, DynamicObject and ExpandObject). The chapter explaining what code is generated when making dynamic calls is the most complex (and most interesting) piece of the book.
  • I understood what code is generated when using the async/await feature and what are the consequences. For example, the code inside an async method does not execute until you await it. Therefore, argument validation wouldn’t give immediate feedback to the caller unless the method is awaited at the point of calling. The same applies to iterators.
  • I learned that something as simple as a foreach loop is actually doing a lot of work under the hood – it creates a try/catch/finally block and disposes of the enumerator if it happens to implement Disposable.
  • I embraced the complexity of type inference of lambda expression parameters and return types.

To sum up, I totally recommend reading this book. It’s not a small time investment, but I think it’s totally worth it.

Building serverless web application with Angular 2, Webtask and Firebase

Recently I’ve been playing a lot with my pet project Tradux. It is a simple trading platform simulator which I built as an exercise in Redux, event sourcing and serverless architectures. I’ve decided to share some of the knowledge I learned in the form of this tutorial.

We’re going to build (guess what?) a TODO app. The client (in Angular 2) will be calling a Webtask whenever an event occurs (task created or task marked as done). The Webtask will update the data in the Firebase Database which will be then synchronized to the client.

Webtask is function-as-a-service offering which allows you to run pieces of code on demand, without having to worry about infrastructure, servers, etc. – i.e. serverless.


The full source code is available on Github.

UPDATE: recently I gave a talk on this topic during #11 AngularJS Warsaw meetup. During the talk I built a silghtly different demo application which additionally performs spell checking in the webtask. Check out the Github repo for the source code.

Project skeleton

Let’s start with a very simple client in Angular 2. We will use Angular CLI to scaffold most of the code.

It takes a while for this command to run and it will install much more stuff than we need, but it’s still the quickest and most convenient way to go.

Let’s create a single component.

Now, let’s create the following directory structure. We’d like to share some code between the client and the webtask so we will put it in common directory.

Let’s start with defining the following interfaces inside model.ts. The first one is a command that will be sent from the client to the webtask. The second one is the entity representing an item on the list that will be stored in the database.

Finally, remember to add the Tasks component to app.component.html :

Adding Firebase to the Client

Before we proceed, you need to create a Firebase account. Firebase is a cloud platform which provides useful services for developing and deploying web and mobile applications. We will focus on one particular aspect of Firebase – the Realtime Database. The Realtime Database is a No-SQL storage mechanism which supports automatic synchronization of clients. In other words, when one of the clients modifies a record in the database, all other clients will see the changes (almost in real-time).

Once you created the account, let’s modify the database access rules. By default, the database only allows authenticated users. We will change it to allow anonymous reads. You can find the Rules tab once you click on the Database menu item.

Firebase provides a generous limit in the free Spark subscription. Create an account and define a new application. Once you are done, put the following definition in config.ts :

If you cannot find your settings, here is a helper for you. If you are really lazy, you can use the following settings, although I cannot guarantee any availability.


Let’s now add Firebase to our client. There is an excellent library called AngularFire2 which we are going to use. Run the following commands:

Modify the imports section of AppModule  inside app.module.ts  so that it looks like this (you can import AngularFireModule  from angularfire2  module):

Now you can inject AngularFire object to Tasks component ( tasks.compontent.ts ):

You will also need some HTML to display tasks. I will include the form for adding tasks as well ( tasks.component.html ):

Our client is ready to display tasks, however there are no tasks in the database yet. Note how we can bind directly to  FirebaseListObservable – Firebase will take care of all the updates for us.

Creating the Webtask

Now we need to create the Webtask responsible for adding tasks to the list. Before we continue, please create an account on Again, you can use it for free for the purposes of this tutorial. The website will ask you to run the following commands:

Creating Webtasks is amazingly easy. You just need to define a function which takes a HTTP context and a callback to execute when the job is done. Paste the following code inside webtasks/add-task.ts :

The above snippet parses the request body (note how it uses the same AddTaskCommand  interface that the client). Later, it creates a Task  object and calls Firebase via the REST API to add the object to the collection. You could use the Firebase Javascript client instead of calling the REST API directly, however I couldn’t get it working in the Webtask environment.

Obviously in a production app you would perform validation here.

Note that you need to define the firebaseSecret  constant. You can find the private API key here:


Firebase complains that this is a legacy method but it’s simply the quickest way to do that.

Why do we need to pass the secret now? That’s because we defined a database access rule which says that anonymous writes are not permitted. Using the secret key allows us to bypass the rule. Obviously, in a production app you would use some proper authentication.

We are ready to deploy the Webtask. A Webtask has to be a single JavaScript file. Ours is TypeScript and it depends on many other modules. Fortunately, provides a bundler which can do the hard work for us. Install it with the following command:

Now we can compile the TypeScript code to JavaScript, then run the bundler to create a single file and then deploy it using the Webtask CLI:

Voila, the Webtask is now in the wild. The CLI will tell you its URL. Copy it and paste inside config.ts:

Calling the Webtask from the Client

There is just one missing part – we need to call the Webtask from the client. Go to the Tasks component and add the below method:

This function is already linked to in HTML. Now, run the following command in console and enjoy the result!


In this short tutorial I showed how to quickly build a serverless web application using Webtasks. Honestly, you achieve the same result without the Webtasks and by talking directly to Firebase from the Client. However, having this additional layer allows you to perform complex validation or calculations. See Tradux for a nice example of a complex Webtask.

You can very easily use Firebase to deploy your app.

ngPoland – Angular Conference 2016

Today I attendend ngPoland – the first international conference devoted to Angular in Central Europe. I’ve had some really good time there and decided to share some of the amazing things I learned about.

First of all, I was surprised to learn how good some of the speakers were at catching people attention and making sure that everyone stays awake. The conference was pretty intense (I counted 15 talks) so it was quite a challange. It was inspiring to see how got can one become at public speaking and working with large audiences.

Photo by Phil Nash from Twilio
Photo by Phil Nash from Twilio

The key takeaway for me is to deffinietly look into Redux (the presentation by Nir Kaufman). The framework introduces a great idea from functional programming to the frontend world. Redux allows you to express your application’s logic as a set of reducer functions which are applied on the global, immutable state object in order to produce the “next version” of state. Thanks to that, it’s much easier to control and predict state transitions. Similiarity to the State Monad seem obvious.

Another very interesting point was the presentation by Acaisoft’s founder who showed a live demo of an on-line quiz app with real-time statistics. The application was implemented in Angular 2 with serverless architecture (AWS Internet of Things on the backend side), event-sourcing and WebSockets. It was exciting to observe a live chart presenting aggregated answers of 250 conference participants who connected with their mobiles.

Definietly the most spectacular talk was the one about using Angular to control hardware connected to a Raspberry Pi device (by Uri Shaked)! The guy built a physical Simon game that was controlled by an Angular app. Thanks to angular-iot he was able to bind LED lights to his model class. The idea sounds crazy but it’s a really convincing demonstration that Angular can be useful outside of the browser. If you are interested, you can read more here.

Last but not the last, I have to mention the workshop about TypeScript 2 (again by Uri) which I attended the day before. Although I knew TypeScript before, it was interesting to learn about the new features such as null strictness and async/await. Coming from a C# background, it’s very easy to spot the Microsoft touch in TypeScript. I believe the language is evolving into the right direction and I’m happy to see more and more ideas from functional programming being incorporated in other areas.

Wrapping up, I think the conference was very convincing at demonstrating how much stuff is happening around frontend development. I like the general direction towords each its evolving and I hope that I will have many opportunities to work with all the new stuff.