Backup your database

To backup your database regularly is one of the tasks that can be very easily accomplished but is quite often neglected until the minute you face the first disaster. Backup solutions can be of very complex types which you might engineer to simple ones like copy and pasting. Depending on your application, the necessity for complex solutions might vary. So what could be a minimum solution that is viable and stable?

The simplest solution in my opinion should contain these elements:

  • Create a dump of the database
  • Copy the dump to another location (different from the DB server)

Now depending on your RDBMS and operating system, you can take different approaches to implement these two tasks. On a Linux system with a MySQL or PostgreSQL, my approach would be to write a shell script which does these two functions. One such a script might look like this

#!/bin/bash

DATE=`date +%Y%m%d-%s`

FILE=/path_to_bckp_folder/$DATE-blog.sql

mysqldump  db_name > $FILE

Line no. 3 creates the DATE variable which holds the current timestamp. It is used to construct the name of the backup file. Line no. 5 creates the FILE variable which holds the complete path of the backup file. Line no. 7 is the MySQL command to dump the database named “db_name” to the path determined in line no. 5.

So far, this code completes the first task of backup up the database. The next task is to copy it somewhere else so we don’t have the db and backup on the same disk. Now this “somewhere” could be some other server, some other disk, or somewhere else e.g. cloud storage. My preferred choice would be to put it to a cloud storage like AWS S3. Having aws cli installed, copying the backup file to an AWS S3 bucket is a one line code

aws s3 cp $FILE s3://bucket_path

The complete file would look like:

#!/bin/bash

DATE=`date +%Y%m%d-%s`

FILE=/path_to_bckp_folder/$DATE-blog.sql

mysqldump  db_name > $FILE

aws s3 cp $FILE s3://blog-db-bckp

Conclusion

I know a lot of people might not agree with me that this is a good solution, but in my opinion, this is the minimum code that does the work. What you need to do next is add this script to /etc/cron.daily folder and your script will execute daily and do the backup for you (please make sure that permissions are correctly set so it can be executed). It is not the most elegant solution but does the job.

As a bonus point, I would also add a “done” notification to a script which would send an email or post to a slack channel or whatever notification that suits you so you know that your script has executed.

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

docker pull docker.elastic.co/elasticsearch/elasticsearch:5.3.1

and running the container

docker run -p 9200:9200 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" docker.elastic.co/elasticsearch/elasticsearch:5.3.1

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

{
  name: "B4VsybF",
  cluster_name: "docker-cluster",
  cluster_uuid: "EDkqSWH1Q7mjM3RSEV7kVw",
  version: {
    number: "5.3.1",
    build_hash: "5f9cf58",
    build_date: "2017-04-17T15:52:53.846Z",
    build_snapshot: false,
    lucene_version: "6.4.2"
  },
  tagline: "You Know, for Search"
}

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

PUT /documents/person
{
  "shards":2,
  "replicas":1
}

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

POST /documents/person/1
{
  "name": "Arian",
  "last_name": "Celina",
  "phone": "1234567"
}

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

{
  "_index": "documents",
  "_type": "person",
  "_id": "1",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "created": true
}

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

curl -XPOST 'http://localhost:9200/documents/person' -d /path/to/file.json

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

GET /documents/person/_search?q=phone:1234567

or in a more complex form

GET /documents/person
{
  "query": {
    "match": {
      "phone": "1234567"
    }
  }
}

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.

Learning process of a software developer

Lifelong learning is a vital skill for software developers. Without continuous learning, I cannot imagine how could a software developer have a successful career in our days. But how can one keep up with the loads of information out there. The amount of information to be consumed passes far our ability to consume and learn. How do we develop ourselves as successful software developers? What strategies should we use? Here is the learning process I use, perhaps it could be useful for you too.

1. Practice

There is a good saying I like: “Practice makes perfect”. If there is one thing that I would choose above all, it is the practice. Writing code is the single most important thing you need to do to get good at software craftsmanship. You may do it in different ways and different levels. Being a full time software developer I would say is the best way, but you may also work on your own or contribute to open source projects in your free time. Apart of full time serious projects, I find it also very useful to work on a side project. Side projects can be fun and may give you the opportunity to learn and enjoy what you do, and often, these projects can be turned to successful projects.

2. Following trends

