My language learning framework

The most important lesson that I have learned in my career of almost 15 years in software development is that programming languages are just tools to solve real life or business problems. About 5 years ago I was doing full time .NET, then I jumped to Java for about two years, then I switched to Ruby and Rails, and just recently I started using Kotlin to create two microservices (don’t ask me why, the business needed it ;)).

Because of this, there is no point whatsoever to be bound to a language/platform religiously. The languages are tools but it’s the core knowledge of computer science and software development practices that prevail.

These changes have been inspired by different rationales, sometimes influenced by the employer and sometimes by the economic conditions of the runtime environment. E.g. hosting a Java web application during 2006 was way more expensive than a PHP application, therefore, I used PHP as a primary language for my web facing pet projects. So during my career so far, I have used Java, .NET, PHP and Ruby as my core languages and also have implemented small solutions using Kotlin, Javascript, and Python.

To adapt to this changing environment of ours I have noticed I had created a framework, which I call my language learning framework. The framework itself is not about the language per se, but about the whole ecosystem around that language. It came as a result of identifying unchanging things around any language ecosystem. E.g. no matter the type of language, there is a way to deal with strings, numbers or arrays. Or the language has some sort of collections.

With almost every language that I have used, I have had the need to also learn a framework to develop web applications, a framework to do testing, and other common things around the application. So out of this experience, here I share with you my language learning framework. It lists the things I try to learn or pay attention to when I start learning a new language.

I. Language
1. Runtime & ecosystem (general knowledge)
2. Syntax
3. Data types (if there are types)
4. Main constructs
4.1. packages/modules, classes and methods/functions
4.2. loops & conditioning
4.3. arrays
5. Core libraries
5.1. String manipulations
5.2. collections (lists, arrays, maps, sets)
5.3. math (rounding, sqrt, pow, PI)
5.4. important packages/gems/etc. and any language/platform specific library
II. Frameworks
1. Application development (evaluate popular ones and pick one)
2. Testing (unit & integration)
3. Main design patterns and in that language
III. Toolset & Other
1. IDE platform specifics
2. CI/CD
3. Deployment (does the docker & Kubernetes work or is there anything platform specific)
4. Community
5. important learning resources

Some of these items on the list are dead clear so you just follow it, but some of them are hard, like choosing which framework to use. How do you choose which framework to pick. Well, in those cases, I use different inputs to make my decision but most often it is an educated guess. What I consider is, I ask my colleagues/friends if they have experience with any of the ones I am considering and get their opinions. I also evaluate possible blog posts about them and also try to measure the popularity by checking the number of contributors, how often does a major version gets released, how many job openings I find requiring that framework, and based on all these inputs I narrow my list to two options. Then I try both of them with a certain simple scenario and I try to evaluate how easily I could implement that scenario and get a feeling of both and then decide. Out of all the factors I consider, how much I like it and how many job vacancies are there requiring that framework are two criteria that weigh most with me. The pleasure to work with is very important for me, but also having an opportunity to use it (have an employer/business which actually uses the framework) is also important in my opinion.

One important thing is, when I try to jump on a new language, I try to do all these steps in a relatively short period, potentially with max 2-3 months, and then try to repeat it at least 2 times with 2-3 sample projects. In this way I make it possible for my brain to remember it, otherwise, if it takes too long to go through the list, I forget things in between and the end result is not satisfactory.

This is not a definitive list and doesn’t include everything we need to learn to be productive in one language/platform, but it certainly serves as a good starting point for me when I want to jump into a new language.

Do you have a different approach? Share with us!

ElasticSearch – Getting started

Context

A few weeks ago, our team decided to use ElasticSearch for the search functionality of the project we are implementing. I had no previous experience implementing any search engines, so I got excited to get my hands onto doing something really new. What I am going to describe you here is the process I followed do a spike on ElasticSearch and what I learned out of it.

Why should you care about it

Elasticsearch is useful on several scenarios. It is very good for searching product catalogs, creating recommendation engines, logs aggregation and searching for faster debugging, data mining and identification of patterns, and in many more scenarios. There is a chance, the product you are working on might need such a thing.

Some basic concepts first

