Saturday, December 28, 2019

Cloud Native 12 factor Application


  1. Codebase/Revision Control
  2. Dependencies
  3. Config
  4. Backing Services
  5. CI/CD
  6. Processes
  7. Port Binding
  8. Concurrency
  9. Disposability
  10. Development/Production Parity
  11. Logs
  12. Admin Processes

Sunday, May 21, 2017

Docker Commands

Docker commands

  • Version, Info …

>docker version

>docker info

  • Search

Searches images in docker registry.

docker search <Image Name>

>docker search ubuntu

  • Images

List all the downloaded images

>docker images

>docker ps –a

    -a – show all

    -l – show last

  • Pull

Pulls the image if it is not available locally. It runs automatically by docker run.

>docker pull <Image name>

  • Run

Docker run starts the container by giving the image name a process to run in that container. The container stops when the main process stops. It automatically pulls the image.

>docker run –ti <image>:[<version/latest>] <program to run>

    -ti – terminal interactive

    -d – detach – will run in the background

    -c – command

    -p – port. eg. –p 1234:3456 Expose port 1234 on the inside of the container to the outside of container as port 3456.

          docker run –p <outside-port>:<inside-port>/protocol(tcp/udp)

    -v – volume

         docker run –v <path in host>:<inside the container path>

        >docker run –ti –v /home/docker/example:/shared-folder ubuntu bash

    --name – name of the container

    --memory – maximum allowed memory

    --cpu-shares – relative to other containers

    --cpu-quota – limit it

    --link <Name of container> – for communication between two containers. It automatically assigns a hostname. Link can break when containers restart.

    --net==<Network name>

    --volumes-from <Name of the container that we want to use the volume> – To share data/file between containers.

  • Commit and Tag

>docker commit <id of the container>

Tagging gives images names

>docker tag <id received from commit> <Image/Tag name>

     or

>docker commit <Name of the container> <Image/Tag name>

  • Build

Creates an image for the docker file

    >docker build –t <Name of tag> .

The (.) shows the docker file in here. Otherwise need to pass the path of docker file.

  • Push

Upload a tagged image to docker hub

    >docker push <Tag name>

  • Attach

>docker attach <Container name>

  • Exec

>docker exec

Starts another process in an existing container.

  • Logs

Docker logs keep the output of the container.

>docker logs <Container name or ID>

  • Stopping and Removing

>docker kill <Container name/ID>

>docker rm <Container name/ID>

  • Network

>docker network create <Network name>

  • Clean Up

>docker rmi <Image name/Image ID>:<Tag>

  • Login

Login in to docker hub

Monday, February 27, 2017

Modules & Classes in ES6

Modules:
Module help us with encapsulation by exposing from a given file the pieces we want to be access publically. An export statement will be used for that.

export {
     show: someFunc()
}


Then an import statement is used to import that piece:

import { show } from './my-file.js'

Sunday, February 19, 2017

ES6 Features

New features in ES6 are:

  • let, const and Block Scoping,
  • Arrow Functions =>,
  • Default Function Parameters,
  • Rest and Spread,
  • Object Literal Extensions,
  • for…of Loops,
  • Octal and Binary Literals,
  • Template Literals
  • Destructuring

let, const and Block Scoping:

let

let statement allows to declare variables that are limited in scope to the block, statement or expression on which it is used.

Arrow Functions =>

Arrow functions are anonymous functions with shorter syntax than a function.

Arrow function without any arguments.

var geEmployee = () => console.log(‘Employee Name’);

Default Function Parameters:

var getEmployee = function(id = 101){
     console.log(id)
};
getEmployee();

Thanks,
Bimal

Saturday, October 29, 2016

Dockerfile Commands

A list of commands are defined to build Docker image.

  • FROM

The first statement/command in the docker file which tells which image to download and start from.

  • MAINTAINER

Describes the author of the docker file.

MAINTAINER <First name> <Last name> <email address>

  • RUN

Run a command, wait for the result and then saves the result.

