Friday, June 17, 2016

Polymer 1.0: dom-repeat tutorial part 1

cat-appender is the name of the element we are creating

Dom-repeat is one of the most useful helper elements in Polymer, in this post series we’ll go through a working example adding, removing and retrieving data, step by step explaining what is happening and linking to the appropriate documentation page for more in-depth details.


This post is part 1 of a 2-part series, it will discuss how to setup the element and basic dom-repeat.


First off, I’m assuming that you know what polymer is and that you have Created an element project.


The element we are going to work on is repeating unordered list items, it is called “cat-appender” (because I like cats, but feel free to name it whatever you like :3).

Here's a demo of what the final result will look like, I’ve removed all the clutter to focus on the element itself.


Enough talking, let’s dive in:

Setting up the element

We will start by setting up the element, that is giving it the required properties and template.


Here’s what the element prototype looks like (at the end of cat-appender.html in the demo) :



<script>
  Polymer({
    is: 'cat-appender',
    properties:{
      kitties: Array
    }
  });
</script>

We have a sole property defined in the properties object, that’s the array that will go inside the “dom-repeat” in a moment, it’s an array of objects as you may have guessed.

Here’s what the template looks like (cat-appender.html in the demo still):
Inside your <dom-module> and <template> elements
<ul>
  <template is="dom-repeat" items="[[kitties]]" as="kitty">
    <li>
      [[kitty.name]] : [[kitty.age]]
    </li>
  </template>
</ul>

I assume that you came to this post because you’ve read about basic dom-repeat somewhere, so I’m going with a quick explanation about what’s going on here:

  • We are telling Polymer that we want to repeat the enclosed markup with the <template is="dom-repeat">.
  • We provide the data we want to iterate on as the “items” property, here, it is the “kitties” property that we defined earlier for the element prototype, it takes its value from the parent (the “host” element when used in a page).
  • “as” property gives an alias to the default “item” that is used to reference the current item that the dom-repeat is iterating over at the moment, this property is commonly used in nested dom-repeats to reference parent template, but I thought it’s worth mentioning.
  • Inside we are rendering an <li> for every item (object) in the array, notice that we’ve used the alias “kitty” instead of the default “item” that we would’ve used otherwise.



Notes on data binding annotations

Choosing an annotation for data binding may seem confusing at first, make sure that you read through the documentation and get your head around it.

As a simple rule: one-way data binding ( [[ ]] ) will be suitable when the goal is to show (read) or use the data without modifications, like when we used it to iterate over the kitties array in the dom-repeat.

While automatic binding ( {{ }} ) is most useful when binding to data that will change, like an input value or an element property (not attribute, see attribute binding if you want to investigate), or when binding to array items (As they are always two-way).




Now, on the file that you’ll show your element in (index.html in the demo):


<link rel="import" href="cat-appender.html">

<h3>Cat list</h3>
<cat-appender 
kitties='[{"name": "Simba", "age": 29}, {"name": "Mufasa", "age": 35}, {"name": "Sylvester", "age":71} ]' >
</cat-appender>

That code imports the element that we just created, and shows it on the page (if you have created an element project, you already have it setup in your demo directory), we then give it an array of objects (cats with names and ages, in this case) as a property.



Note:

  • Single quotes are being used for the property itself, that’s because this array is being deserialized into a JSON string, which must have double quotes.
  • Also the property names for the objects are enclosed in double quotes, it will not deserialize properly if you remove the quotes (because it’s a JSON string, not a Javascript object). Further reading
We now have a template that is repeated on an array, nothing very interesting so far.
In the next part we will let the user add a cat, remove a cat and retrieve the cats in the list through our “API”, stay tuned, it’s coming very soon..


Update: part 2 is here

Monday, June 13, 2016

Focus: the Pomodoro Technique



Like all programmers, you have a lot of things in your head that you want to accomplish, and these things are competing for your attention.

I’ve found myself struggling to focus solely on one task, whenever I started a task the other thing just pops up in my head and grabs my attention and most of the time I would listen to it and start with it until something else knocks on my brain.
This kills productivity and causes a bad feeling.

I recently came across this technique called the Pomodoro (tomato, in Italian) technique and it works like magic, it helped me focus on one thing at a time and it involves frequent breaks, so you accomplish more without ending up totally exhausted.

The technique is as follows:
  • Choose the task that you’ll start working on for this session (a session is called a  Pomodoro).
  • Set a timer for 25 minutes and start working on that task.
  • If anything crossed your mind just ignore it or write it down for later.
  • If an unavoidable interruption occurs, restart your session.
  • After the 25 minutes are over, take a 5-minute break.
  • Repeat with the same task if it is not over yet, or with a new task, until you’ve made, say, 4 pomodoros then take a long break (15 minutes or something)

Keeping track of these steps can be done physically, using a timer, paper and pen, or virtually as there are apps that count down the minutes for your pomodoro sessions and breaks.

I use an app called “Pomodoro One” on macOS, it’s free.

Monday, May 30, 2016

The Mechanics of Web Sessions

Web developers use sessions almost everyday, but not all know how it really works, this post will cover some important questions about web server sessions, so it would be easier to debug your session problems.


No TL;DR for you today, sorry, but here’s a table of contents.


What is a web server session?

A session in general is some data that’s shared between two or more devices.

A web server session is used to exchange connection-specific temporary information between the server and the browser for the duration of the browsing session.

A session is used to tell the server which client has sent the request so it knows what data it will send to that client.

What is a web server session, really?

