Monthly Archives: May 2017

Angular2 – Attribute Directives

Angular2 – Attribute Directives

Directives give us the ability to create tags which can be directly used in the template. Since they are not HTML5 templates, we need to define how Angular can render these components In the end, they would be converted to a representation that a browser understands.

Angular can convert these directives and translate to the corresponding HTML5 and javascript code, which browser understands.

Types of Directives

There are three types of directives in angular2:

  1. Component Directives:

    Components are displayed using the selectors used in the decorator when we create a component.

  2. Structural Directives:

    Change the DOM structure.

  3. Attribute Directives

    Change the appearance or behavior of an existing DOM element.

Attribute Directives

As discussed above, attribute directives allows changing the behavior and / or appearance of an existing DOM element. In this post, we are just discussing Attribute Directives.

ng new

ng new

ng generate directive

ng generate directive

A directive’s type is decorated with @Directive decorator. Please check selector and change in accordance with your naming convention if required. No, it doesn’t have to implement an interface or inherit from some special type.

Angular CLI also performs the necessary plumbing required in the app.module. It automatically imports the directive and adds it to the Declarations section.

Attribute with Defaults

Let’s first update our directive with some default properties. In the following case, the directive is causing a rotation of 90% by keeping the transform-origin as 50% 50%. It also adds a background color ‘cyan’.

We can easily use this directive in our template as follows (app.component.html).

The page is displayed as follows:

transform rotate

transform rotate

You can notice that it is rotated 90 degrees as expected.

Listening to Directive’s Host Element

We can also listen for events from directive’s host element. In this case we are listening to mouseenter event from Host. As the event is triggered, we are trying to update the rotation angle to the input property rotationAngle.

We also need to update the component’s template to use the input property. Here we are just setting it to 45 literal value.

As we run the app, page is displayed with the element rotated at 90 degrees.
Screen Shot 2017-05-28 at 5.18.44 PM

As we mouse over the element, the rotation is updated to 45 degrees as follows:

Screen Shot 2017-05-28 at 5.19.03 PM

Using Directive’s selector for Property Binding

Angular2 also allows the directive to be used for property binding to one of it’s own input properties. We just need to use the directive name for input property. Here we are using appRotated for rotationAngle property.

And here is how we are using the binding using directive’s name.

Using Renderer to set Style Properties

Up until now we are directly using the element’s style properties to set the background color. An alternative is to use Renderer. The Renderer class is a built-in service that provides an abstraction for UI rendering manipulations. Here we are using Renderer to set the backgroundColor from the style of the nativeElement for the ElementRef.

Directive’s @Input Binding to Template Properties

We can also bind directive input properties to the properties of the component. Here we are adding a new property myangle to app.component. We are assigning property a value of 145.

Now we can use this property to bind in the component’s template.

The component can also implement OnInit and assign the property value in the implementation method as follows:

Property Binding & Constructor

It must be remembered that the property binding values are picked up after the directive is constructed. If we try to get the value, it would be undefined as below:

property binding and constructors

property binding and constructors

The solution is to implement OnInit by the directive and use the necessary initializations in the OnInit method:

directive oninit

directive oninit

Code

github repository

github repository

Postman Interceptor – Chrome Extension

Postman – Interceptor Chrome Extension

Postman has an alternate to fiddler to capture and replay the HTTP requests sent by browser. It is called Postman Interceptor. There is a number of steps you need to follow in order to get request interception. You can start with Postman and enable interceptor from the header. If Interceptor is not installed, it would direct you to Chrome Store where it can be installed from.

interceptor

interceptor

This would launch chrome store with the plugin loaded. You can install the plugin from here:

install_chrome

install_chrome

Just make sure that you still have the interceptor enabled from Postman. Yes, this installs a chrome plugin, and you can enable / disable the recording right from the browser.

enable interception in chrome

enable interception in chrome

As it is enabled, the requests are displayed in the Postman. Here you can evaluate the request details.

postman capture

postman capture

Curator for Managing Elastic Search Indices

Curator for Managing Elastic Search Indices

Curator is one of the officially supported plugins of Elastic Search. It supports a number of features including the following:

  • Add or remove indices (or both!) from an alias
  • Change shard routing allocation
  • Close indices
  • Create index
  • Delete indices
  • Delete snapshots
  • Open closed indices
  • forceMerge indices
  • reindex indices, including from remote clusters
  • Change the number of replicas per shard for indices
  • rollover indices
  • Take a snapshot (backup) of indices
  • Restore snapshots

Is this plugin officially supported?
Plugin is officially supported ElasticSearch client:
https://www.elastic.co/guide/en/elasticsearch/client/curator/current/index.html

Is this Open Source:
Yes, the code is available here:

https://github.com/elastic/curator

Purging Index Data

If space is a big concern for Elastic Search databases where you keep your logs then we can always schedule purging older data. Let’s download the plugin first:

https://www.elastic.co/guide/en/elasticsearch/client/curator/current/installation.html

Required Configurations
We need to update two configuration files here:

  1. action.yml
  2. config.yml

action.yml
Here we are deleting all indices which follows logstash- where index data is older than 6 days.