RUN echo hello docker

  • ADD

Adds local files, contents of a tar archives and works with urls.

  • ENV

Helps to set environment variables, both during the build and when running the result.

ENV artifactId=com.org.artifactId

  • ENTRYPOINT

Specifies the start of the command to run

  • CMD

Specifies the whole command to run

  • EXPOSE

Maps a port into the container

EXPOSE 8080

  • VOLUME

Defines shared or ephemeral volumes.

VOLUME [“/host/path/” “/container/path/”]

VOLUME [“/shared-data”]

  • WORKDIR

Sets the directory the container starts in. It is similar to use ‘cd’ after start.

WORKDIR /install/

  • USER

Sets which user the container will run as.

USER bimal

USER 1000

Thursday, September 22, 2016

TypeScript

TypeScript is a superset of JavaScript. When TypeScript is compiled, it transpiled to JavaScript.

Features:

  • Static Typing
  • Interfaces
  • Class Properties
  • Access modifiers (Public, Private)

Static Typing:

let name: string
let age: number
let dob: data

Interfaces:

interface IEmp {
     name: string
     age?: number //Optional property
     dob: date
}

let myEmp: IEmp

Class Properties:

class Employee {

name: string
dob: date
constructor (name){
       this.name = name
}
}

Access Modifier:

Class members are public by default in both ES6 and TypeScript.

class Employee {

private name: string
private getSalary() {
     console.log(‘Salary of ’ + this.name + ‘ is $5000.00‘)
}
}

let myEmp = new Employee ()
console.log(myEmp.name) //Compile time error

Thanks,
Bimal

Saturday, November 07, 2015

Custom Matchers in Jasmine 2.3

Custom matchers, provided by the behavior-driven development framework Jasmine, is a great feature for testing JavaScript code. Custom Matchers helps to group multiple catch checking which makes the test cases clean and self explanatory.

Let’s look at an example that I tried recently

Here is a Calculator.js file:

   1: var Calculator = function () { };
   2:  
   3: Calculator.prototype.add = function (a, b) {
   4:     return a + b;
   5: };
   6:  
   7: Calculator.prototype.divide = function (a, b) {
   8:     return a / b;
   9: };

One of the test scenarios that I would like to try is to check whether the result of the method is in a particular range. The test method will look like this with existing matchers.



   1: describe('Calculator', function () {
   2:     var calc;
   3:  
   4:     beforeEach(function () {
   5:         calc = new Calculator();       
   6:     });
   7:  
   8:     it('should be able to add 1 and 1', function () {
   9:         expect(calc.add(1, 1)).toBe(2);
  10:     });
  11:  
  12:     it('should be able to divide 6 by 2', function () {
  13:         expect(calc.divide(6, 2)).toBe(3);
  14:     })
  15:  
  16:     it('should be able to divide a rational number', function () {
  17:         expect(calc.divide(1, 3)).toBeLessThan(0.34);
  18:         expect(calc.divide(1, 3)).toBeGreaterThan(0.3);        
  19:     })
  20: });

But you can replace the existing matchers with a custom matcher like this.



   1: describe('Calculator', function () {
   2:     var calc;
   3:  
   4:     beforeEach(function () {
   5:         calc = new Calculator();
   6:  
   7:         jasmine.addMatchers({
   8:             toBeBetween: function (util, customEqualityTesters) {
   9:                 return {
  10:                     compare: function (actual, a, b) {
  11:                         var result = {};
  12:                         result.pass = actual >= a && actual <= b;
  13:                         return result;
  14:                     }
  15:                 }
  16:             }
  17:         });
  18:     });
  19:  
  20:     it('should be able to add 1 and 1', function () {
  21:         expect(calc.add(1, 1)).toBe(2);
  22:     });
  23:  
  24:     it('should be able to divide 6 by 2', function () {
  25:         expect(calc.divide(6, 2)).toBe(3);
  26:     })
  27:  
  28:     it('should be able to divide a rational number', function () {
  29:         expect(calc.divide(1, 3)).toBeBetween(0.3, 0.34);
  30:     })
  31: });