As an entry point to this task, first I had to learn the basic concepts about ElasticSearch. In essence, ElasticSearch is a document database which uses Lucene as a search engine. It is fast and horizontally scalable, though, it is a very memory hungry system. It stores all documents inside so called Indices. An index can be imaged something like a database in the relational databases world. Inside indices, you can have types, which you might think of as database tables (not exactly like that, but a good analogy).

Data of an index is saved in one or more shards (the default is 5 but this is configurable). Every shard can have one or more replicas. A replica is just a copy of the shard and it serves for optimizing performance and failover. If you don’t have millions of data, it might be good to have fewer shards for a better performance.

Setup ElasticSearch on your computer

To start experimenting, I started with setting up an instance on my computer. Setting up ElasticSearch is pretty easy (at least for the beginning). There are numerous ways you could follow and they are very well documented in their installation page. The approach I took is to have it as a docker container on my local machine so I can start experimenting right away and for production to have a chef script to do the installation for us.

If you already have docker installed, having ElasticSearch up and running on your machine is a matter of minutes by executing pull command to get the image

and running the container

This command runs the container and exposes port ElasticSearch on port 9200. If you try in your browser executing http://localhost:9200 (username: elastic, password: changeme) you will receive a response like

This shows that ElasticSearch is running inside the docker container and you can start playing with it. You can find all these installation details in Elastic’s site.

Loading data to an index

Now that ElasticSearch is running, the next step is to populate some data so we can test the search functionality. At simplest, we can communicate with ElasticSearch using curl cli tool or by using a http tool like Postman, or Sense – chrome extension. Pushing data can be done manually one record at a time, or in bulk. As a first step, we could create an index by executing

This will create index named documents with two shards and one replica per shard. It will also create a type named person.

To insert a person document, we can execute a post request with person’s data

The url segments map to {index}/{type}/{id}. If we didn’t specify id, then ElasticSearch would create an id for us. The response from ElasticSearch for this request would look like

From the response, I can read that I posted to index documents and type person and the request was successful.

For the sake of simplicity, we just posted the data to ElasticSearch without doing any data mapping. If we don’t do it, Elastic will do a dynamic mapping. If you want to enforce the type of data uploaded, you might consider to create a mapping when creating the index. Please take a look at mapping documentation for more details.

Loading more data

Posting one or two documents is easy, however, that would be of little help to really test searching functionality. To make the test more realistically, what I did was to export data from our PostgreSQL database to a json file and then posting the file to ElasticSearch using a curl command

If the export file is too large, you might want to split it to smaller ports (I got the right size by ‘trial and error’).

Searching

ElasticSearch offers plethora of query combinations. The query documentation is large and describes all the ways to construct complex queries with filters and aggregations. To the simplest form, for the sake of demonstration, if I want to search for the person whose phone number is ‘1234567’, the query would look like

or in a more complex form

Either one would bring the same result. For more complex queries, please consult the documentation.

Conclusion

With such a short article, I could only touch the top of the iceberg about ElasticSearch. This article summarises the steps you can take to bring up an instance of ElasticSearch, load some data on it and start experimenting with it. Happy hacking.

My weekend with Python programming language

This weekend was a long one for me. Unfortunately, I catched cold and had to stay the whole weekend home resting and waiting to feel better. While sitting and wondering what can I do (I wasn’t in a mood to work on anything), I decided to take a look at Python programming language. It’s been a while that I have developed a kind of interest to try this language but never had a chance to take some time out of a busy schedule. Many people were telling me good words about it, how elegant it is and how easy it is to write code using it, but I needed to try it to have my own opinion. Although I could only spend 2-3 hours during the whole weekend trying it, I would like to express my first impression of this language.

What I liked

  • There are plenty of learning resources. Although I could have started with a video tutorial, I chose to start with this tutorial by google which seemed to me quite concise and straight to the point. It was showing all important points without getting too much into details. Just what I needed.
  • Coming from a programming background, I found it extremely easy to start coding immediately in python. The language syntax may seem odd at the beginning but the learning curve is smooth. It’s easy to grasp the python way of coding, although, it may take some time to forget putting the semicolon at the end of the line though 🙂
  • The language seems elegant and rich in features. It has most of the features found in other languages such as Java, C#, and PHP.
  • The fact that you can write code in the command line was interesting to me 🙂
  • Working with lists and tuple structures was extremely easy and handy.