Following trends is very important to keep your skills sharp. Knowing what is coming next in your industry is of utmost importance to excel in your career as a software developer. Following trends can be done in several ways and you may find which suits you best. You may choose to follow the industry leads in social media, or read regularly their blogs, or you might be just the guy who goes to the events of user groups and conferences. Following trends will show you what you need to learn next and where should you put your focus so you are trained well to cope with future challenges.

3. Video tutorials

Video tutorials have become the common way we consume information today. Videos have many benefits. We can consume higher amount of information in a shorter amount of time. Also, most people learn better when they consume information visually, and this makes watching videos a preferred way to learn new technologies. You may choose to subscribe to a learning site (e.g. PluralSight or Udemy), or you may choose to watch videos in Youtube, you have plenty of choices.

4. Books

Although we have several ways to consume information, I think books are the best choice when you want to learn a technology thoroughly. Tutorials are good to get a glimpse on a technology for evaluation purposes or to get an idea how it is working, but if you want to get a sound understanding of something, I think, books are still the best choice. They usually are more carefully written, present the information more completely and in a flowing order. Yes, they take more time to read and they are larger in volume, but they give you a better understanding and full perspective of a big picture.

5. Sharing

One of the best practices for learning better in my opinion is sharing your knowledge. Be it blogging, showing off your code in a user group, or teaching someone on a what you are good at, sharing your knowledge pushes you learn better what you know. Teaching challenges your understanding of a subject and helps you improve your knowledge. This is my main motivation why I write in this blog.

Summary

The learning process of a developer nowadays might be different and adjusted to custom habits and requirements, however, in my opinion, these are some of the best ways to learn new technologies and always maintain your skills. What are your learning habits? Share with us.

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.

 

*python logo image source: http://www.vizteams.com/wp-content/uploads/2013/08/python-logo-master.png

5 reasons you should be a web developer

Over the plenty of career choices in the world economies, choosing what to do for living is not an easy decision. A healthy career comes out of finding the intersection of market demand and what you love to do. Being in the software industry for around fourteen years, and ten of them spent in web development, my career choice of web developer has come out of a funnel, starting as a desktop application developer and refining my knowledge to web development as the potential market started to emerge. But web development has changed dramatically last ten years. The possibilities of web applications often surpass those of desktop applications in market reach and sales perspectives. I will list here 5 reasons you should be a web developer.

1. You can work independently

Being a good team player is an essential skill required to be a part of any organization, but when it comes to starting a private business or wanting to earn some extra money in addition to your full time job, being able to work alone is equally important and a huge benefit. As a web developer, you can create web applications, web sites, themes, and many more digital products which you can easily monetize. You may sell gigs in sites such as Fiver, or create WordPress themes and earn some extra money by working an hour or two in the afternoons at your home .

2. You do not have a big startup cost

Developing web applications does not require huge computing resources. The startup cost is as cheap as having a moderate computer and an internet connection. Many of the software tools which are used to develop web applications are free of charge or cost less than $100. Nowadays, even the hosting providers have lowered the hosting prices quite a bit, and you may easily find good hosting to your web site(s) for ~$5 per month.

3. You can sell your work online

Being a web developer, you do not need any shipping or packaging of your products. You simply push your code to the hosting server and run it there. You may also easily do remote consulting work or create web sites and sell them in different market places. Envato is one of the companies that provides different marketplaces for different digital products, one of them being for WordPress themes: themeforest.net.

4. You may develop mobile applications with web development skills

Web development has evolved over the years, and with that, the support to browsers as well. In current days, you may easily pack a web application as a mobile application and publish it in Apple AppStore, Google PlayStore, or any other mobile app market. The user interfaces may often be very similar to native applications and may create a full featured mobile app with a plain web development skills, thus, allowing yourself access to a huge market and business opportunities.

5. You have plenty of tools and framework to suit your work style

As a web developer, you will have plenty of tools and frameworks which make your job easy in many different ways. Of course this is highly impacted by the platform you choose, but I would confidently say that, all major web development platforms and languages have good communities with good support and plenty of tools available to develop web applications and web sites. This will make your jump start to web development easier and time to market quite short.

If you have not yet decided which profile of developer you want to be, here are five reasons to be a web developer. Web developers have plenty of opportunities in front of them which suits the needs of different kinds of persons. You may be an entrepreneur or a full time professional developer, web development has a lot to offer to you.

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:

internal sealed class Configuration : DbMigrationsConfiguration<MyFinancesContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(MyFinancesContext context)
        {
            var cashPaymentType = new PaymentType() {Active = true, Name = "Cash"};
            var visaCardPaymentType = new PaymentType() {Active = true, Name = "Visa Card"};

            context.PaymentTypes.AddOrUpdate(cashPaymentType);
            context.PaymentTypes.AddOrUpdate(visaCardPaymentType);

            var foodCategory = new Category() {Active = true, Name = "Food"};
            var rentCategory = new Category() {Active = true, Name = "Rent"};

            context.Categories.AddOrUpdate(foodCategory);
            context.Categories.AddOrUpdate(rentCategory);

            context.SaveChanges();
        }
    }

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:

public class HumanResourcesContext : DbContext
{
}

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.

public class HumanResourcesContext : DbContext
{
  DbSet<Person> Persons;
  DbSet<Country> Countries;
}

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.

using (var db = new HumanResourcesContext)
{
   Person testPerson = db.Persons.find(1);
}

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:

public class HumanResourcesContext : DbContext
{
 public HumanResourcesContext() : base("myConnectionString")
 {
 }
}

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

public class HumanResourcesContext : DbContext
{
   public HumanResourcesContext() : base("Data Source=(LocalDb)\...")
   {
   }
}

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.

public class Person
{
   public int Id {get; set;}
   public string Name {get; set;}
   public string Surname {get; set;}
   public DateTime BirthDate {get; set;}
}

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.

public class Person
{
   public int Id {get; set;}

   [required]
   public string Name {get; set;}

   [required]
   [MaxLength(50)]
   public string Surname {get; set;}

   public DateTime BirthDate {get; set;}
}

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:

public class Country
{
  public int Id {get; set;}
  public string Name {get; set;}
}

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

public class Person
{
   public int Id {get; set;}

   [required]
   public string Name {get; set;}

   [required]
   [MaxLength(50)]
   public string Surname {get; set;}

   public DateTime BirthDate {get; set;}

   public virtual Country Country {get; set;}
}

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.

(function() {
	angular.module("myApp", ["restangular"]).config(function(RestangularProvider) {
                //set the base url for api calls on our RESTful services
		var newBaseUrl = "";
		if (window.location.hostname == "localhost") {
			newBaseUrl = "http://localhost:8080/api/rest/register";
		} else {
			var deployedAt = window.location.href.substring(0, window.location.href);
			newBaseUrl = deployedAt + "/api/rest/register";
		}
		RestangularProvider.setBaseUrl(newBaseUrl);
	});
}());

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

//get all students
Restangular.all('students');

//get student with id 1234
Restangular.one('students', 1234);

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:

(function() {
	angular.module("myApp").factory("Students",
		["Restangular", function(Restangular) {
			var service = Restangular.service("students");  
                        // I can add custom methods to my Students service
                        // by adding functions here service
                        service.validateData = function(student) {
                           //validate student data
                        }
			return service;
		}]);
}());

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

Students.getList().then(function(data){
  //do something with the list of students
});

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

Students.one(1234).get().then(function(data){
  //do something with student data
});

Saving a student is also as easy as getting it

//we expect student data to be filled by angularjs databinding

Students.post(student).then(function(data) {
   //interprete save result
});

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:

<form id="subscriptionForm">
  <label for="email">Your email</label>
  <input type="email" id="email" name="email" />
</form>

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

<div id="processing" style="display: none"><img src="spinner.gif" /></div>

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.

$("#subscriptionForm").bind("ajaxSend", function(){	
   $("#processing").show();
}).bind("ajaxComplete", function(){		
   $("#processing").hide();
});

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:

#processing {  
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    z-index:1000;
    background-color:grey;
    opacity: .6;
}

.ajax-loader {
    position: absolute;
    left: 50%;
    top: 50%;
    display: block;     
}

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.

myApp = angular.module('myApp',[]).config(function($httpProvider){
  $httpProvider.interceptors.push(function($q) {
    return {
     'request': function(config) {
         $('#processing').show();
         return config;
      },

      'response': function(response) {
         $('#processing').hide();
         return response;
      }
    };
  });
});

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.