You can reuse custom matchers to make the test cases clear and more simple.


What are some scenarios that you use custom matchers?

Monday, May 11, 2015

JavaScript Data Binding Frameworks

Data binding is the process that establishes a connection between the application UI and business logic. It synchronize the elements of the application with different sources of data.
Over the last few years several JavaScript libraries have been released to handle the process of binding data to HTML controls which includes:
  • AngularJS
  • Backbone.js
  • Derby
  • Ember
  • JsViews
  • JQXB Expression Binder
  • Knock
  • Meteor
  • Simpli5
  • WinJS

Thanks,
Bimal


Thursday, January 15, 2015

Basic git operations

Git is a version control system and GitHub is a web-page on which we can publish our Git repositories and collaborate with other people.

The basic commands used are:

To initialize a project in local, go to the project directory and use the following command which will create a .git folder.

   1: >git init <project name>

To check the status of the repository use the status command.


   1: >git status

To track the files created or modified locally, add command should be used.


   1: >git add *

or



   1: >git add *.js


or



   1: >git add <file name>

To attach git repo to local workspace


   1: >git remote add origin <git url>
To commit changes to head


   1: >git commit –m “Commit my changes”
To push the changes to master branch in server


   1: >git push -u origin master
To pull an existing repo to the local


   1: >git pull


Thanks.
Bimal

Friday, January 09, 2015

RESTful Framework for Java

  • Apache CXF
  • Apache Tuscany
  • Apache Wink
  • Cuubez framework
  • Jersey
  • RESTeasy
  • Restfulie
  • Restlet

Monday, December 29, 2014

Basic Angular Application–Step by Step




Angular JS is a JavaScript framework from Google which helps to build structured, testable Single Page Applications(SPA).
Application Requirement
  1. Add a <script> tag which point to angular.js
  2. Add an ng-app attribute(it is a directive  and ng is short form of angular)
Step by Step
To build a basic Angular JS application, follow the steps shown below
  1. Create a html file or a project with a html file in your favorite IDE. I am using WebStorm 9.0.2 trial version and named the project as BasicAngular as shown below.

    image
  2. Add angular.js framework Angular JS framework can be pointing to a local copy of the angular.js file or from a CDN (content delivery network). The screenshot below shows the Google CDN URL.
    image
  3. Add ng-app attribute Include ng-app directive to auto bootstrap the angular application.
    image
  4. Run or open in a browser The expression 12 * 34 is included inside {{ }} will be evaluated and resulting html will be inserted into the div tag as shown below
    image
Thanks,
Bimal

Wednesday, October 22, 2014

Java Frameworks for RESTful Web Services



API Provider
Cuubez

CXF Apache
Dropwizard Yammer
Jersey Oracle
RESTEasy JBoss
Restlet

Tuscany Apache
Wink Apache
Restfulie Caelum

Tuesday, August 26, 2014

Java 7 Programming Language features

Java 7 programming language includes a few new language features which includes
  • Binary Literals
  • Strings in Switch Statements
  • Automatic resource management with try-with-resources Statement
  • Catching Multiple Exception Types and Re-throwing Exceptions with Improved Type Checking
  • Underscores in Numeric Literals
  • Type Inference for Generic Instance Creation or Diamond Operator

Saturday, March 15, 2014

JavaScript Promise


Introduction
A Promise is an object that represents a one-time event, typically the outcome of an async task. Basically it starts with a pending state and eventually change to resolve or reject.
It provides an unified or standard way to handle async tasks and it decouples the logic of processing the result from the object which invokes the task.
JS Promise libraries
  • Promise
  • Q
  • When
  • rsvp.js
  • Vow
Thanks,
Bimal

Tuesday, March 11, 2014

JavaScript MVC Frameworks

