Saturday, December 29, 2018

.NET - Code First Approach in Entity Framework


Objective:

The objective of this tutorial is to explain the code first approach that Microsoft’s Entity Framework provides.  We’ll go step by step to explore the code first approach via which we can access database and data using entity framework in our application.

Pre-requisites:
Ensure that the following softwares are already installed:
1) Visual Studio
2) .NET Framework (version 4.6 or higher)
3) SQL Server
4) SQL Server Management Studio

Entity Framework:
  • Microsoft Entity Framework is an ORM (Object-relational mapping). 
  • Being an ORM,  Entity Framework is a data access framework provided by Microsoft that helps to establish a relation between objects and data structure in the application. 
  • It is built over traditional ADO.NET and acts as a wrapper over ADO.NET and is an enhancement over ADO.NET that provides the data access in a more automated way, thereby, reducing a developer’s effort to struggle with connections, data readers, or datasets.
  • It is an abstraction over all those and is more powerful with the offerings it makes. A developer can have more control over what data he needs, in which form and how much.
  • A developer having no database development background can leverage Entity framework along with LINQ capabilities to write an optimized query to perform DB operations

Entity Framework Approaches:

It is very common to know the three approaches that Microsoft Entity Framework provides. The three approaches are as follows:

Model First,
Database First, and
Code First

Model First:
  • The Model-First approach says that we have a model with all kinds of entities and relations/associations using which we can generate a database that will eventually have entities and properties converted into database tables and the columns and associations and relations would be converted into foreign keys respectively
Database First:
  • The Database-First approach says that we already have an existing database and we need to access that database in our application. 
  • We can create an entity data model along with its relationship directly from the database with just a few clicks and start accessing the database from our code. 
  • All the entities, i.e., classes, would be generated by EF that could be used in the application's data access layer to participate in DB operation queries.
Code First:
  • The Code-First approach is the recommended approach with EF, especially when you are starting the development of an application from scratch. 
  • You can define the POCO classes in advance and their relationships and envision how your database structure and data model may look like by just defining the structure in the code. 
  • Entity Framework, at last, will take all the responsibility to generate a database for you for your POCO classes and for the data model and will take care of transactions, history, and migrations.
In this tutorial, we are going to look at the Code First approach.

Code First Example:

1. Open Visual Studio, click File --> New --> Project

2.  Select Console App (.NET Framework) and enter name EF_CF (or some name of your preference) and hit OK button. 


3. This will give you Program.cs and a Main() method inside that.

4. We’ll create our model classes now, i.e., POCO (Plain Old CLR Object) classes. Let’s say we have to create an application where there would be database operations for an employee and an employee would be allocated to some department. So, A department can have multiple employees and an employee will have only one department. So, we’ll create the first two entities, Employee, and Add a new class to the project named Employee and add two simple properties to it i.e. EmployeeId and EmployeeName.





5. Similarly, add a new class named Department and add properties DepartmentId, DepartmentName, and DepartmentDescription as shown below.


6. Since an employee belongs to one department, each employee would have a related department to it, so add a new property named DepartmentId to the Employee class.


7. Now, it is time to add EntityFramework to our project. Open the Package Manager console, select the default project (EF_CF) as your current console application, and install the Entity Framework using the following command:
 Install-Package EntityFramework



8. Add a new class named CodeFirstContext to the project which inherits from DbContext class of namespace System.Data.Entity as shown in the following image. Now add two DbSet properties named Employees and Departments as shown in the following.


Both DbContext and DbSet are required in creating and dealing with database operations, and make us far abstracted, providing ease of use to us.

When we are working with DbContext, we are in real working with entity sets. DbSet represents a typed entity set that is used to perform create, read, update, and delete operations. We are not creating DbSet objects and using them independently. DbSet can be only used with DbContext.

9. Let’s try to make our implementation a more abstract and instead of accessing dbContext directly from the controller, let’s abstract it in a class named DataAccessHelper. This class will act as a helper class for all our database operations. So, add a new class named DataAccessHelper to the project.

10. Create a read-only instance of the DB context class and add few methods like FetchEmployees() to get employees details, FetchDepartments() to fetch department details. One method each to add employee and add a department. You can add more methods to your will like the update and delete operations. For now, we’ll stick to these four methods.