What I did not like

  • The fact that there are no curly braces and semicolons at the end of the line might cause a little headache for those of us who come with a background from the C line of languages (C++, Java, C#, PHP, JavaScript, etc.). Omitting semicolons looked easier to me than maintaining the lining of code to keep track which code belongs to which block. After you get used to it, the whole code starts to look more elegant and easy to read.
  • You can define variable names same as built-ins overriding system variables. I think this could be a big point of confusion for newcomers.

Summary

I admit, evaluating a programming language by spending three hours learning it is extremely hard and might lead to biased judgments. However, I write this review solely because of my positive impression with this language. I like learning new programming languages as almost each of them have good parts and practices from which we all might learn and benefit. Certainly, python has its share in this and in my opinion is worthy to give a try. For me, my next step should be to find an opportunity to use it in a real life web application and see the experience 🙂

What is your experience with python? Share it with us.

 

Entity Framework Migrations and Data Seeding

This article is a part of a multi-post article on Entity Framework Code First for web applications:

  1. Entity Framework Code First Entities and entity relationships
  2. What do you need to know about Entity Framework Data Context
  3. Entity Framework Migrations and Data seeding

This article is the second part of the posts. The first part talks about defining entities and relationships. The second part talks about the data context. You may find links to previous posts above. Let’s continue by talking about how to propagate changes to the database and seed the database with data for referential tables.

Entity Framework Migrations is a feature of Entity Framework to manage the reflection of changes in the code to the database structure. It compares the structure of entity classes and database tables to identify changes and write SQL scripts for implementing changes in the database.

To start using Migrations feature, we must first activate the tracking of changes in entity classes. Enabling Migrations can be done with a simple command which can be given through Package Manager Console (you may find it at: View->Other windows->Package Manager Console). In the console, you write the command Enable-Migrations (please note, this command may be different in versions of Entity Framework, my examples are using Entity Framework 6).

 

Before executing the command, please note to have the right project selected as the default project (in case you have an n tier architecture with data access layer on it’s own project).

After the command is executed, you will see a new folder appearing in the project structure, which holds the migration related files. As you add migration points, you will see files to be added to this folder with the name of migration point and its timestamp.

migrations-folder

Inside the Migrations folder, you will also find a file named Configuration.cs. This file contains the initial configuration for the database, which we may use to populate some database tables with initial values and many other configuration tasks. A sample initialization can be done through the Seed method of the Configuration class:

In the example above, you may see two sample classes, PaymentType and Category, which refer to referential tables in database, being populated with initial values, and the context saving changes at the end. This happens every time we issue update to the database. To avoid duplicate entries, please use AddOrUpdate method to add entities, instead of just Add.

But, what do I mean by a migration point. As you develop, often you make several structure changes in the classes, you add new classes, you add properties to existing classes, refactor existing ones, etc. After you do a fix or complete e feature, you create a migration point which stores changes from previous migration point until now. We can create a migration point by executing this command:

PM>add-migration 'name of migration'

Each successful migration point will create a file in the Migrations folder named as timestamp_name_of_migration.cs. These points will help you if you want to go back to a previous state of the database structure, in case you want to roll back the developments.

One point to be clear, when you create a migration point, the changes are not yet pushed to the database. It is only when we execute command Update-Database that the Entity Framework tries to push changes to the database based on the connection string found in the config file. This MSDN article shows a more complete list of migration commands.

We might some times want to update the database ourselves and not let the Entity Framework do it on its own. We may ask Entity Framework to show us the script of changes. We can do this using the command Update-Database -Script. After the execution, we will have an SQL script with all changes pending to be executed in the database.

Summary

Entity Framework Migrations is an important feature which will allow you to adopt the database structure in agility as you develop the code. Changes you make are kept in history and if you would like, you may go back in history, track changes, or even revert back to some point in history. All this with an easy command line interface which is easily executed in the Package Manager Console. Find more info in the official documentation of Entity Framework.

What you need to know about Entity Framework Data Context

This article is a part of a multi-post article on Entity Framework Code First for web applications:

  1. Entity Framework Code First Entities and entity relationships
  2. What do you need to know about Entity Framework Data Context
  3. Entity Framework Migrations and Data seeding

This article is the second part of the posts. The first part talks about defining entities and relationships. You may find the first article in this link. Let’s continue by talking about the data context in the Data Access Layer.

Entity Framework enables us to abstract the data layer and communicate with the database for the Create, Read, Update, and Delete (CRUD) operations. We also defined the relationship between entity classes and database tables. Just as every table is enclosed inside a database, in Entity Framework, entities are enclosed inside a data context to abstract a database. The primary class that creates this context is the DbContext class of System.Data.Entity namespace. To abstract a database, we usually create a class representing our context which extends DbContext class. Let us suppose that we have a database called HumanResources and we want to connect to that database using Entity Framework. Our Entity Framework Data Context would look like this at beginning:

The DbContext class that we extend will allow us to define our database tables as sets of entities (DbSet<T>), and then, we can query the database and do all the CRUD operations using those sets. Entity Framework will convert all those actions we perform to SQL queries, execute them towards the database, and return us the results back. DbContext even offers these operations in synchronous and asynchronous modes.

From the previous post, we had defined two entities, Person and Country. Let’s define them inside our context.

We pluralize the names of the sets as they represent the table of persons/countries, so multiple records are represented.

The DbContext’s lifetime starts with the instantiation of the object and it will end when the object is disposed or garbage collected. If we want to manage the lifetime of the context, we can put it inside a using construct to dispose it when we are done. During the lifetime, it will also manage opening and closing of connections to the database. E.g.

In the example below, we have created an instance of the HumanResourcesContext. Inside the curly braces, we have queried the persons table to find the person with the id equal to 1 (db.Persons.find(1)). DbContext allows us to query the database using the name of the DbSet properties we have define (which point to database tables), but the actual query is not executed when we say like db.Persons. The queries are executed when we ask the context for concrete data, like in our example with finding the person with id equal to 1. Other forms that we ask the context for the data could be execution of ToList(), ToArray(), Single() methods.

When using with ASP.NET, we should create a context per request. If we do it, we should use using during the process of request, or if we do it using an Inversion of Control (IoC) container, we should define the initialization of our context class as per request.

There is one more important thing to note here. We queried the database without even specifying the connection string for the Entity Framework. How does it know where to connect? By default, it uses the default connection string in asp.net (found in web.config in versions prior ASP.NET 5) and make the connection using it. If you want to specify a specific connection string, e.g. if we have a connection string named myConnectionString defined in web.config, you may pass it to the constructor of DbContext like this:

or hardcode it if you want (I would not recommend it)

Summary

DbContext class allows us to create the data context of our database abstraction. It allows us to perform CRUD operations towards our database using code first approach without writing SQL queries.

 

Entity Framework Code First Entities and entity relationships

This article is a part of a multi-post article on Entity Framework Code First for web applications:

  1. Entity Framework Code First Entities and entity relationships
  2. What do you need to know about Entity Framework Data Context
  3. Entity Framework Migrations and Data seeding

It is not very often that I see web development tutorials focusing on db level with entities and their relationships. But, whatever web application you start working on, chances are you will need a database to store and read some information. In this post, I will try to give a short description of entities and how relations are created between them in the context of Entity Framework Code First, as the data access layer of a web application. Let’s see first what is Entity framework.

About Entity Framework Code First

Entity framework is Microsoft’s Object Relational Mapping (ORM) solution. It supports the communication between the code and the database, facilitating the development of the database structure (by generating DML code automatically), data access, and mapping the data between data sets and objects of our code. Entity framework enables us to develop the data access layer in three ways: database first, model first, and code first. The development of these methods have come in a progressive way, code first being the latest approach, and personally I would say, it is the most flexible one. It allows us to develop our database starting from the code. This gives us the possibility to think from the code’s perspective and enable us to structure our code as it fits best the application logic, not the database organization.

What is an Entity class?

Basically, entities are simple classes which represent entities of the application. Usually, every entity corresponds to a database table and in a way becomes the code representation of that table. An example might be, if we have the table persons in the database, we might have the class Person which represents a single record of that table. As the class represents a single person, it’s name is singular, and table’s name is usually in plural. Entity Framework by default take care about pluralization of table names by convention.

Creating an Entity class

Creating an Entity class is as simple as defining a class. Usually, classes have some properties inside them. Let’s model our entity class Person and see how it might look.

If we examine this class, we see that it has four properties, one integer number named Id, two string properties Name and Surname, and one DateTime property BirthDate, all representing personal details of a Person. Based on this definition of the Person class, Entity Framework creates persons table by examining these properties. We’ll go little deeper in the db creation in the next post.

Decorating Entities with validation attributes

Leaving Entities plain as in the example above will keep the code clean and readable. This kind of Entity is called a Plain Old CLR Entity or POCO for short. In some scenarios, it might be a good strategy to stick to POCO style and keep the Entities clean and put the validation code in some other partial classes or other parts of the code.

Entity framework gives us the possibility to decorate the classes and class properties with attributes, which are later used during the process of creating the database tables, and the client side validation in ASP.NET MVC. These decorations serve in two perspective: 1) they enable the Entity Framework to understand the property and gather metadata based on which will create the table columns; 2) they enable the client side validation of the input data for those properties to be done automatically.

