Sunday, December 10, 2017

Global CSS Styles in Angular

Angular recommends component based styling as the component should encapsulate every UI functionality. Here is a typical example using stylesheet for a component:

import { Component } from "@angular/core";

@Component({
    selector: "top-bar",
    templateUrl: "./TopBarComponent.html",
    styleUrls: ["./TopBarComponent.css"]
})
export class TopBarComponent {
}

In some situations we may need to have styles that we want to apply to multiple components or globally across the entire application. In this case we can define a css file and use it in the index.html page.

<link rel="stylesheet" href="~/styles.css" />

With the above approach we may lose the building and bundling provided by Angular and have to extend or implement a separate webpack or gulp task.
I recommend creating a separate component which contains all the global styles and expose these component’s style using encapsulation as shown below:

import { Component, ViewEncapsulation } from "@angular/core";

@Component({
    selector: "app-styles",
    template: "",
    styleUrls: ["./AppStyles.css"],
    encapsulation: ViewEncapsulation.None
})
export class AppStyles {
}

ViewEncapsulation.None exposes all the styles defined in AppStyles.css globally and these styles can be across the application. As a final step we need to include this AppStyles Component (which does not have any visible elments) inside our AppComponent


<app-styles></app-styles>

Friday, November 24, 2017

ASP.NET MVC style layout and section in Angular

As you know ASP.NET MVC provides a great feature for consistent look and feel with Layout engine. This layout engine consists of two main components, RenderBody and RenderSection which helps in defining hot areas in the page where we can substitute content from the current/active page. Almost everyone who worked/working in ASP.NET MVC have used this feature. In this blog I will go over how to recreate the same feature in Angular.

RenderBody

Similar to ASP.NET MVC we need to fill the content of the View at this location in HTML. In Angular this is similar to the router-outlet. So I will wrap the router-outlet with our own component called render-body. Here is the code for this:

import { Component } from '@angular/core';

@Component({
    selector: 'render-body',
    template: '<router-outlet></router-outlet>'
})
export class RenderBodyComponent {
}

RenderBody is straight forward. Whenever there is a route transition, Angular routing automatically inject the content of the view at this location. Here is how RenderBody can be used in the layout page

<render-body></render-body>

RenderSection

In MVC RenderSection allows a part of the layout page be replaced by the content defined in the current page. RenderSection allows us to define multiple named sections in the layout for which the content be defined in each page. It also allows to define a default content if the page does not specify the content.

I implemented the similar functionality in my RenderSection component. In addition I extended the RenderSection with an ability to hide from the content page. I also added the capability to have nested levels of RenderSection.

Similar to MVC, first you would define a named section and then in the content page specify the target where you would like the content to be displayed. Here is how you can use the RenderSection in the layout page with a default content (showing a menu)

<render-section name="menu" fxFlex="25">
    <b>Menu</b> <br />
    <a routerLink="/home">Home</a> <br />
    <a routerLink="/counter">Counter</a> <br />
    <a routerLink="/fetch-data">Fetch Data</a> <br />
</render-section>

In the content page this menu section can be replaced with page specific menu or content.

<render-section target="menu">
    Custom Menu from content page
</render-section>

Let’s delve into the code on how to implement the RenderSection component in Angular.
As we are showing content dynamically when a user navigates from page to page, we have to use ngTemplateOutlet. Angular transclusion (ng-content) is used for displaying the content. Here is the template code for RenderSection component for dynamic content:

<ng-container *ngTemplateOutlet="getTemplate()"></ng-container>
<ng-template #sectionRef>
    <ng-content></ng-content>