actions:
  1:
    action: delete_indices
    description: "Delete Older Indices"
    options:
      timeout_override:
      continue_if_exception: False
      disable_action: False
    filters:
     - filtertype: pattern
       kind: prefix
       value: logstash-
     - filtertype: age
       source: name
       direction: older
       timestring: '%Y.%m.%d'
       unit: days
       unit_count: 6
       field:
       stats_result:
       epoch:
       exclude: False

config.yml
This is used to provide connection information for host. It is also used to specify log configuration:

---
# Remember, leave a key empty if there is no value.  None will be a string,
# not a Python "NoneType"
client:
  hosts: HOST_NAME
  port: 9200
  use_ssl: False
  ssl_no_validate: False
  timeout: 30
  master_only: False

logging:
  loglevel: INFO
  logformat: default
  blacklist: []

Running Curator
We can run curator as follows:

curator.exe --config config.yml action.yml

Play Framework – Input line is too long…

Play Framework – Input line is too long…

I have recently come across this problem where Play framework service wouldn’t run on some windows servers and result in the following error:

Input line is too long

Input line is too long

The problem is APP_CLASS. Just update it to the following it should work fine:

set "APP_CLASSPATH=%APP_LIB_DIR%\..\conf\;%APP_LIB_DIR%\*"

Note: This would load all the libraries from the APP_LIB_DIR generally set in the same batch file.

Angular 2 Routes – Controlling Access / Guards

Angular2 Routes – Controlling Access using Route Guards
Previously we discussed how we can use routing in an Angular2 app. This allows a user to navigate through the user interface.

Screen Shot 2017-05-18 at 12.46.06 AM

In this post we are going to discuss how we can control access to these routes. These control work as guards to navigate in and away from the route.

Available Route Guards
There are a number of Route Guard types available for an Angular2 app. These are interfaces which can also be implemented by the same class. It just needs to implement the contract methods.

  1. CanActivate
  2. CanActivateChild()
  3. CanDeactivate
  4. Resolve
  5. CanLoad

What is the order of execution of these route guards?
An application can consist of various routes. There might also be route hierarchies if there are parent-child relationships between components. It must be remembered that route guards are executed bottom-up. So bottom child routes are executed before top routes are executed. It starts with CanDeactivate followed by CanActivateChild and CanActivate. CanLoad is executed when a module is loaded. What about Resolve??

Are they executed Synchronously / Asynchronously?
Route guards support both synchronous and asynchronous executions. It uses rxJS for asynchronus execution. For synchronous execution, the guard just returns true or false. In the asynchronous case, it returns Observable<Boolean> instead. If you are wondering why we need asynchronous execution for routes at all, consider the case when you might need to display a message to user and get a confirmation before exiting to confirm the possible lost changes. Or you might need a service call before a guard is satisfied.

Guards aren’t democratic
Guards are not democratic. It’s not sufficient to satisfy most routes. All routes should eventually return true before a route can be activated.

Example Scenario – Chat Service
Let’s use the example repository from our existing Angular2 Routes repository from one of our previous discussion. Let’s add a component for chat. Since our service representatives are only available during the working hours of 9:00 AM to 5:00 PM, we only want the chat page to be available during that time duration. We also want to show some message as they are leaving the page to thank their interaction with our service agents.

Creating the Component
Let’s first create chat component using Angular2 CLI.

ng generate component chat

ng generate component chat

Adding chat component to Route Config
Now let’s add chat component to RouteConfig. This is defined in app.module.ts. Here we are using “/chat” as sub-route for our chat page.

Now as we use the configured route, we are shown with this amazing message that we defined in chat.component.html page. You might not have seen the same message before but that’s a general intention of all customer services. And isn’t the intention that counts…

chat page

chat page

CanActivate Route Guard
Let’s create a CanActivate route guard. This checks the current time. If the current time falls between 9:00 AM and 5:00 PM, the page is displayed.

We need to define CanActivate route. Obviously this would implement CanActivate interface. If you are coming from C# or Java background, the implementation might seem a little strange to you. Actually the same method might return either of a list of return type here. Here you can see that the method returns boolean | Observable<boolean> | Promise<boolean>

The other interesting piece is string interpolation in console.log(). Other languages do support interpolation now including C#. But this is interesting that typescript also supports this. We need to use back-tick for interpolating variables in scope.

console.log(`Is Chat allowed: ${isAllowed}`)

And this is how it is displayed. Since we are accessing this during the working hours of our chat agents, the page is navigated properly. You can also notice the message logged in the console.

Chat Allowed View

Chat Allowed View

CanDeactivate Route Guard
Let’s show a message to the user as they are leaving our page. We don’t want to keep them on our component, we just want to show them, we care… That’s why we are just showing them in the console log.

Here we are just showing the message and returning true.

We need to add this guard to the component. We also need to add this in the providers array.

can deactivate

can deactivate

Now as we navigate away from the component, the message is displayed in the console. In order to show it is working, we have added some router links to our app.component.html to using hyperlinks for navigation.

Github Repository:

Github Repository

Github Repository