Let us decorate the Person class with some attributes.

I have decorated Name and Surname properties. Now, both have the validation attribute [required]. Validation attributes are written inside brackets. The required attribute marks a property as required and this will translate as not null in the database. From this, we can see that we have made Name and Surname properties. The surname attribute is also decorated with a second validation attribute, which is MaxLength. MaxLength tells the maximum length (when the data type is string, this is the length of characters, when the data type is number, it is the length of numbers) of a column in a database. For more details about validation attributes please refer to this link on MSDN.

Defining relationships between Entities

The benefit of Code First approach of Entity Framework is that it allows you to define the whole database structure from within the code, this includes the relations between the entities as well. Let’s suppose that we have a lookup table countries which holds the list of countries. Now, we need to assign every Person entity a country. How can we do that?

We start by defining our Country entity first:

Now that we have our country entity, we can add the relation to the Person entity by modifying the class

By adding a reference to a Country entity we are telling the Entity Framework that we want to a relation between Person and Country entities. We have also quantified it as one to many, as one Person can have one country, but one country can be assigned to multiple persons, this definition will result to one to many relationship between Person and Country entities. The relationship diagram will look like this:

one-to-many

You may refer to this link for further details on defining relationships.

Conclusion

Entity Framework Code First approach will give you a good possibility to focus on code and and define everything from there. It gives you the flexibility to in a declarative form to define all the properties of database structure and change it accordingly as the code evolves. In the next posts, we will go through the defining the Data Context which is the backbone of the data access layer and after that we will focus on how to create the database from the code, feed it with data, and manage the changes in the database structure.