The code may look like as shown below,

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace EF_CF  
  8. {  
  9.     public class DataAccessHelper  
  10.     {  
  11.         readonly CodeFirstContext _dbContext = new CodeFirstContext();  
  12.   
  13.         public List<Employee> FetchEmployees()  
  14.         {  
  15.             return _dbContext.Employees.ToList();  
  16.         }  
  17.   
  18.         public List<Department> FetchDepartments()  
  19.         {  
  20.             return _dbContext.Departments.ToList();  
  21.         }  
  22.   
  23.         public int AddEmployee(Employee employee)  
  24.         {  
  25.             _dbContext.Employees.Add(employee);  
  26.             _dbContext.SaveChanges();  
  27.             return employee.EmployeeId;  
  28.         }  
  29.   
  30.         public int AddDepartment(Department department)  
  31.         {  
  32.             _dbContext.Departments.Add(department);  
  33.             _dbContext.SaveChanges();  
  34.             return department.DepartmentId;  
  35.         }  
  36.     }  
  37. }  

11. Let’s add the concept of navigation property now. Navigation properties are those properties of the class through which one can access related entities via the Entity Framework while fetching data. So while fetching Employee data we may need to fetch the details of its related Departments and while fetching Department data we may need to fetch the details of associated employees with that. Navigation properties are added as virtual properties in the entity. So, in Employee class, add a property for Departments returning a single Department entity and make it virtual. Similarly, in Department class, add a property named Employees returning the collection of Employee entity and make that virtual too.


Following is the code for the Employee and the Department model,

Employee.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace EF_CF  
  8. {  
  9.     public class Employee  
  10.     {  
  11.         public int EmployeeId { get; set; }  
  12.         public string EmployeeName { get; set; }  
  13.         public int DepartmentId { get; set; }  
  14.   
  15.         public virtual Department Departments { get; set; }  
  16.     }  
  17. }  

Department.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Security.Policy;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace EF_CF  
  9. {  
  10.     public class Department  
  11.     {  
  12.         public int DepartmentId { get; set; }  
  13.         public string DepartmentName { get; set; }  
  14.         public string DepartmentDescription { get; set; }  
  15.   
  16.         public virtual ICollection<Employee> Employees { get; set; }  
  17.     }  
  18.  

12. Let’s write some code to perform database operations with our code. So, in the Main() method of Program.cs class add the following sample test code,

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace EF_CF  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             Department department = new Department  
  14.             {  
  15.                 DepartmentName = "Technology",  
  16.                 Employees = new List<Employee>  
  17.                 {  
  18.                     new Employee() {EmployeeName = "Jack"},  
  19.                     new Employee() {EmployeeName = "Kim"},  
  20.                     new Employee() {EmployeeName = "Shen"}  
  21.                 }  
  22.             };  
  23.             DataAccessHelper dbHelper = new DataAccessHelper();  
  24.             dbHelper.AddDepartment(department);  
  25.             var addedDepartment = dbHelper.FetchDepartments().FirstOrDefault();  
  26.             if (addedDepartment != null)  
  27.             {  
  28.                 Console.WriteLine("Department Name is: " + addedDepartment.DepartmentName + Environment.NewLine);  
  29.                 Console.WriteLine("Department Employees are: " + Environment.NewLine);  
  30.   
  31.                 foreach (var addedDepartmentEmployee in addedDepartment.Employees)  
  32.                 {  
  33.                     Console.WriteLine(addedDepartmentEmployee.EmployeeName + Environment.NewLine);  
  34.                 }  
  35.   
  36.                 Console.ReadLine();  
  37.             }  
  38.         }  
  39.     }  
  40. }  
In the above code of Main() method, we are trying to create an object of Department class and add a list of Employees to the Employees property of that class. Create an instance of the dbHelper class and invoke the method AddDepartment, passing the department entity object to that method to add the new department.

Just after adding the department, we are fetching the newly added department and just to make sure that the department and its related employees got added successfully to the database. So, we’ll fetch the departments and on the console, print the department name and its related employees. But how will all this be done, we do not have a database yet.

13. Not to worry, let’s see how we can make sure that we get the DB created from our code. First like we saw earlier, our context class name should be the same as our connection string name or vice versa. So, add a connection string having the same name as DB context class in the App.config file as shown below.