JavaScript MVC Frameworks
  • Agility.js
  • AngularJS
  • Backbone.js
  • CanJS
  • Ember.js
  • Epitome
  • ExtJS
  • Kendo UI
  • Knockout
  • Maria
  • PlastronJS
  • rAppid.js
  • Sammy.js
  • Serenade.js
  • soma.js
  • Spine.js
  • SproutCore
  • Stapes.js
Thanks,
Bimal

Monday, October 08, 2012

C#, CLR, .Net Framework and VS Versions




There are various versions of C# language, CLR and .Net framework.
C# Version CLR Version .Net Framework Version Visual Studio Version
1.0 1.0 1.0 Visual Studio.Net
1.1 1.1 1.1 (SP 1) Visual Studio.Net 2003
2.0 2.0 2.0 (SP 2) Visual Studio 2005
3.0 (SP 2)
3.0 2.0 3.5 (SP 1) Visual Studio 2008
4.0 4.0 4.0 Visual Studio 2010
5.0 4.5 4.5 Visual Studio 2012

Thanks,
Bimal

Sunday, February 26, 2012

Dependency Injection Containers for .Net



Dependency Injection (DI) Containers for .Net:

  • Unity Framework
  • Ninject
  • Spring.NET
  • Castle Windsor
  • StructureMap
  • Autofac
  • Munq.DI
Thanks,
Bimal

Saturday, April 16, 2011

Printing in Silverlight 4.0 with MVVM