Implementing REST services in AngularJS using Restangular

Current web development trends are in favour of AngularJS. The framework is having its momentum and is one of the most popular choices for client side development frameworks. Personally, I like it a lot, it makes my job easier to jump start the web development projects quickly. It is also useful for hybrid mobile applications.

Another thing that has quite a momentum for some time now is implementation and consumption of REST services. REST as an architecture, although it makes things easier after implementation, is an architectural style which is very easy to get it wrong, despite most of the time what we need is simple GET/POST/PUT/DELETE requests.

Restangular is an AngularJS service which makes GET/POST/PUT/DELETE requests simpler and easier. The configuration is easier and can be done in several ways with different initiation settings. Let me try to put an easier demonstration on how to use Restangular on your site and how easy it is to make your AngularJS app consume RESTful service.

Configuration

The first thing to do is to reference restangular in your index.html (refer to official page for installation).

To configure restangular with your AngularJS app, in your app module definition file you configure restangular settings.

Now that we have restangular configured, we can make requests for resource like this:

Alternatively, we can also create services for our resources. For e.g. if I have a resource named students, I would create the service through these lines of code:

then I would add this service as a dependency to the controller that I want to use it in. With this simple service definition, I can now easily initiate GET/POST/PUT/DELETE requests through restangular.

Let us take some examples. We can read all students by requesting