<connectionStrings>
    <add name="CodeFirstContext" 
         connectionString="data source=.\SQLEXPRESS;initial catalog=codefirstdb;integrated security=SSPI"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>


Job done! Entity Framework will take care of the rest of the pending work of creating a database. We just run the application and now, DB context class is first used to perform a DB operation, we get our database created.

14. Run the application (with F5 command). Now go to the database server and see we got the database created with the same name that we supplied in the connection string. We have Departments and Employees table and a table named __MigrationHistory to track the history of code first migrations performed on this database.


We see that we also got one Department added in the database having the name ”Technology” that we used in the code.

And, got our employee's table filled with three rows having three employees with department id 1 i.e. the id of the newly added department. And so our code first approach worked as well.


When console window appears we see the details of the department and added employees in that window, so our fetch operations also work fine.


That's all I want to cover. Hope this tutorial was useful.

Monday, July 16, 2018

Kubernetes Overview


What is Kubernetes?

Kubernetes is an open-source platform for automating deployment, scaling, and operations of application containers across clusters of hosts, providing container-centric infrastructure.

With Kubernetes, you are able to quickly and efficiently respond to customer demand:

Deploy your applications quickly and predictably.
Scale your applications on the fly.
Seamlessly roll out new features.
Optimize use of your hardware by using only the resources you need.

Our goal is to foster an ecosystem of components and tools that relieve the burden of running applications in public and private clouds.

Kubernetes is:
portable: public, private, hybrid, multi-cloud
extensible: modular, pluggable, hookable, composable
self-healing: auto-placement, auto-restart, auto-replication, auto-scaling

The Kubernetes project was started by Google in 2014. Kubernetes builds upon a decade and a half of experience that Google has with running production workloads at scale, combined with best-of-breed ideas and practices from the community.

Features of Kubernetes:

Following are some of the important features of Kubernetes.

  • co-locating helper processes, facilitating composite applications and preserving the one-application-per-container model,
  • mounting storage systems,
  • distributing secrets,
  • application health checking,
  • replicating application instances,
  • horizontal auto-scaling,
  • naming and discovery,
  • load balancing,
  • rolling updates,
  • resource monitoring,
  • log access and ingestion,
  • support for introspection and debugging, and
  • identity and authorization.

Kubernetes Architecture:


1. Kubernetes Clients will get inputs from clients in the form of API, UI and CLI. 

2. Kubernetes Master is responsible for scheduling, provisioning, controlling and exposing the API to the clients (API, UI or CLI). Kubernetes understands declerative artifacts in the form of YAML and these YAML definitions are submitted to master. Based on the YAML configuration proivided, the Master will create pods in Nodes 

3. Kubernetes Nodes are the worker nodes, where the action is happening and they will provide the feedback to Master.

4. Registry is place where the Docker images are centrally stored. It will be public registry like Docker Hub or private registry running in local data center.

Kubernetes Master:


API Server is responsible for exposing various API's for various operations. Kubectl is a go-language binary talks to API Server. Kubernetes Dashboard also consumes API Server. So API Server forms the frontend or Gatekeeper for the entire cluster, where everything should pass through APi Server. 

Scheduler is one of the key components of Kubernetes master. It is a service in master responsible for distributing the workload. It is responsible for tracking utilization of working load on cluster nodes and then placing the workload on which resources are available and accept the workload. In other words, this is the mechanism responsible for allocating pods to available nodes. The scheduler is responsible for workload utilization and allocating pod to new node.

Controller Manager is responsible for most of the collectors that regulates the state of cluster and performs a task. In general, it can be considered as a daemon which runs in non-terminating loop and is responsible for collecting and sending information to API server. It works toward getting the shared state of cluster and then make changes to bring the current status of the server to the desired state. The key controllers are replication controller, endpoint controller, namespace controller, and service account controller. The controller manager runs different kind of controllers to handle nodes, endpoints, etc.

etcd stores the configuration information which can be used by each of the nodes in the cluster. It is a high availability key value store that can be distributed among multiple nodes. It is accessible only by Kubernetes API server as it may have some sensitive information. It is a distributed key value Store which is accessible to all.


Kubernetes Node:


Docker will help in running the encapsulated application containers in a relatively isolated but lightweight operating environment.

Kubelet is a small service in each node responsible for relaying information to and from control plane service. It interacts with etcd store to read configuration details and right values. This communicates with the master component to receive commands and work. The kubelet process then assumes responsibility for maintaining the state of work and the node server. It manages network rules, port forwarding, etc.