</ng-template>`

In the above code I am getting the current page’s template using the getTemplate function call and showing its content.
For each section I am capturing the following data (as defined in the SectionModel):

export class SectionModel {
    name: string;
    hidden: boolean;
    changeDetectorRef: ChangeDetectorRef;
    template: TemplateRef<any>;
    currentTemplate: TemplateRef<any>;
    targets: SectionTargetModel[];
}

Here are the details for each of the properties in the SectioModel
  • name – This holds the name of the section. This is used to display the content when the target is equal to the name of the template
  • hidden – This is the initial setting whether the section be hidden or not
  • changeDetectorRef – This is used to force a change detection when we set the target’s content to the section’s content. If a page has specified the content for a section (using target attribute), this page’s content is set to the section defined with name and the change detection is manually invoked for this section component
  • template – This is the default content for the section. If no target is defined in the content page, then this template is displayed as the section’s content
  • currentTemplate – This the template of the content which is currently shown. The currentTemplate is bound to the section template. This currentTemplate would contain either the default template or the template defined in the current page. A change detection is called whenever there is a change in this variable
  • targets – This is the stack of all the contents defined for a section. As my design support hierarchical replacement of the content, I am using stack. During the page load (ngAfterContentInit) if the page has a render-section, then the section’s template is pushed into this array. When this page is destroyed(ngOnDestroy), then the page’s template is poped. The targets are of type SectionTargetModel array whose definition is below:

export class SectionTargetModel {
    target: string;
    hidden: boolean;
    template: TemplateRef<any>;
}

Now let’s delve into the code. Surprisingly the code is very simple. We need three functions, push, pop and update. Here is important code for each of these functions.

push

As the name indicates it pushes the section defined either in the layout or in the page. This is also needed to support the default section content or the nested sections. During the page load (ngAfterContentInit), the section is pushed into the array.

public push(
            name: string,
            target: string,
            hidden: boolean,
            template: TemplateRef<any>,
            changeDetectorRef: ChangeDetectorRef
            ): void {

    if (name !== undefined) {
        this.sections[name] = <SectionModel>{
            name: name,
            hidden: hidden,
            changeDetectorRef: changeDetectorRef,
            targets: [<SectionTargetModel>{
                target: name,
                hidden: hidden,
                template: template
            }],
            template: template,
            currentTemplate: template
       };
       this.update(section);
    }
    else if(target !== undefined) {
        section.targets.push(<SectionTargetModel>{
            target: name,
            hidden: hidden,
            template: template
        });
        this.update(section);
    }
}

As you see above the code checks if the section with the name already exists or not, if not exists creates and pushes the section. If it exists it just pushes the section into the array. After pushing the section into the array, update is called to refresh the section in the layout and show the relevant section content from the page.

pop

Again as the name indicates, pop removes the page’s section content from the array. During page  destroyed(ngOnDestroy) the section is poped from the array. It also changes the section content from the array.

private popTemplate(name: string): void {
    let section: SectionModel = this.sections[name];
    section.targets.pop();
    this.update(section);
}

Similar to push the upgrade function is called in pop to refresh the section and to show the active content.

update

This sets the current template to a section and calls the change detection to refresh the section. This always shows the last section content in the array. It also has the logic to show or hide the section.

private update(section: SectionModel) {

    let targetSection = section.targets[section.targets.length - 1];
    section.currentTemplate = targetSection.template;
    if (targetSection.hidden) {
        section.template.elementRef.nativeElement.parentElement.style.display = "none";
    }
    if (!targetSection.hidden) {
        section.template.elementRef.nativeElement.parentElement.style.display = "block";
    }

    if (!(section.changeDetectorRef as ViewRef).destroyed) {
        section.changeDetectorRef.detectChanges();
    }
}

With these simple three functions, push, pop and update we can get the behaviour similar to that of ASP.NET MVC sections.
Finally here is the MVC type layout, which is a regular component in Angular. AppComponent can also be used for this.

<div fxLayout="row">
    <render-section name="menu" fxFlex="25">
        <b>Menu</b> <br />
        <a routerLink="/home">Home</a> <br />
        <a routerLink="/counter">Counter</a> <br />
        <a routerLink="/fetch-data">Fetch Data</a> <br />
    </render-section>
    <div fxFlex>
        <render-body></render-body>
    </div>
</div>

Finally I created an Angular module to wrap the RenderBody, RenderSection and supporting providers. You can review this code from my GitHub site


Monday, September 11, 2017

Ethereum Solidity Compiler


Ethereum contracts are written in the high level language called Solidity and compiled into bytecode using the Solidity compiler. This bytecode is then uploaded on to the blockchain.

As mentioned in the previous blog, Visual Studio Code and several editors provide integrated environment to compile the code. If you want to manually run the compiler then here are the steps for compiling a smart contract.

Download the compiler from the GitHub release site
Based on your platform download the corresponding bits

Open the command line and run the below command to compile our 0xService or any smart contract
%path%\solc.exe --bin --abi --overwrite -o bin Service.sol

As you see in the above we are passing bin and abi arguments to specify to the compiler to create the bin and abi file. The generated files are created in the bin folder as mentioned by the other bin attribute. The overwrite flag is used to overwrite the previously generated abi and bytecodes.

Tuesday, September 5, 2017

0x Services Objective & Requirements


Below are the objective and requirements of 0x platform

Objective:
Provide a decentralized platform where a client can post a service request and a provider or contractor perform the service in a trustless environment and with escrow payment system.

Requirements:
Client
  • Register and create an account with 0x. 0x creates an user account in Ethereum chain
  • Post a service request in 0x and set its price in Ether or 0x tokens. 0x creates a smart contract on Ethereum chain
  • 0x charges a small amount of fee for creating the contract, this is in addition to the gas required by Ethereum chain. This fee will be paid through 0x tokens
  • Negotiate the price of the service with the provider (out of scope for POC)
  • The contract acts as the escrow account. Fund the contract with the agreed service amount. This funding can be done through Ether or 0x tokens.
  • Once the work is complete authorize payment to the contractor.
  • Settle disputes with help of arbiter

Contractor
  • Register and create an account with 0x. 0x creates an user account in Ethereum chain
  • Apply for a service
  • Perform the requested service (outside of 0x)
  • Request payment for the service
  • Receive payment to the account
  • Raise arbitration if the payment is not received

Arbiter
  • Settle the dispute and authorize the payment from escrow account.
  • 0x acts as the default arbiter. The client can choose his own arbiter.


The below are the out of scope requirements for the current implementation and these can be taken up at a later time.
  • Terms and Conditions of the work which will be checked before the payment is made
  • Termination procedure
  • Intermediate payment or payment schedule where the contractor gets payments based on the payment terms

s

Thursday, August 31, 2017

Visibility Modifiers


Solidity exposes state variables and functions to internal and external worlds using the visibility modifiers. There are four types of visibility modifiers public, internal, private and external.

Functions can have all the four visibility modifiers, the default visibility modifier for functions is public. State variables cannot have external visibility modifier and the default modifier is internal.

Below is the brief description and usage of these visibility modifiers for state variables and functions:

public

Public functions are part of the contract interface and can be either accessible within the contract or via messages. Public state variables are accessible similar to the functions.
contract Service {
    address public arbiter; // 0x is the default arbiter for every contract
    address contractor;

    /// @notice Once the service is completed, client pays to the contractor
    function pay() public {
        contractor.transfer(amountPaid);
        amountPaid = 0;
    }
}

For public State variables Solidity automatically generates a getter function. In the above contract, arbiter is defined as public, Solidity generates a function called arbiter which returns the arbiter address.

internal

The internal functions and state variables can only be accessed within the contract or derived contracts. This is similar to protected variables in C# and other object oriented programming.
In the above code, contractor state variable does not have any visibility modifier. As per default configuration, the contract state variable will be on internal scope.

private

Private functions and state variables, like the name indicates, are accessible within the contract they defined. They are not available in the derived contracts.

external

An external function is similar to public function. In addition from being called internally and via transactions, external functions can be called from other contracts. To call an external function internally it needs to be prefixed with this (this.fund()). External functions can access other functions and state variable directly (without the prefix of this)
/// @notice based on the agreement, client will fund the contract
/// this amount will be payed to contractor at the end
function fund() external onlyClient payable {
    amountPaid += msg.value;
}


As mentioned earlier State variables cannot have external visibility modifier. Only functions can have external visibility modifier.

Tuesday, August 29, 2017

Solidity Constant


Solidity supports to declare constant state variables and functions. A keyword constant is used to define constants in Solidity.

Constant State Variables

State variables can be declared as constant. All constant state variables should be assigned to a constant value at compile time. It can have an expression, but that expression should be evaluated to constant at compile time. Solidity only supports value types and string types as constants. Here is an example of defining constant static variable from Ethereum documentation. Currently in our contract we do not need this constant variables.

contract C {
    uint constant x = 32**22 + 8;
    string constant text = "abc";
    bytes32 constant myHash = keccak256("abc");
}

Constant Functions

Constant function are those functions which does not modify the state of the contract. These functions are used to return values from the contract. In our 0x service contract we defined a constant function which returns the address of the contractor.
/// @notice Get the contractor assigned to the service
/// @return contractor address
function getContractorAddress() public constant returns (address) {
    return contractor;
}