or if I want to read the student with id 1234 I would request

Saving a student is also as easy as getting it

Restangular has the main request types GET/POST/PUT/DELETE almost ready made for us, but also it allows many things to be configured per our needs. We can make custom requests to custom methods, specify parameter names, and many other not so standard things. Please refer to restangular’s github page for detailed specifications.

As it makes RESTful api consumption so simple, currently it is one of my favorite parts of my AngularJS apps.

Implementing loading animation in AngularJS and jQuery

With the advancement of web development technologies, web application are closing the user experience gap with desktop applications very quickly. It is a very common practice to let the user know when the application is busy with a certain task, and one of the most common ways to do this is by showing a loading indicator or a spinning gif. This will let the user know that the application is working and he or she will not try to refresh or press other buttons until the task is finished.

To implement this, before the task is initiated at server, we must show our spinner or any loading animation we want to show, and then when the task is finished (successfully or unsuccessfully) hide the animation. I will show you how you can do it using jQuery and using AngularJS.

Implementing loading animation in jQuery

Let us start with the jQuery. I want to show a spinner whenever I post something to the server from the form, until I receive a response. Let us suppose we have a form like this:

and I have a div with a spinner gif img inside it somewhere in the html

At the beginning, I need to make this hidden, so you can put a css style display:none  or hide it using jquery or whatever way you like most.

There are several forms to determine how to show the spinner and hide it. One way is to bind to subscriptionForm ajaxSend and ajaxComplete events to show and hide the spinner respectively.

This will make the spinner show when a ajax request starts from that form and disappear when the request completes.

If it is the case that you need to make the spinner show for every ajax request made within the page, then you may need to bind the events to the DOM.

You can also make the spinner show as a modal dialog by applying a style like this and adding class ajax-loader to the spinner img element:

This will make the spinner show in a modal dialog and prevent the user from initiating any other requests before this one finishes.

Implementing loading animation in AngualarJS apps

The strategy for implementing the loading animation in AngularJS is little different and requires a bit of a setup. To catch the start and end of requests, in AngularJS we must create http interceptors for request and response. Interceptors will intercept requests before they are handed to the server so we can show our spinner and response before it is handed to the client so we can hide the spinner.

To get the interceptors, we need to register them through an anonymous factory  and inside request and response functions, we need to show and hide the div of spinner respectively.

Interceptors are a useful part of AngularJS which can be used to make several kinds of validations before a request is made or after a response is received (authentication validations, etc.), and one of the tasks we can put here is also to show and hide the spinner when a request has started and completed (please be aware that for the simplicity of the code, I have omitted functions which check for errors on requests).

To make the example more clear, I have create a sample interceptor demo in a Plunker, you may see it here http://plnkr.co/edit/hAg1T8sdsLq5c61iW97f?p=preview

This was a simple post to show you how is implementing loading animation in AngularJS and jQuery done. Of course your scenario may have additional or more complex requirements but this should serve as a basis to set it up.

Multilanguage AngularJS apps

Last two years, almost every project that I have worked on, has had the requirement of multilingual graphical user interface (GUI) and messages. This scenario may be important if your country has a multilingual environment or if you are opening to international markets and want to give your users the best possible user experience. The former is little easier as the number of supported languages is usually lower than the latter.

So, what is the problem definition here. We need to support dynamic language setting in GUI for two types of components:

  1. Labels
  2. Dropdown lists

In order to define the actual language the user is using, we chose to use a route parameter for it. Our route became something like this:

Route parameter :lang enabled us to get the user’s current language by calling

Then, we used angular library angular-translate which happened to be very convenient and easy to use for us. The setup is pretty easy. You include angular-translate.js file in your index.html and require reference to ‘pascalprecht.translate’ when defining your module, e.g.

After this, we create a json file for every language we wanted to define, eg. en.js file will contain the labels for English language (sq.js for Albanian, and so on), and it looks like this:

We also need to tell our app the translation configuration. I like to do this in a separate configuration file which I call translation.js (don’t forget to reference it in index.html) and it looks like this:

If later I want to add a translation for Albanian language, I will create one file sq.js which contain the translations e.g.

and I will add this line of code to the translation.js file

and the new language is automatically supported.

Now, in the controller that we want to use translation, we need to to tell the language to be used and we do it like by getting the param from route and pass it to $translate object:

In the view, we put the dynamic labels and messages by using an angularjs binding and filtering it with translate

Here we are, our labels will be translated automatically based on the route parameter :lang.

The labels are translated, now we need to translate the dropdown lists. To support list translation, as we already had a small number of languages to be supported, we chose to save list values in the database lookup tables in all languages, so basically, every lookup table has a structure similar to this:

id name_en name_sq

and when we return the json object for the lookup values, we return an object similar to the object below and bind it in our controller to a scope variable list

then our html select element will look like this

In this way, our ng-options will get automatically the language from lang parameter set in $scope from the $routeParams and it will automatically get the lookup name for the specific language

This might not be the best way to implement multilanguage angularjs apps but it worked pretty well in our case and in several other projects I have worked on.

Hope it helps to you as well.

Developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap

In this post I am going to talk about developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap. In my post Develop mobile applications using web development skills, I pointed out a list of possible frameworks which can be used to create a hybrid mobile app. My favorite choice so far is using Cordova/Phonegap (Read my post on my opinion about Cordova/Phonegap) in combination with a hybrid app development framework. In my previous mobile applications I have developed, I used to use jQuery mobile as my framework of choice for developing the UI of my apps. Nowadays, I have switched to another combination, which is:

Cordova/Phonegap + AngularJS + Bootstrap

The hybrid mobile app architecture with Phonegap, AngularJS, Bootstrap looks like this:

The presentation layer is built with Bootstrap framework, the app domain is modelled using AngularJS, and the is packaged using Cordova/Phonegap to a native app. Let us go through the components of this hybrid mobile app architecture and describe them.

Bootstrap

Bootstrap is a mobile-first responsive front-end framework. What this mean? Bootstrap has an easy to use responsive grid which allows you to position your layout in a well structured responsive way. As the framework is built with mobile use in mind, it responds well to different screen sizes and adapts the layout of the app easily to different screen sizes. This is a good possibility to use the very same implementation for tablet and mobile devices of different screen sizes. And it is not only the grid that makes it special. It helps you manage typography, responsive images, forms, form validation messages, notification messages, responsive tables, and a good number of UI components. You can download it from getbootstrap.com.

AngularJS

AngularJS

AngularJS

A very powerful, full-featured JavaScript MVW framework. With AngularJS framework, you can give a structure to your app domain model and manage your app logic in a very flexible way. Everything is organized around a model which is displayed through a View. Views can be well structured templated HTML code styled and organized using Bootstrap. Controllers organize the communication between the View, Services, and all other parts. The framework supports a good routing mechanism, which can also be extended by other extension libraries for more powerful functionalities. There are a plethora of extension libraries for AngularJS which add value to the framework by filling in the gaps of the framework. You can get AngularJS from angularjs.org.

 

Cordova/Phonegap

Cordova is an Apache project which creates an underlying platform for developing multiplatform mobile applications. In our case, it makes possible the AngularJS+Bootstrap web app to be packaged to a native mobile app which can be published to the mobile markets and be instlalled in mobile devices. Adobe PhoneGap is a distribution of Cordova.

Basically what Cordova does is to make possible the web app to run inside a WebView component of a native app, we can say it as a native package of a web app. You can do the packaging using Cordova Command Line Interface (CLI) or using Adobe PhoneGap Build which does not require any installations.

The most powerful feature of Cordova in my opinion is the extension possibility by plugins. By installing specific plugins, you get access to device’s hardware such as camera, compass, geolocation, as well as other device specific APIs such as contacts, media, notifications, etc. Very powerful plugins such as barcode reading, push notifications, and many more, can give your application good features by writing few lines of code.

The development process