Kubernetes Proxy Service (kube-proxy) is a proxy service which runs on each node and helps in making services available to the external host. It helps in forwarding the request to correct containers and is capable of performing primitive load balancing. It makes sure that the networking environment is predictable and accessible and at the same time it is isolated as well. It manages pods on node, volumes, secrets, creating new containers’ health checkup, etc.

Supervisord: Both Docker and Kublet are combined to Supervisord layer, which is basically a process manager where you can run multiple processes inside one parent process. It ensures that both Docker and Kublet are running all the time 

Fluentd is responsible to managing the logs and talking to central logging mechanism configured. 

Pod is a unit of deployment, it is possible to have multiple pods and they can be of different configuration (that's why the Pods are depicted in different size and colours in the diagram). Pods could be homogeneous (i.e multiple version of same pod) Or heterogeneous (i.e completly different version and belong to different application) 

Addons are the optional components that you can install on core Kubernetes, which will help you to manage the Kubernetes setup well. Most popular Addon's are DNS and UI. 


Kubernetes Terminology:
Labels:
Labels are key-value pairs which are attached to pods, replication controller and services. They are used as identifying attributes for objects such as pods and replication controller. They can be added to an object at creation time and can be added or modified at the run time.

Selectors:
Labels do not provide uniqueness. In general, we can say many objects can carry the same labels. Labels selector are core grouping primitive in Kubernetes. They are used by the users to select a set of objects. Kubernetes API currently supports two type of selectors −

  • Equality-based selectors
  • Set-based selectors

Namespace:
Namespace provides an additional qualification to a resource name. This is helpful when multiple teams are using the same cluster and there is a potential of name collision. It can be as a virtual wall between multiple clusters.

Service:
A service can be defined as a logical set of pods. It can be defined as an abstraction on the top of the pod which provides a single IP address and DNS name by which pods can be accessed. With Service, it is very easy to manage load balancing configuration. It helps pods to scale very easily. A service is a REST object in Kubernetes whose definition can be posted to Kubernetes apiServer on the Kubernetes master to create a new instance.

Replica Set:
Replica Set ensures how many replica of pod should be running. It can be considered as a replacement of replication controller. The key difference between the replica set and the replication controller is, the replication controller only supports equality-based selector whereas the replica set supports set-based selector.

Deployments:
Deployments are upgraded and higher version of replication controller. They manage the deployment of replica sets which is also an upgraded version of the replication controller. They have the capability to update the replica set and are also capable of rolling back to the previous version.

Volumes:
In Kubernetes, a volume can be thought of as a directory which is accessible to the containers in a pod. We have different types of volumes in Kubernetes and the type defines how the volume is created and its content. The volumes that are created through Kubernetes is not limited to any container. It supports any or all the containers deployed inside the pod of Kubernetes.  Supports different types like emptyDir, hostPath, gcePersistentDisk, awsElasticBlockStore, nfs, iscsi, flocker, glusterfs, rbd, cephfs, gitRepo, secret, persistentVolumneClaim, downwardAPI, azureDiskVolume

Secrets:
Secrets can be defined as Kubernetes objects used to store sensitive data such as user name and passwords with encryption. There are multiple ways of creating secrets in Kubernetes.

  1. Creating from txt files.
  2. Creating from yaml file.

Network Policy:
Network Policy defines how the pods in the same namespace will communicate with each other and the network endpoint.


Friday, June 15, 2018

Developer tutorial for creating a IBM Blockchain Platform: Develop solution



This tutorial will walk you through building a IBM Blockchain Platform: Develop blockchain solution from scratch. In the space of a few hours you will be able to go from an idea for a disruptive blockchain innovation, to executing transactions against a real Hyperledger Fabric blockchain network and generating/running a sample Angular 4 application that interacts with a blockchain network.

This tutorial gives an overview of the techniques and resources available to apply to your own use case.

Note: This tutorial was written against the latest IBM Blockchain Platform: Develop build on Ubuntu Linux running with Hyperledger Fabric where referenced below and also tested for a Mac environment.

Prerequisites
Before beginning this tutorial:

Step One: Creating a business network structure

The key concept for IBM Blockchain Platform: Develop is the business network definition (BND). It defines the data model, transaction logic and access control rules for your blockchain solution. To create a BND, we need to create a suitable project structure on disk.

The easiest way to get started is to use the Yeoman generator to create a skeleton business network. This will create a directory containing all of the components of a business network.

1. Create a skeleton business network using Yeoman. This command will require a business network name, description, author name, author email address, license selection and namespace.
yo hyperledger-composer:businessnetwork
2. Enter tutorial-network for the network name, and desired information for description, author name, and author email.
3. Select Apache-2.0 as the license.
4. Select org.example.mynetwork as the namespace.
5. Select No when asked whether to generate an empty network or not.

This will create a folder named tutorial-network in the current directory and you will see the folders and files that created as shown in the above screen shot.

Step Two: Defining a business network

A business network is made up of assets, participants, transactions, access control rules, and optionally events and queries. In the skeleton business network created in the previous steps, there is a model (.cto) file which will contain the class definitions for all assets, participants, and transactions in the business network. The skeleton business network also contains an access control (permissions.acl) document with basic access control rules, a script (logic.js) file containing transaction processor functions, and a package.json file containing business network metadata.

Modelling assets, participants, and transactions
The first document to update is the model (.cto) file. This file is written using the IBM Blockchain Platform: Develop Modelling Language. The model file contains the definitions of each class of asset, transaction, participant, and event. It implicitly extends the IBM Blockchain Platform: Develop System Model described in the modelling language documentation.

1. Go to the folder tutorial-network/model
2. Open the org.example.mynetwork.cto model file.
3. Replace the contents with the following:
/**
 * My commodity trading network
 */
namespace org.example.mynetwork
asset Commodity identified by tradingSymbol {
    o String tradingSymbol
    o String description
    o String mainExchange
    o Double quantity
    --> Trader owner
}
participant Trader identified by tradeId {
    o String tradeId
    o String firstName
    o String lastName
}
transaction Trade {
    --> Commodity commodity
    --> Trader newOwner
}
4. Save your changes to org.example.mynetwork.cto.

Adding JavaScript transaction logic
In the model file, a Trade transaction was defined, specifying a relationship to an asset, and a participant. The transaction processor function file contains the JavaScript logic to execute the transactions defined in the model file.

The Trade transaction is intended to simply accept the identifier of the Commodity asset which is being traded, and the identifier of the Trader participant to set as the new owner.

1. Go to the folder tutorial-network/lib/
2. Open the logic.js script file.
3. Replace the contents with the following:
/**
 * Track the trade of a commodity from one trader to another
 * @param {org.example.mynetwork.Trade} trade - the trade to be processed
 * @transaction
 */
async function tradeCommodity(trade) {
    trade.commodity.owner = trade.newOwner;
    let assetRegistry = await getAssetRegistry('org.example.mynetwork.Commodity');
    await assetRegistry.update(trade.commodity);
}
4. Save your changes to logic.js.

Adding access control
1. Replace the following access control rules in the file permissions.acl :
/**
 * Access control rules for tutorial-network
 */
rule Default {
    description: "Allow all participants access to all resources"
    participant: "ANY"
    operation: ALL
    resource: "org.example.mynetwork.*"
    action: ALLOW
}

rule SystemACL {
  description:  "System ACL to permit all access"
  participant: "ANY"
  operation: ALL
  resource: "org.hyperledger.composer.system.**"
  action: ALLOW
}
2. Save your changes to permissions.acl.

Step Three: Generate a business network archive
Now that the business network has been defined, it must be packaged into a deployable business network archive (.bna) file.

1. Using the command line, navigate to the tutorial-network directory.
2. From the tutorial-network directory, run the following command:
composer archive create -t dir -n .

After the command has run, a business network archive file called tutorial-network@0.0.1.bna has been created in the tutorial-network directory.

Step Four: Deploying the business network
After creating the .bna file, the business network can be deployed to the instance of Hyperledger Fabric. Normally, information from the Fabric administrator is required to create a PeerAdmin identity, with privileges to install chaincode to the peer as well as start chaincode on the composerchannel channel. However, as part of the development environment installation, a PeerAdmin identity has been created already.

After the business network has been installed, the network can be started. For best practice, a new identity should be created to administer the business network after deployment. This identity is referred to as a network admin.

Retrieving the correct credentials
A PeerAdmin business network card with the correct credentials is already created as part of development environment installation.

Deploying the business network
Deploying a business network to the Hyperledger Fabric requires the IBM Blockchain Platform: Develop business network to be installed on the peer, then the business network can be started, and a new participant, identity, and associated card must be created to be the network administrator. Finally, the network administrator business network card must be imported for use, and the network can then be pinged to check it is responding.

1. To install the business network, from the tutorial-network directory, run the following command:

composer network install --card PeerAdmin@hlfv1 --archiveFile tutorial-network@0.0.1.bna

The composer network install command requires a PeerAdmin business network card (in this case one has been created and imported in advance), and the the file path of the .bna which defines the business network.

2. To start the business network, run the following command:

composer network start --networkName tutorial-network --networkVersion 0.0.1 --networkAdmin admin --networkAdminEnrollSecret adminpw --card PeerAdmin@hlfv1 --file networkadmin.card

The composer network start command requires a business network card, as well as the name of the admin identity for the business network, the name and version of the business network and the name of the file to be created ready to import as a business network card.

3. To import the network administrator identity as a usable business network card, run the following command:

composer card import --file networkadmin.card

The composer card import command requires the filename specified in composer network start to create a card.

4. To check that the business network has been deployed successfully, run the following command to ping the network:

composer network ping --card admin@tutorial-network

The composer network ping command requires a business network card to identify the network to ping.

Step Five: Generating a REST server
IBM Blockchain Platform: Develop can generate a bespoke REST API based on a business network. For developing a web application, the REST API provides a useful layer of language-neutral abstraction.

1. To create the REST API, navigate to the tutorial-network directory and run the following command:
composer-rest-server
2. Enter admin@tutorial-network as the card name.
3. Select never use namespaces when asked whether to use namespaces in the generated API.
4. Select No when asked whether to secure the generated API.
5. Select Yes when asked whether to enable event publication.
6. Select No when asked whether to enable TLS security.

The generated API is connected to the deployed blockchain and business network.
Note: The REST Server will try to start on Port 3000. In my case, the port 3000 is already in use, so I have to use the following command:

composer-rest-server -c admin@tutorial-network -p 3010

This will default the rest of the parameters.

Step Six: Generating an application
IBM Blockchain Platform: Develop can also generate an Angular 4 application running against the REST API.
1. To create your Angular 4 application, navigate to tutorial-network directory and run the following command:
yo hyperledger-composer:angular
2. Select Yes when asked to connect to running business network.
3. Enter standard package.json questions (project name, description, author name, author email, license)
4. Enter admin@tutorial-network for the business network card.
5. Select Connect to an existing REST API
6. Enter http://localhost for the REST server address.
7. Enter 3000 for server port.
8. Select Namespaces are not used

The Angular generator will then create the scaffolding for the project and install all dependencies. To run the application, navigate to your angular project directory and run npm start . This will fire up an Angular 4 application running against your REST API at http://localhost:4200

IBM Blockchain Platform: Installing the development environment


Follow these instructions to obtain the IBM Blockchain Platform: Develop development tools (primarily used to create Business Networks) and stand up a Hyperledger Fabric (primarily used to run/deploy your Business Networks locally). Note that the Business Networks you create can also be deployed to Hyperledger Fabric runtimes in other environments e.g. on a cloud platform.

To provide flexibility and enable the maximum number of dev, test and deployment scenarios, Blockchain Platform is delivered as a set of components you can install with npm and control from the CLI. These instructions will tell you how to install everything first, then how to control your development environment.

Installing components

Step 1: Install the CLI tools
There are a few useful CLI tools for Blockchain Platform developers. The most important one is composer-cli, which contains all the essential operations, so we'll install that first. Next, we'll also pick up generator-hyperledger-composer, composer-rest-server and Yeoman plus the generator-hyperledger-composer. Those last 3 are not core parts of the development environment, but they'll be useful if you're following the tutorials or developing applications that interact with your Business Network, so we'll get them installed now.

1. Essential CLI tools:

npm install -g composer-cli

2. Utility for running a REST Server on your machine to expose your business networks as RESTful APIs:

npm install -g composer-rest-server

3. Useful utility for generating application assets:

npm install -g generator-hyperledger-composer

4. Yeoman is a tool for generating applications, which utilises generator-hyperledger-composer:

npm install -g yo

Step 2: Install Playground

If you've already tried Blockchain Platform online, you'll have seen the browser app "Playground". You can run this locally on your development machine too, giving you a UI for viewing and demonstrating your business networks.

1. Browser app for simple editing and testing Business Networks:

npm install -g composer-playground

Step 3: Set up your IDE
Whilst the browser app can be used to work on your Business Network code, most users will prefer to work in an IDE. Our favourite is VSCode, because a Blockchain Platform extension is available.

1. Install VSCode from this URL: https://code.visualstudio.com/download

2. Open VSCode, go to Extensions, then search for and install the Hyperledger Composer extension from the Marketplace.

Step 4: Install Hyperledger Fabric
This step gives you a local Hyperledger Fabric runtime to deploy your business networks to.

1. In a directory of your choice (we will assume ~/fabric-dev-servers), get the .tar.gz file that contains the tools to install Hyperledger Fabric:

mkdir ~/fabric-dev-servers && cd ~/fabric-dev-servers

curl -O https://raw.githubusercontent.com/hyperledger/composer-tools/master/packages/fabric-dev-servers/fabric-dev-servers.tar.gz
tar -xvf fabric-dev-servers.tar.gz

A zip is also available if you prefer: just replace the .tar.gz file with fabric-dev-servers.zip and the tar -xvf command with a unzip command in the preceding snippet.

2. Use the scripts you just downloaded and extracted to download a local Hyperledger Fabric runtime:

cd ~/fabric-dev-servers
./downloadFabric.sh

Congratulations, you've now installed everything required for the typical Developer Environment. Read on to learn some of the most common things you'll do with this environment to develop and test your Blockchain Business Networks.

Controlling your dev environment
Starting and stopping Hyperledger Fabric
You control your runtime using a set of scripts which you'll find in ~/fabric-dev-servers if you followed the suggested defaults.

The first time you start up a new runtime, you'll need to run the start script, then generate a PeerAdmin card:

    cd ~/fabric-dev-servers
    ./startFabric.sh
    ./createPeerAdminCard.sh

Note: While running the above createPeerAdminCard.sh, if you encounter the below error, please follow the solution mentioned below:
===============
Error details:
$ sudo ./createPeerAdminCard.sh   Development only script for Hyperledger Fabric control
Running 'createPeerAdminCard.sh'
FABRIC_VERSION is unset, assuming hlfv11
FABRIC_START_TIMEOUT is unset, assuming 15 (seconds)

No version of composer-cli has been detected, you need to install composer-cli at v0.19 or higher

Solution:
1. Know the path where composer is installed by running the command 
where composer
It will mention the path where composer-cli is installed. Let's say the output is ~/.nvm/versions/node/v8.11.2/bin/composer
2. Now you need to add the alias into .bash_aliases file to make it work whenever you open the terminal.
a) First navigate to your user path using the bellow command.
cd ~
b) Then create or open a file named .bash_aliases in the home user path using the following command.
nano .bash_aliases
c) Then add the alias composer='~/.nvm/versions/node/v8.11.2/bin/composer' to that file and save it. So it will be work even after you restarting the system.
d) Now you can execute the createPeerAdminCard.sh and you will not encounter the error.
===============


You can start and stop your runtime using ~/fabric-dev-servers/stopFabric.sh, and start it again with ~/fabric-dev-servers/startFabric.sh.

At the end of your development session, you run ~/fabric-dev-servers/stopFabric.sh and then ~/fabric-dev-servers/teardownFabric.sh. Note that if you've run the teardown script, the next time you start the runtime, you'll need to create a new PeerAdmin card just like you did on first time startup.

The local runtime is intended to be frequently started, stopped and torn down, for development use. If you're looking for a runtime with more persistent state, you'll want to run one outside of the dev environment, and deploy Business Networks to it. Examples of this include running it via Kubernetes, or on a managed platform such as IBM Cloud.

Start the web app ("Playground")
To start the web app, run:
composer-playground
It will typically open your browser automatically, at the following address: http://localhost:8080/login

You should see the PeerAdmin@hlfv1 Card you created with the createPeerAdminCard script on your "My Business Networks" screen in the web app: if you don't see this, you may not have correctly started up your runtime!

Congratulations, you've got all the components running, and you also know how to stop and tear them down when you're done with your dev session.