A web server session is some data structure that usually stores key-value pairs of data that’s stored and managed on the web server, it can be stored in a file, cookie, database or other storage options (including the RAM).
That data structure, say, a file, is created for each user and stores whatever is the backend (PHP, Python, etc..) tell it to store, but most importantly it carries the session ID, that’s unique for each connection (browser session).

How exactly does that “exchange” happen?

As soon as you hit a web page, the server receives your request for that particular page, it sends you the page content along with your “randomly” generated session ID (usually in a cookie).
That cookie carries your session ID back and forth between all your requests for the current browsing session so that the server knows who you are and persists your information across subsequent requests.
So basically that sookie is like a fingerprint for your browser for the current session.

Screen Shot 2016-05-27 at 11.37.30 PM.png


The cookie name is different between languages and frameworks (In this image it’s the default Laravel session cookie name) , you can set its name to your liking, what matters is that its value is the session ID that server had assigned to your browser at that time.

Let’s take an example like when you log into an application, the server hands the session information to the backend language, e.g. PHP, so that it stores that you are logged in (stores your user ID that is in the database, for example) in the session so that you don’t have to login at every request.

Session exchange diagram


So, how does the server know which session file is mine?


At every request, your browser sends back your session ID (in the form of a cookie or in URL parameters, whichever is the method) to the server along with the request to the web page to tell the server that it’s really you from before.

The server compares the session ID you just sent it with the session IDs it has stored for all the clients and it gets your specific information and makes it available to your backend programming language to process the request (get your information from the database using the user ID in your session and feed that into you a user-specific profile page, for example) and send you back your requested page, and your session ID cookie with a Set-Cookie header.



Screen Shot 2016-05-28 at 12.13.52 AM.png


This goes on until the session is destroyed;

Logging out, closing the browser or a timeout, for example, are all session destroyers.

When does this “Session ID” get created?

In general, your session is created when there’s a mismatch between the session IDs that are exchanged between the browser and the server, including missing ID from either ends.

  • With the first page you open in a web application, the request for that web page is sent without the session ID cookie, so the server knows that it should start giving you a name (session ID) which you use after that to tell it that it’s the same you.
  • You open another browser (or use a new private window), explaining why in a moment.
  • The session is deleted on the server.

When I open another browser tab or window, why is the server still identifying me?

The session cookie is stored by the browser, usually the browser keeps this kind of information until you close it, so all tabs and windows of the same browser still have the cookie stored and accessible because it’s the same browsing sessions.

But when I open a private (incognito) window of the same browser, I’m not logged in, my session is not there.

According to browser specifications for private browsing and how it works, private browsing is treated as an independent entity, it’s an -almost- totally independent browsing session with an “empty cookie jar”, so it doesn't have access to your cookies from before.

“Remember me” ?

So, if the session ends when you close the browser window, how do sites that have a “remember me” checkbox save the session information even after closing the browser?

Session cookies don’t have an expiry date on them, so the browser knows that it should destroy it when it’s closed.

On the other hand, the “remember” me cookie has an expiration date in the future (say, after two weeks) so it keeps the cookie from being deleted when the browsing session ends.


That’s it. As usual, please correct my mistakes, point out missing information and ask questions.

References

Wednesday, May 25, 2016

"Unexpected token ILLEGAL" when getting markup from the server?

Getting “Unexpected token ILLEGAL“ (maybe “Unexpected EOF” in Safari)  when retrieving your HTML from the server and parsing it? Even worse the stack trace is pointing you to some weird place (in my case it’s some line column in jquery.min.js).
Newlines are to suspect here..
The story here is that I was retrieving a form markup with an ajax request from a PHP backend, that’s getting the data from MySQL and filling the form template with the result, sending the form to the browser then placing this markup into a div with jQuery ( $(“#somediv”).html(markup) ).
The form had a textarea and a script that compared the value of that field to some other value, and that was the problem, when the field (textarea value) had a newline, Javascript would just breakdown, so if you have a similar situation, read along..



Why is this happening

Javascript (and every other language for that matter, AFAIK) can’t have line breaks between the quotes of a string, that’s because when JS encounters a line break it will consider that new line an indication that it’s the end of a command (statement - piece of code) and proceeds to the next line imagining it’s a new command and that would make it treat the new quote character as an opening, not closing quote and boom.. that’s why we have the “\n” thingy.


The catch

JS recognizes the “\n” with no problems, but HTML does not, it has a special entity for the line break.
After investigating, I found out that PHP saves the new lines from the textarea as a vertical tab (ASCII code 013) and a backspace (ASCII code 010).
HTML understands the vertical tab (through a special entity) and that’s how newlines can be displayed in a textarea without problems.

I needed not to alter what’s being saved but rather change how it’s displayed.

The solution

The HTML version of a vertical tab is &#013; so we need to replace every “013” ASCII character with it’s HTML version before sending it to the browser, we will also get rid of the backspace character because it would cause problems (ASCII code 010).

So, in PHP (in my case) write down the code that will do exactly that..
//Starting off with an empty string the will hold the address after modifications
$newAddress = "";
$address = $row['address']; //Address returned from the database query
//Loop through the string characters
for ($char = 0; $char < strlen($address); $char++) {
    //ord() gets the ASCII code for the current character
    if (ord($address[$char]) == 13){
        $newAddress .= ' &#013;';
    }
    //Getting rid of the backspace character
    elseif (ord($address[$char]) != 10){
        $newAddress .= $address[$char];
    }
}
//$row is what is being used to fill out the form template with data, so that's what’s being placed in the textarea and what’s being compared in the script
$row['address'] = $newAddress;


Just note that the address when used in the script will have &#013; in place of new lines (that shouldn’t be a problem though) .


That’s it, feel free to fill the gaps and ask questions.