Microsoft Silverlight 4.0 supports Printing with the help of Printing API. The article will basically deals with step by step approach in achieving Print functionality with MVVM pattern.
  1. Start Visual Web Developer 2010 Express and create a Silverlight Application

    image

  2. Select Silverlight 4 from Silverlight version dropdown and click Ok

    image

  3. Create three folders, Model, ViewModel and Command. 

    image

  4. Right click on Model folder and create a class for model. Let name it as Employee.

    image

    and add the following properties

       1: public class Employee
       2: {
       3:     /// <summary>
       4:     /// Gets or sets Employee Id.
       5:     /// </summary>
       6:     public int Id { get; set; }
       7:  
       8:     /// <summary>
       9:     /// Gets or sets Employee's First name.
      10:     /// </summary>
      11:     public String FirstName { get; set; }
      12:  
      13:     /// <summary>
      14:     /// Gets or sets Employee's Last name.
      15:     /// </summary>
      16:     public String LastName { get; set; }
      17:  
      18:     /// <summary>
      19:     /// Gets or sets Location of Employee.
      20:     /// </summary>
      21:     public String Location { get; set; }
      22:  
      23:     /// <summary>
      24:     /// Gets Employee's full name.
      25:     /// </summary>
      26:     public String FullName { get { return FirstName + " " + LastName; } }
      27:  
      28:     /// <summary>
      29:     /// Returns a collection of dummy details
      30:     /// </summary>
      31:     /// <returns>Collection of Employee</returns>
      32:     public static Collection<Employee> GetEmployeeDetails()
      33:     {
      34:         Collection<Employee> empList = new Collection<Employee>() 
      35:         { 
      36:             new Employee() { Id=001, FirstName = "Amanda", 
      37:                 LastName = "Hartshorn", Location="United States" },
      38:             new Employee() { Id=002, FirstName = "Binu", 
      39:                 LastName = "Babu", Location="India" },
      40:             new Employee() { Id=003, FirstName = "Nihas", 
      41:                 LastName = "Alangaden", Location="India" },
      42:             new Employee() { Id=004, FirstName = "Parvathi", 
      43:                 LastName = "Mahesh", Location="United States" },
      44:             new Employee() { Id=005, FirstName = "Tony", 
      45:                 LastName = "Xavier", Location="India" }
      46:         };
      47:  
      48:         return empList;
      49:     }
      50: }

  5. Right click on ViewModel folder in the Silverlight project create a BaseViewModel class

    image


    and implement INotifyPropertyChanged interface as shown below




       1: public class BaseViewModel : INotifyPropertyChanged
       2: {
       3:     /// <summary>
       4:     /// This event occurs when a property value changes
       5:     /// </summary>
       6:     public event PropertyChangedEventHandler PropertyChanged;
       7:  
       8:     protected void OnPropertyChanged(string name)
       9:     {
      10:         if (PropertyChanged!= null)
      11:         {
      12:             PropertyChanged(this, new PropertyChangedEventArgs(name));
      13:         }
      14:     }
      15: }



  6. Create MainPageViewModel class inside ViewModel folder and Command class inside Command folder.

  7. Implement ICommand interface in Command class as shown below
     


       1: public class Command : ICommand
       2: {
       3:     private bool m_canExecuteCache;
       4:     private Action<object> m_executeAction;
       5:     private Func<object, bool> m_canExecute;
       6:  
       7:     /// <summary>
       8:     /// This event occurs when changes occur that 
       9:     /// affect whether the command should execute.
      10:     /// </summary>
      11:     public event EventHandler CanExecuteChanged;
      12:  
      13:     /// <summary>
      14:     /// Initializes a new instance of <see cref="Command"/> class.
      15:     /// </summary>
      16:     /// <param name="canExecute">
      17:     /// Encapsulates a method that has one 
      18:     /// parameter and returns a value of the type bool.
      19:     /// </param>
      20:     /// <param name="executeAction">
      21:     /// Encapsulates a method that takes a single 
      22:     /// parameter and does not return a value.
      23:     /// </param>
      24:     public Command(Func<object, bool> canExecute, Action<object> executeAction)
      25:     {
      26:         m_canExecute = canExecute;
      27:         m_executeAction = executeAction;
      28:     }
      29:  
      30:     /// <summary>
      31:     /// This method determines whether the 
      32:     /// command can execute in its current state.
      33:     /// </summary>
      34:     /// <param name="parameter">
      35:     /// Data used by the command. If the command does not 
      36:     /// require data to be passed, this object can be set to null.
      37:     /// </param>
      38:     /// <returns>
      39:     /// true if this command can be executed; otherwise, false.
      40:     /// </returns>
      41:     public bool CanExecute(object parameter)
      42:     {
      43:         bool enable = m_canExecute(parameter);
      44:  
      45:         if (m_canExecuteCache != enable)
      46:         {
      47:             m_canExecuteCache = enable;
      48:  
      49:             if (CanExecuteChanged != null)
      50:             {
      51:                 CanExecuteChanged(this, new EventArgs());
      52:             }
      53:         }
      54:  
      55:         return m_canExecuteCache;
      56:     }
      57:  
      58:     /// <summary>
      59:     /// This method will be called when the command is invoked.
      60:     /// </summary>
      61:     /// <param name="parameter">
      62:     /// Data used by the command. If the command does not 
      63:     /// require data to be passed, this object can be set to null.
      64:     /// </param>
      65:     public void Execute(object parameter)
      66:     {
      67:         m_executeAction(parameter);
      68:     }
      69: }

  8. Create a property for Print Command and another one for Employees collection in the view model. Create an instance of Command and pass the methods which handles can execute and print. 


       1: public class MainPageViewModel : BaseViewModel
       2: {
       3:     /// <summary>
       4:     /// Initializes a new instance of <see cref="MainPageViewModel"/> class.
       5:     /// </summary>
       6:     public MainPageViewModel()
       7:     {
       8:         //Gets dummy data from model
       9:         Employees = Employee.GetEmployeeDetails();
      10:         //Setting the Command to the property
      11:         PrintCommand = new Command.Command(CanPrint, Print);
      12:     }
      13:  
      14:     /// <summary>
      15:     /// Gets or sets a collection of Employee.
      16:     /// </summary>
      17:     public Collection<Employee> Employees { get; private set; }
      18:  
      19:     /// <summary>
      20:     /// Gets or sets the Print Command.
      21:     /// </summary>
      22:     public ICommand PrintCommand { get; private set; }
      23:  
      24:     #region Private Methods
      25:  
      26:     /// <summary>
      27:     /// Method which is called when the command is invoked.
      28:     /// </summary>
      29:     /// <param name="obj">Data used for Printing</param>
      30:     private void Print(object obj)
      31:     {
      32:         //Creates a new instance of the System.Windows.Printing.PrintDocument class.
      33:         PrintDocument document = new PrintDocument();
      34:  
      35:         //Event handler which fires when each page is printing.
      36:         document.PrintPage += (s, arg) => { arg.PageVisual = obj as UIElement; };
      37:  
      38:         // Starts the printing process for the specified 
      39:         // document by opening the print dialog box.
      40:         document.Print("Print");
      41:     }
      42:  
      43:     /// <summary>
      44:     /// Method which determines whether the 
      45:     /// command can execute in its current state.
      46:     /// </summary>
      47:     /// <param name="obj">Data used for Printing</param>
      48:     /// <returns>true if the command can be executed; otherwise, false</returns>
      49:     private bool CanPrint(object obj)
      50:     {
      51:         return true;
      52:     }
      53:  
      54:     #endregion
      55: }

  9. Build the Solution and import ViewModel namespace in MainPage.xaml as shown below


       1: xmlns:vm="clr-namespace:PrintApplication.ViewModel"

    Set the DataContext of the MainPage usercontrol.




       1: <UserControl.DataContext>
       2:     <vm:MainPageViewModel />
       3: </UserControl.DataContext>

  10. Add reference to System.Windows.Controls.Data.dll to the Silverlight project and

    image


    import System.Windows.Controls.Data as shown below for adding DataGrid Control to list the Employee details.


       1:  xmlns:data="clr-namespace:System.Windows.Controls; assembly=System.Windows.Controls.Data"

  11. Add a TextBlock for displaying Title, DataGrid for displaying the Employees Collection and a button for handling Print action in MainPage.xaml.



       1: <UserControl x:Class="PrintApplication.MainPage"
       2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       4:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
       5:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       6:     xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
       7:     xmlns:vm="clr-namespace:PrintApplication.ViewModel" mc:Ignorable="d">
       8:     <UserControl.DataContext>
       9:         <vm:MainPageViewModel />
      10:     </UserControl.DataContext>
      11:     <Grid x:Name="LayoutRoot" Background="White" Height="270">
      12:         <Grid.RowDefinitions>
      13:             <RowDefinition Height="50" />
      14:             <RowDefinition />
      15:             <RowDefinition Height="50" />
      16:         </Grid.RowDefinitions>
      17:         <TextBlock x:Name="trbBlock" Text="Printing API Sample" FontSize="18" 
      18:                    Margin="3,10,3,14" HorizontalAlignment="Center" Height="26" />
      19:         <StackPanel x:Name="DisplayPanel" Grid.Row="1" HorizontalAlignment="Center">
      20:             <data:DataGrid ItemsSource="{Binding Path=Employees}" 
      21:                            AutoGenerateColumns="False">
      22:                 <data:DataGrid.Columns>
      23:                     <data:DataGridTextColumn Header="Id" Width="50"
      24:                                              Binding="{Binding Id}" />
      25:                     <data:DataGridTextColumn Header="First Name" Width="100"
      26:                                              Binding="{Binding FirstName}" />
      27:                     <data:DataGridTextColumn Header="Last Name" Width="100"
      28:                                              Binding="{Binding LastName}" />
      29:                     <data:DataGridTextColumn Header="Location" Width="100"
      30:                                              Binding="{Binding Location}" />
      31:                 </data:DataGrid.Columns>
      32:             </data:DataGrid>
      33:         </StackPanel>
      34:         <Button Content="Print" Grid.Row="2" Width="100" Height="30" 
      35:                 Command="{Binding PrintCommand}" 
      36:                 CommandParameter="{Binding ElementName=DisplayPanel}" />
      37:     </Grid>
      38: </UserControl>



  12. Run the solution and click the Print button to get the Print dialog box.  

    image


Thanks
Bimal