As we described the architecture parts, let us start with the process of developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap. We start with creating a sample application  which shows you your current location coordinates and demonstrate the development process. The easiest way to start the app development is by creating initial template using Cordova/Phonegap CLI. We do this through this command (if you do not have cordova cli installed, here is the link showing how to do it: https://cordova.apache.org/docs/en/4.0.0/guide_cli_index.md.html)

The create command requires 3 arguments:

  1. The directory name to be created for generation of the project, in our case “blogSample”
  2. The second argument is the project identifier, in our case “com.ariancelina.blogSample”. Usually it is used as a reversed domain name identifier
  3. The third argument is the display title of the application, in our case “BlogSample”

In this sample code, I used phonegap to create the app. The command equally applies to cordova as well.

If you already had phonegap installed and the app was created successfully, inside blogSample directory you should have a config.xml file and four other directories (hooks, platforms, plugins, and www). Platforms folder contains builds for specific platforms, plugins directory contains installed plugins, and WWW directory contains all our web code (AngularJS + Bootstrap + other files).

To read our location coordinates we need to install the Geolocation plugin (Find the list of plugins) and we do that by executing this command:

Now that we have the initial structure, we need to add platforms to which we want to deploy, but to do that, we need to be inside out app directory, which in our case is blogSample. Adding ios platform is done using the command

After the platform is added, we can build our app using

We can repeat last two commands for all other supported platforms like android, windows phone, etc.

If we want to test our app, we can go to directory blogSample/platforms/ios and lunch BlogSample.xcodeproj and run the app in simulator or existing device.

We have our platform set up, now let us add the AngularJS and Bootstrap files. After we download these (download AngularJS as a zip file so you get all parts of it), we put inside blogSample/www/js directory AngularJS and Bootstrap js files: jquery-1.11.2.min.js (jquery is a dependency of bootstrap and can be downloaded from jquery.com)angular.min.js, angular-route.min.js and bootstrap.min.js. Inside blogSample/www/css directory we put bootstrap.min.css and bootstrap-theme.min.css files. And the last part here is to link these files in our main file index.html. We put css code in head section:

and near the closing body tag we link the javascript files

Now we have the setup ready and we can start coding the logic. We need three things to define to make it work, we need an angular route config which allows us to navigate from page to page, then we need an angular controller, and a view which will display the user his/her current location.

We start with the app.js file which contains the initialization of the js app. This file also is the place where the initialization events are placed. In our case, it looks like this:

We start by defining our angular app, blogSample (line 1). We initiate it and  define the modules which we need (ngRoute, ui.bootstrap). There are other interesting things happening here. As we are used to use jquery ready function to react when the page is loaded and ready for use, here we have onDeviceReady event which is fired when the app is loaded and we can start using it. Inside this event, we will get the current position of the device through this line of code

The getCurrentPosition function which gets the current latitude and longitude of the device, needs two functions as parameters, first being the function that is called if the current location can be obtained successfully, and the latter for errors. The error function is used to report the unavailability of the location. The success function is used to read the coordinates and bind them to our angular app, blogSample through this function

Now that we have our app setup ready, let us define two views, one about page and the other showing location information. Showing the coordinates inside the view is done using

AngularJS will substitute the values inside curly braces with current coordinates set in onSuccess function. But views do not access application level values. We usually link a controller with a view, and view is limited to the scope of that controller, so we need to define a controller to glue the coordinates to the view. The controller will look like:

and finally we add the router configuration to bind the controller to the view and enable the user moving between pages. The router has this code:

The router part defines one default url and ‘/about’ url. The default url ‘/’ binds to main.html view, and the ‘/about’ url binds to about.html view.

Now that we have all the building pieces in place, we need to add the reference of last created files in index.html and the references will look like this:

Now that everything is on place, we can deploy our app to the phone for testing, or run it in a simulator. Running the application is different depending on the platform. You may use the simulators that can be started from phonegap, by xcode, eclipse, or android studio, but for any serious app development, I would strongly suggest you try your app in a real device. I will not go into details about deployment as it is out of scope of this post, but in the simplest scenario, you may go to platforms folder inside  your phonegap project folder, and open the project of the specific platform and run the project from the respective ide.

The complete source code of this application can be found on GitHub https://github.com/acelina/phonegapWithAngularJs, you may download it and try it on your computer.