Latest Entries »

Install Electron

You can choose to either install Electron globally on your computer with the following command (don’t run this for now):

$ npm install electron -g

..or, you can install it as a development dependency in your app, which is what we will do.

Run the following command:

$ npm install electron --save-dev --save-exact

Electron-deep-linking-mac-win

Reference : https://github.com/oikonomopo/electron-deep-linking-mac-win

const {app, BrowserWindow} = require('electron')
// Module with utilities for working with file and directory paths.
const path = require('path')
// Module with utilities for URL resolution and parsing.
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

// Deep linked url
let deeplinkingUrl

// Force Single Instance Application
const shouldQuit = app.makeSingleInstance((argv, workingDirectory) => {
  // Someone tried to run a second instance, we should focus our window.

  // Protocol handler for win32
  // argv: An array of the second instance’s (command line / deep linked) arguments
  if (process.platform == 'win32') {
    // Keep only command line / deep linked arguments
    deeplinkingUrl = argv.slice(1)
  }
  logEverywhere("app.makeSingleInstance# " + deeplinkingUrl)

  if (mainWindow) {
    if (mainWindow.isMinimized()) mainWindow.restore()
        mainWindow.focus()
  }
})
if (shouldQuit) {
    app.quit()
    return
}

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // Protocol handler for win32
  if (process.platform == 'win32') {
    // Keep only command line / deep linked arguments
    deeplinkingUrl = process.argv.slice(1)
  }
  logEverywhere("createWindow# " + deeplinkingUrl)

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// Define custom protocol handler. Deep linking works on packaged versions of the application!
app.setAsDefaultProtocolClient('myapp')

// Protocol handler for osx
app.on('open-url', function (event, url) {
  event.preventDefault()
  deeplinkingUrl = url
  logEverywhere("open-url# " + deeplinkingUrl)
})

// Log both at dev console and at running node console instance
function logEverywhere(s) {
    console.log(s)
    if (mainWindow && mainWindow.webContents) {
        mainWindow.webContents.executeJavaScript(`console.log("${s}")`)
    }
}

Reference : https://github.com/felixrieseberg/electron-windows-store

                     https://electronjs.org/docs/tutorial/windows-store-guide

To compile any existing Electron App, ensure that you have the following requirements:

  • Windows 10 with Anniversary Update (released August 2nd, 2016)
  • The Windows 10 SDK, downloadable here
  • At least Node 4 (to check, run node -v).
  • Then, go and install the electron-windows-store CLI:

npm install -g electron-windows-store

  • Then, configure your PowerShell:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

  • To turn an Electron app into an AppX package, run:

electron-windows-store –input-directory D:\<foldername>–output-directory D:\output\<foldername> –package-version 1.0.0.0 –package-name <exe file name>

–input-directory : Path of the exe file
–output-directory D:\output\<foldername> : Path where appx will be stored after creation
–package-version 1.0.0.0 : Version of the appx file
–package-name <exe file name> : EXE file name, (there should be no space in the file name)

  • It will ask few question to create certificate file, like

    Did you install DesktopAppConverter (Y/n) ? N
    Do you want to create the certificate file (Y/n) ? Y

Post that it will ask,

Publisher : CN=developmentca
Windows Kit Location(Path to makeappx.exe) : C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x64

Once all the input are given it will start creating certificate and all configuration will be store in the .electron-windows-store

Appx (Window app store) file will be created at –output-directory D:\output\<Dir name>

  1. C:\Users\<User>\AppData\Roaming\electron-windows-store\developmentca

Developmentca.pfx
Developmentca.pvk
Developmentca.cer

     2. Configuration of .electron-windows-store file path : C:\Users\<User>

{
 “publisher”: “CN=developmentca”,
 “windowsKit”: “C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x64”,
 “devCert”: “C:\\Tools\\DesktopConverter\\Certs\\devcert.pfx”,
 “desktopConverter”: “C:\\Tools\\DesktopConverter”,
 “expandedBaseImage”: C:\\ProgramData\\Microsoft\\Windows\\Images\\BaseImage-14316\\”
}

NOTE : In case of re-creating the certificate , please delete all files mentioned in the point 1 and 2.

git diff –name-only –diff-filter=U

Reference : https://www.hacksparrow.com/using-node-js-to-download-files.html

There are three approaches to writing a file downloader app using Node –

i. HTTP.get
ii. curl
iii. wget

I have created functions for all of them. To get the examples working makes sure you have the dependencies and app variables intact. Read the comments thoroughly, you will not only learn how to download files, but will also learn more about Node’s child_process, File System, Buffers, and Streams. Let’s start with HTTP.get.

i. Downloading using HTTP.get

HTTP.get is Node’s built-in mechanism for making HTTP GET requests, which can also be used for downloading files using the HTTP protocol. The advantage of using HTTP.get is that you don’t rely on any external programs to download files.

// Dependencies
var fs = require(‘fs’);
var url = require(‘url’);
var http = require(‘http’);
var exec = require(‘child_process’).exec;
var spawn = require(‘child_process’).spawn;

// App variables
var file_url = ‘file url’;
var DOWNLOAD_DIR = ‘./downloads/’; // User can give custom path as per their need

// We will be downloading the files to a directory, so make sure it’s there
// This step is not required if you have manually created the directory
var mkdir = ‘mkdir -p ‘ + DOWNLOAD_DIR;
var child = exec(mkdir, function(err, stdout, stderr) {
if (err) throw err;
else download_file_httpget(file_url);
});

// Function to download file using HTTP.get
var download_file_httpget = function(file_url) {
var options = {
host: url.parse(file_url).host,
port: 80,
path: url.parse(file_url).pathname
};

var file_name = url.parse(file_url).pathname.split(‘/’).pop();
var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);

http.get(options, function(res) {
res.on(‘data’, function(data) {
file.write(data);
}).on(‘end’, function() {
file.end();
console.log(file_name + ‘ downloaded to ‘ + DOWNLOAD_DIR);
});
});
};
The above function is probably the best way to download files using HTTP.get in Node. Make a HTTP.get request and create a writable stream using fs.createWriteStream. Since the HTTP.get’s response is a stream, it has the data event, which carries the chunks of data sent by the server. One each data event, write the data to the writeable stream. Once the server finishes sending data, close the instance of fs.createWriteStream. If you are trying to use fs.write or fs.writeFile or any of their variants, they will fail for medium to large files. Use fs.createWriteStream instead for reliable results.


ii. Downloading using curl

To download files using curl in Node.js we will need to use Node’s child_process module. We will be calling curl using child_process’s spawn method. We are using spawn instead of exec for the sake of convenience – spawn returns a stream with data event and doesn’t have buffer size issue unlike exec. That doesn’t mean exec is inferior to spawn; in fact we will use exec to download files using wget.

// Function to download file using curl
var download_file_curl = function(file_url) {

// extract the file name
var file_name = url.parse(file_url).pathname.split(‘/’).pop();
// create an instance of writable stream
var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);
// execute curl using child_process’ spawn function
var curl = spawn(‘curl’, [file_url]);
// add a ‘data’ event listener for the spawn instance
curl.stdout.on(‘data’, function(data) { file.write(data); });
// add an ‘end’ event listener to close the writeable stream
curl.stdout.on(‘end’, function(data) {
file.end();
console.log(file_name + ‘ downloaded to ‘ + DOWNLOAD_DIR);
});
// when the spawn child process exits, check if there were any errors and close the writeable stream
curl.on(‘exit’, function(code) {
if (code != 0) {
console.log(‘Failed: ‘ + code);
}
});
};
The way data was written to the instance of fs.createWriteStream is similar to way we did for HTTP.get. The only difference is that the data and end events are listened on the stdout object of spawn. Also we listen to spawn’s exit event to make note of any errors.


iii.  Downloading using wget

Although it says downloading using wget, this example applies to downloading using curl with the -O option too. This method of downloading looks the most simple from coding point of view.

// Function to download file using wget
var download_file_wget = function(file_url) {

// extract the file name
var file_name = url.parse(file_url).pathname.split(‘/’).pop();
// compose the wget command
var wget = ‘wget -P ‘ + DOWNLOAD_DIR + ‘ ‘ + file_url;
// excute wget using child_process’ exec function

var child = exec(wget, function(err, stdout, stderr) {
if (err) throw err;
else console.log(file_name + ‘ downloaded to ‘ + DOWNLOAD_DIR);
});
};
In the above method, we used child_process’s exec function to run wget. Why exec and not spawn? Because we just want wget to tell us if the work was done properly or not, we are not interested in buffers and streams. We are making wget do all the dirty work of making request, handling data, and saving the file for us. As you might have guessed, this method is the fastest among the three methods I described.

So now the question is – which method is the best? The answer – whatever suits your need. The wget method is probably the best is you want to save the files to the local disk, but certainly not if you want to send those files as a response to a current client request; for something like that you would need to use a stream. All the three methods have multiple options, you choice will ultimately depend on what your needs are.

Happy downloading!

 

 

Indexed DB with Angular 6

Reference (by Ujjwal Gupta)

Create Angular project

First we will have to create a angular project. I am showing you how to do with angular cli.

  1. Setup development environment — Install Node.js and npm if they are not installed.
  2. Install angular cli — execute the below code in a terminal window.
npm install -g @angular/cli

3. Create a new project — execute the below command to create an angular project.

ng new

You can choose any application name — i am choosing “my-app”.
Please keep patience , It will take some time to create the project.

4. Run Project — Goto the project directory and run the project.

Cd my-app
ng serve

It will take some time to compile the project. When it will be compiled , you will see a message — “Webpack compiled successfully”.

project compiled

Now open address — http://localhost:4200/ in browser . You will see output like this —

app works

Create Component and Service

Run the below command to create the component –

ng generate component student

This component will be used to write the business logic.

Now lets create the service to write the data logic. This way our code will be clean and easy to maintain.

Run the below code in terminal –

ng g service service/student

This will create a new student service inside the Service folder.

Now we need to add Service student inside component student . Copy the below code inside the file — student.component.ts

import {
      Component,
      OnInit
  } from '@angular/core';
  import {
      StudentService
  } from '../service/student.service';
  
  @Component({
      selector: 'app-student',
      templateUrl: './student.component.html',
      styleUrls: ['./student.component.css'],
      providers: [StudentService]
  })
  
  export class StudentComponent implements OnInit {
  
      private _service: StudentService;
  
      constructor(service: StudentService) {
          this._service = service;
      }
  
      ngOnInit() {}
  
  }
}

In the above code — I have added the StudentService in the providers array, which will be injected as dependency in StudentComponent constructor by angular.

Now to check the new component. We need to add the component selector tag in app.component.html

Replace the code with the below code –


student works

Download JsStore

Run the below command in terminal to install JsStore –

npm install jsstore --save

it will download the JsStore and save the dependencies in package.json .

Since database connection will be used by all the services, so it will be good if we keep the connection object in a common service.

So lets create a common service . Execute the below code in terminal –

ng g service service/idb

This will create the IdbService in service folder

now we need to write the code to get the connection. Copy the below code in the idb.service.ts –

import * as JsStore from 'jsstore';
import * as workerPath from 'file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js';
export class IdbService {
 // this will make sure that we are using one connection
 // otherwise multiple instance will be created and thus multiple 
 // worker and that may create some problems
 static idbCon = new JsStore.Instance(new Worker(workerPath));
}

In the above code —

  1. In the second line — you can see- we are importing “file-loader” as worker path. Now this seems confusing right ?

Actually i am doing some kinda of hack here- Angular uses webpack and file-loader (a webpack plugin) which is used by angular too to manage files. I am using file-loader here to get the path of jsstore.worker.min.js which you can see in file-loader query. Now that path will be supplied to jsstore to create the worker.

But since we are in a typescript project, we need to define the file-loader and let the typescript compiler know that this is a valid code. For this- create an extra folder and inside the folder a file — “worker.d.ts”. Paste the below content inside the file.

declare module "file-loader?name=scripts/[name].[hash].js!*" {
 const value: string;
 export = value;
}
including file-loader definition for typescript

2. we are declaring idbCon as static which will make sure that we are maintaining only one jsstore instance. Every service will use this connection to do indexeddb query.

Now we need to use this connection in student service but imagine if we have multiple service they all needs to use the connection and may be there are some common codes which all service needs to use like ajaxhelper, some common service variable etc. This is why — we need to create a base service which will help us to remove code redundancy and make the service more cleaner and maintainable.

So lets create a base service — execute below cmd in terminal

ng g service service/base

This will create the base service. Copy the below code in base service –

import {
 Injectable
} from '@angular/core';
import {
 IdbService
} from './idb.service';
export class BaseService {
constructor() {
  // turn on jsstore log status - help you to debug
  // turn it off in production or when you dont need
  this.connection.setLogStatus(true);
 }
get connection() {
  return IdbService.idbCon;
 }
}

Now we need to inherit base service in student service. So copy the below code

import {
 Injectable
} from '@angular/core';
import {
 BaseService
} from './base.service';
@Injectable({
 providedIn: 'root'
})
export class StudentService extends BaseService {
 constructor() {
  super();
 }
}

Run the below command to check if everything is good or not.

ng build

If it shows error — “In ambient enum declarations member initializer must be contant expression” then we need to update the typescript version.

To update the typescript version, run the below command –

npm install typescript@latest

now everything is setup, we just need to write the code.

Create Database

Creating database in JsStore is simple. It uses Sql approach — A database consist of multiple tables and a table consists of multiple columns.

Please take a look at the jsstore doc to create the database –

1. Create the table doc — http://jsstore.net/tutorial/table/

2. Create database doc — http://jsstore.net/tutorial/database/

now lets write the code to create the database and get the connection. Copy the below code in the base.service.ts –

import {
 IdbService
} from './idb.service';
import {
 IDataBase,
 DATA_TYPE,
 ITable
} from 'jsstore';
export class BaseService {
 dbname = 'Angular_Demo';
 constructor() {
  // turn on jsstore log status - help you to debug
  // turn off it in production or when you dont need
  this.connection.setLogStatus(true);
  this.initJsStore();
 }
get connection() {
  return IdbService.idbCon;
 }
initJsStore() {
  this.connection.isDbExist(this.dbname).then(isExist => {
   if (isExist) {
    this.connection.openDb(this.dbname);
   } else {
    const dataBase = this.getDatabase();
    this.connection.createDb(dataBase);
   }
  }).catch(err => {
   // this will be fired when indexedDB is not supported.
   alert(err.message);
  });
 }
private getDatabase() {
  const tblStudent: ITable = {
   name: 'Students',
   columns: [{
     name: 'id',
     primaryKey: true,
     autoIncrement: true
    },
    {
     name: 'name',
     notNull: true,
     dataType: DATA_TYPE.String
    },
    {
     name: 'gender',
     dataType: DATA_TYPE.String,
     default: 'male'
    },
    {
     name: 'country',
     notNull: true,
     dataType: DATA_TYPE.String
    },
    {
     name: 'city',
     dataType: DATA_TYPE.String,
     notNull: true
    }
   ]
  };
  const dataBase: IDataBase = {
   name: this.dbname,
   tables: [tblStudent]
  };
  return dataBase;
 }
}

The above code will create the database when it does not exist otherwise open the db connection for the specified database name.

Read data

JsStore provides select api to select the data from IndexedDB.

Please have a look at select api document — http://jsstore.net/tutorial/select

Lets first create a student model — execute the below command

ng generate class model/student

This will generate a class Student in folder Model.

Now we need to define our student model. So copy the below code in the file student.ts under folder model –

export class IStudent {
      id?: number;
      name: string;
      gender: string;
      country: string;
      city: string;
  }
  
  export class Student implements IStudent {
      id = 0;
      name = '';
      gender = 'm';
      country = '';
      city = '';
  }

In the above code i have also created the interface. It is a good practice to have an interface of class and you will see how we are going to use the interface.

Now lets write the code to select the students from indexedDB . Since it is data related code, so we will write it in Service.

Copy the below code inside the class StudentService –

getStudents() {
      return this.connection.select({
        from: 'Students'
      });
}

Looks simple and clean Right ?

Now we need to call getStudents from component student . Copy the below code inside the file — student.component.ts

import {
      Component,
      OnInit
  } from '@angular/core';
  
  import {
      StudentService
  } from '../service/student.service';
  import {
      Student,
      IStudent
  } from '../model/student';
  
  
  
  @Component({
  
      selector: 'app-student',
  
      templateUrl: './student.component.html',
  
      styleUrls: ['./student.component.css'],
  
      providers: [StudentService]
  
  })
  
  export class StudentComponent implements OnInit {
  
      private service: StudentService;
      students: Array  = [];
  
      constructor(service: StudentService) {
          this.service = service;
      }
  
  
      ngOnInit() {
          this.getStudents();
      }
  
      getStudents() {
          this.service.getStudents().
          then(students => {
              this.students = students;
          }).catch(error => {
              console.error(error);
              alert(error.message);
          });
      }
  
  }

In the above code –

  1. A method getStudents is created which calls the method — getStudents in the service and store the list of students inside the class member — students.

We have written business and data logic to get the students. Now we need to write the code for view. So lets write it.

Copy the below code inside the file — student.component.html

 

GenderCountryCity

{{student.gender==’m’?’Male’:’Female’}} {{student.country}} {{student.city}}

Student Name
{{student.name}}

In the above code –

  1. I have loop through “students” variable.
  2. I have also kept student id as attribute “data_id”. We will use this later for identifying the student.

Before runing the code , lets add some styles. Copy the below css code in the student.component.css file –

table {
    border-collapse: collapse;
  }
  
  table tr td,
  th {
    border: 1px solid black;
    text-align: center;
    padding: 10px;
  }
  
  contenteditable {
    border: 2px solid blue;
  }

Some styles will be used later. I hope you are able to understand these css.

Now everything is done. So lets see the output in browser . Run the command — “ng serve” and open the address localhost:4200

output with no data

There is only table heading but no data. This is because we have not inserted any data.

Insert Data

JsStore provides insert api for inserting data into IndexedDB.

Please have a look at insert api doc — http://jsstore.net/tutorial/insert

Now we need to write the code for adding student. So lets write the code in student service.

Copy the below method in student.service.ts

addStudent(student: IStudent) {
      return this.connection.insert({
        into: 'Students',
        return: true, // as id is autoincrement, so we would like to    get the inserted value
        values: [student]
      });
  }

now we need to call the addStudent from Component. Copy the below code inside the student.component.ts –

import {
 Component,
 OnInit
} from '@angular/core';
import {
 StudentService
} from '../service/student.service';
import {
 Student,
 IStudent
} from '../model/student';
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrls: ['./student.component.css'],
providers: [StudentService]
})
export class StudentComponent implements OnInit {
private service: StudentService;
 students: Array = [];
 newStudent: IStudent = new Student();
constructor(service: StudentService) {
  this.service = service;
 }
ngOnInit() {
  this.getStudents();
 }
getStudents() {
  this.service.getStudents().
  then(students => {
   this.students = students;
  }).catch(error => {
   console.error(error);
   alert(error.message);
  });
 }
addStudent() {
  this.service.addStudent(this.newStudent).
  then((addedStudents: IStudent[]) => {
   if (addedStudents.length > 0) {
    this.students.push(addedStudents[0]);
    this.clearNewStudent();
    alert('Successfully added');
   }
  }).catch(error => {
   console.error(error);
   alert(error.message);
  });
 }
clearNewStudent() {
  this.newStudent = new Student();
 }
}

In the above code –

  1. A class member newStudent has been created. This will be used to keep the new student information. Basically it will be used to bind with the view.
  2. A method addStudent is written. It will call the addStudent in the service supplying the new student which will add data in JsStore.
  3. A method clearNewStudent is written, which will clear the student value written in textbox.

now we have successfully written business logic and data logic. Its time for creating view for adding data.

Copy the below code inside the file — student.component.html

 

GenderCountryCity

Male
FeMale
AddCancel

{{student.gender==’m’?’Male’:’Female’}} {{student.country}} {{student.city}}

Student Name
{{student.name}}

In the above code –

  1. We have added a new table row which is used to add the student. We have binded newStudent with the textbox.
  2. Method addStudent will be called for add buttton.
  3. method clearNewStudent will be called for cancel button.

Now lets see the output.

add student

lets test the add function –

add student with data

Delete data

JsStore provides remove api for deleting data .

Please read the delete api doc — http://jsstore.net/tutorial/remove/

Lets write the code for deleting student. We need to delete a particular student, so we will use student id for deleting particular data.

Add the below method in student.service.ts –

deleteStudent(studentId: number) {
      return this.connection.remove({
        from: 'Students',
        where: {
          id: studentId
        }
      });
  }

lets call this code from component Student. Add the below function inside the component –

deleteStudent(studentId) {
      this.service.deleteStudent(studentId).
        then(rowsDeleted => {
          if (rowsDeleted > 0) {
            const index = this.students.findIndex(student => student.id === studentId);
            this.students.splice(index, 1);
            alert('Successfully deleted');
          }
        }).catch(error => {
          console.error(error);
          alert(error.message);
        });
  }

Now we need to create the view to delete data. Just add the below code in last cell of second row –

Delete
add delete button

Now everything is done. Lets test the code.

delete button screenshot

Update data

JsStore provides update api for updating data.

JsStore Update docs — http://jsstore.net/tutorial/update

Lets write the code for updating students in student service. Copy the below code in student.service.ts

updateStudent(studentId: number, updateValue: IStudent) {
      return this.connection.update({
        in: 'Students',
        where: {
          id: studentId
        },
        set: updateValue
      });
    }
  
    getStudent(studentId: number) {
      return this.connection.select({
        from: 'Students',
        where: {
          id: studentId
        }
      });
    }

In the above code –

  1. updateStudent method is written, which will update the student by student id.
  2. getStudent method is written, which returns student by id.

Now we need to call these methods from component

import { Component, OnInit } from '@angular/core';
  
  import { StudentService } from '../service/student.service';
  import { Student, IStudent } from '../model/student';
  
  
  
  @Component({
  
    selector: 'app-student',
  
    templateUrl: './student.component.html',
  
    styleUrls: ['./student.component.css'],
  
    providers: [StudentService]
  
  })
  
  
  
  export class StudentComponent implements OnInit {
  
    private service: StudentService;
    students: Array = [];
    newStudent: IStudent = new Student();
    oldStudent: IStudent = new Student();
  
    constructor(service: StudentService) {
      this.service = service;
    }
  
  
    ngOnInit() {
      this.getStudents();
    }
  
    getStudents() {
      this.service.getStudents().
        then(students => {
          this.students = students;
        }).catch(error => {
          console.error(error);
          alert(error.message);
        });
    }
  
    addStudent() {
      this.service.addStudent(this.newStudent).
        then((addedStudents: IStudent[]) => {
          if (addedStudents.length > 0) {
            this.students.push(addedStudents[0]);
            this.clearNewStudent();
            alert('Successfully added');
          }
        }).catch(error => {
          console.error(error);
          alert(error.message);
        });
    }
  
    clearNewStudent() {
      this.newStudent = new Student();
    }
  
    deleteStudent(studentId) {
      this.service.deleteStudent(studentId).
        then(rowsDeleted => {
          if (rowsDeleted > 0) {
            const index = this.students.findIndex(student => student.id === studentId);
            this.students.splice(index, 1);
            alert('Successfully deleted');
          }
        }).catch(error => {
          console.error(error);
          alert(error.message);
        });
    }
  
    clearOldStudent() {
      this.oldStudent = new Student();
    }
  
    getStudent(studentId) {
      this.service.getStudent(studentId).
        then(students => {
          if (students.length > 0) {
            this.oldStudent = students[0];
          }
        }).catch(error => {
          console.error(error);
          alert(error.message);
        });
    }
  
    updateStudent() {
      const updatedValue: IStudent = {
        name: this.oldStudent.name,
        gender: this.oldStudent.gender,
        country: this.oldStudent.country,
        city: this.oldStudent.city
      };
      this.service.updateStudent(this.oldStudent.id, updatedValue).
        then(rowsUpdated => {
          if (rowsUpdated > 0) {
            const index = this.students.findIndex(student => student.id === this.oldStudent.id);
            this.students[index] = this.oldStudent;
            this.clearOldStudent();
            alert('Successfully updated');
          }
        }).catch(error => {
          console.error(error);
          alert(error.message);
        });
    }
  
  }

In the above code –

  1. A class member oldStudent is created. It is used to keep the student info which is in edit mode.
  2. Method getStudent is created, which will be used to set the oldStudent variable by student id.
  3. Method updateStudent is created, which will be used to update the edited student.

Cool, now we are left with the view. Copy the below html code –

 

gendercountrycity

Male
FeMale
AddCancel

Male
FeMale
{{student.gender==’m’?’Male’:’Female’}} {{student.country}} {{student.city}} UpdateEditCancelDelete

Student Name
{{student.name}}

In the above code –

  1. We have kept a temporary variable editing. It will be used to check whether the table cell is edit mode or not.
  2. When edit button is clicked — we set the editing to true and call the getStudent which will set the student info inside the oldStudent.
  3. When Update button is clicked — we set the editing to false and call the updateStudent which will update the student.

Rest are simple html code.

Now lets test the result in browser –

You can download the article implementation here — Angular example

LAMP Setup

sudo apt-get update

## Install Apache
sudo apt-get install apache2
sudo service apache2 restart

## Install MySql
sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo systemctl status mysql

#mysql -u root -p

## Install PHP
sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql

## PHP Extensions
sudo apt install php7.0-cgi php7.0-imap php7.0-gd php7.0-mbstring php7.0-mcrypt php7.0-intl php7.0-zip php7.0-cgi php7.0-cli php7.0-json php7.0-xml php7.0-soap php7.0-odbc php7.0-pgsql php7.0-common php7.0-
curl

sudo service apache2 restart

https://github.com/PHPMailer/PHPMailer/tree/master/examples

Installation & loading

PHPMailer is available on Packagist (using semantic versioning), and installation via Composer is the recommended way to install PHPMailer. Just add this line to your composer.json file:

"phpmailer/phpmailer": "~6.0"

or run

composer require phpmailer/phpmailer

Note that the vendor folder and the vendor/autoload.php script are generated by Composer; they are not part of PHPMailer.

If you want to use the Gmail XOAUTH2 authentication class, you will also need to add a dependency on the league/oauth2-client package in your composer.json.

Alternatively, if you’re not using Composer, copy the contents of the PHPMailer folder into one of the include_path directories specified in your PHP configuration and load each class file manually:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

If you’re not using the SMTP class explicitly (you’re probably not), you don’t need a use line for the SMTP class.

If you don’t speak git or just want a tarball, click the ‘zip’ button on the right of the project page in GitHub, though note that docs and examples are not included in the tarball.

Legacy versions

PHPMailer 5.2 (which is compatible with PHP 5.0 – 7.0) is no longer being supported for feature updates, and will only be receiving security updates from now on. You will find the latest version of 5.2 in the 5.2-stable branch, and future versions of 5.2 will be tagged with 5.2.x version numbers, so existing Composer configs should remain working. If you’re using PHP 5.5 or later, we recommend you make the necessary changes to switch to the 6.0 release.

Upgrading from 5.2

The biggest changes are that source files are now in the src/ folder, and PHPMailer now declares the namespace PHPMailer\PHPMailer. This has several important effects – read the upgrade guide for more details.

Minimal installation

While installing the entire package manually or with Composer is simple, convenient and reliable, you may want to include only vital files in your project. At the very least you will need src/PHPMailer.php. If you’re using SMTP, you’ll need src/SMTP.php, and if you’re using POP-before SMTP, you’ll need src/POP3.php. You can skip the language folder if you’re not showing errors to users and can make do with English-only errors. If you’re using XOAUTH2 you will need src/OAuth.php as well as the Composer dependencies for the services you wish to authenticate with. Really, it’s much easier to use Composer!

A Simple Example

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader
require 'vendor/autoload.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@example.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    //Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

You’ll find plenty more to play with in the examples folder.

That’s it. You should now be ready to use PHPMailer!

Localization

PHPMailer defaults to English, but in the language folder you’ll find numerous (48 at the time of writing!) translations for PHPMailer error messages that you may encounter. Their filenames contain ISO 639-1 language code for the translations, for example fr for French. To specify a language, you need to tell PHPMailer which one to use, like this:

// To load the French version
$mail->setLanguage('fr', '/optional/path/to/language/directory/');

MySQL Innodb Performance Tuning For Disk-Bound Workloads On CMT Servers

MySQL is one of the world’s most popular open source databases, and it is widely used and becoming the database-of-choice for many leading Web 2.0 sites. Like most database servers, the most common bottleneck in the enterprise environment encountered by MySQL is disk I/O. To maximize the performance of MySQL for disk I/O bound workloads on the Solaris operating system on CMT servers (e.g. the Sun Fire T2000 Server), configuration and tuning of MySQL server variables is critical and can make a big difference to performance,  as does the optimization of the Solaris filesystem for MySQL, and the configuration of storage arrays.

Configuration Issues

MySQL server’s performance can be optimized using various configuration settings. The first step is to read the configuration and system variables by running the command:

mysql> show variables;

Once you have done this, you can take appropriate action to configure/tune the variables for better performance. This action can be one of the following:

  1. Change a value in the my.cnf configuration file, or mysql start up options
  2. Configure the optimum number of user connections
  3. Optimize Solaris file system performance
  4. Setup and configure storage disk array
  5. Make database schema changes, such as changing design of one or more tables, or adding or modifying indexes
  6. Optimize the queries used by the application

 

This document will only concentrate on changing MySQL configuration settings and file system tuning. Storage configuration and changes at the database design and application level are not covered.

MySQL Server Variables

MySQL has many variables that can be adjusted to change MySQL behavior or for performance purpose. For I/O bound workloads, the most important parameters are memory related variables. MySQL includes several storage engines, including MyISAM, InnoDB, HEAP, and Berkeley DB (BDB), some variables apply to one of the storage engines only, some variables are used in the SQL layer applying to all the storage engines. While using the ACID transaction supported Innodb storage engine, first, we don’t need to configure the following memory-related variables, saving precious memory in the disk I/O bound workload:

         bulk_insert_buffer_size

         key_buffer_size

         key_cache_age_threshold, key_cache_block_size, key_cache_division_limit

         read_buffer_size, read_rnd_buffer_size

There are several memory-related variables that apply to all storage engines

         join_buffer_size – A buffer used for full join. When there are large joins without indexes, increase this buffer size to improve the efficiency.

         sort_buffer_size – A buffer used for the sort result set allocated by each thread. This can speed up ORDER BY and GROUP BY queries.

         query_cache_size – Set this variable to a nonzero value to enable query caching

         query_cache_limit – The maximum size of the cached result set, the larger result set won’t be cached

         query_cache_min_res_unit –query cache allocate memory blocks with the minimum size set by this variable. When the application has a lot of queries with small results,the default block size (4KB) may lead to memory fragmentation. So with small resultsets, decreasing it to 2048 or 1024 bytes might improve performance; with large query resultsets, increasing it to 8192, 16384 or more may improve performance query_cache_type: 0=OFF, 1=ON

The MySQL query cache stores the identical SELECT queries issued by clients to the database server. This makes it possible to locate and re-issue the same queries without repetitive hard parsing activities. MySQL also stores the query’s result set in the query cache, which can significantly reduce the overhead of creating complex result sets for queries from the disk or memory caches, reducing both physical and logical I/O. This can speed up applications where repetitive queries of products are being issued.  If you see a high value for qcache_hits compared to your total queries at runtime or a low value forqcache_free_memory seen from the mysql>show status; you probably need to increase the value of the query_cache_size parameter accordingly. Otherwise, you would decrease the value of the query_cache_size parameter to save memory resources for the other MySQL cache buffers. If qcache_hit is 0 in the runtime, you would completely turn off the query cache by setting query_cache_type as 0, together with setting query_cache_size as 0, since there is some overhead caused by having the query cache enabled besides wasting the memory resource. If the application uses many simple SELECT queries without them being repeated, having the query cache enabled may actually impede performance by 5-10%. However, for applicationswith many repeated SELECT queries with large resultsets, the performance increase set by the query cache can be 200% or more.

         tmp_table_size – set the maximum memory to allocate to a temporary table automatically created during query execution before MySQL converts it into an on-disk MyISAM table. When you see a lot of queries with the state value shown as “copying to tmp table on disk” when running the mysql>SHOW PROCESSLIST(or mysqladmin –i10 processlist extended-status) command, this means that the temporary resultset was larger than the value set by tmp_table_size, so that the MySQL thread copies the temporary table from RAM to disk. , In such cases, increasing the value can speed up execution of large queries; otherwise, decrease the value to save memory for the MySQL I/O bound workload.

         table_cache – Size this cache to keep most tables open since opening tables can be expensive. The optimum value for table_cache is directly related to the number of tables that need to be opened simultaneously in order to perform multiple-table joins. The table_cache value should be no less than the number of concurrent connections times the largest number tables involved in any one join.  1024 is a good value for applications with a couple of hundred tables (each connection has its own entry). You should check theOpen_tables status variable to see if it is large compared to table_cache

MySQL Innodb Only Memory-related variables

         innodb_buffer_pool_size – Set the amount of memory allocated to both Innodb data and index buffer cache. If the server requests data available in the cache, the data can be processed right away. Otherwise, the operating system will request that the data be loaded from the disk into the buffer. It is important to set this value as high as possible to use the more efficient innodb data and index buffer cache instead of operating system buffer. For the sysbench I/O bound workload on a T2000 server with 8G RAM, increasing innodb_buffer_pool_size from 4G to 5G can improve performance by around 11%.

          innodb_additional_mem_pool_size – Sets the amount of memory allocated to the buffer storing the InnoDB internal data dictionary and other internal data structures. This parameter does not affect performance much, so set it to 20M (For applications with more tables, more memory needs to be allocated here) for the sysbench OLTP I/O bound test case.

         innodb_log_buffer_size – Set the amount of memory allocated to the buffer storing InnoDBwrite-ahead log entries. For large transactions, the log can be loaded into the log buffer instead of writing log to the log files on disk untill the log buffer is flushed on each transaction commit. If you see large log I/Os in the show innodb status output at runtime, you probably need to set a larger value for the innodb_log_buffer_size parameter to save disk I/O. For workloads which don’t have long transactions like sysbench, it is not necessary to waste memory resources by setting a higher value for the log buffer; it is fine to set it to 8Mbytes.

Other MySQL Innodb variables impacting I/O Performance

         innodb_flush_log_at_trx_commit – InnoDB flushes the transaction log to disk approximately once per second in the background. As a default,innodb_flush_log_at_trx_commit is set to 1, meaning the log is flushed to the disk at a transaction commit, and modifications made by the transaction won’t be lost during a MySQL, OS, or HW crash. For workloads running with many small transactions, you can reduce disk I/O to the logs to improve performance by setting theinnodb_flush_log_at_trx_commit parameter to 0, meaning no log flushing on each transaction commit. However, the transaction might be lost if MySQL crashes. In the sysbench OLTP I/O bound workload test on a T2000 server, settinginnodb_flush_log_at_trx_commit =0  in the read-only test can improve performance by 4%. You can set this value to 2 to flush the log to the OS cache to save disk I/O on each transaction commit.

         innodb_log_file_size – Set the size of each log file in a log group. InnoDB writes to the log files in a circular fashion, so the bigger innodb_log_file_size, the less checkpoint flush activity, reducing disk I/O, but increasing recovery time. In the show innodb status output, if there are large page writes in the BUFFER POOL AND MEMORY part, you will need to increase this parameter.

Configure an Optimum Number of User Threads

MySQL is a single-process, multithreaded application.  There is one master thread with highest priority to control the server. For every client request, it creates a dedicated user thread running at normal priority in the thread pools to process the user request and send back the result to each client once the result is ready. And there is one single user thread that waits for input from the console, and a group of utility threads running at lower priority to handle some background tasks. Currently, MySQL cannot scale well with the number of concurrent user connections. On a T2000 server, in the OLTP I/O bound read-write sysbench test, MySQL can scale from 2 up to 64 concurrent user threads to reach the peak performance point. After that, increasing the number of user connections will increase the user level lock contention observed from prstat –mLoutput(LCK) to reduce MySQL performance. For applications where the number of user connections is tunable, you need to test to get the optimum number of user connections for peak performance. For applications where the number of user connections is not tunable, theinnodb_thread_concurrency parameter can be configured to set the number of threads working inside the InnoDB engine. You need to increase this value when you see many queries in the queue in show innodb status. Setting this value at 0 will disable it. On the T2000 server, we set it to be around 2\*(Num of disks) in the sysbench OLTP I/O bound workload test. Testing and tuning the optimal value for the innodb_thread_concurrency parameter according to the kind of workload, and behavior of your system at runtime, can affect performance significantly.

Optimize File system Performance on T2000

File system performance have a big impact on system performance — particularly when running an I/O bound workload with a database size much bigger than system memory. How to configure the file system for better performance depends on the workload access pattern: random or sequential. For a sequential workload, we can increase the file system cluster size (the maxcontigparameter) to allow read ahead or writing back more data from/to the disk to reduce the total number of I/O operations. For random workloads, we can reduce the file system cluster size to match the innodb I/O size.  On the Solaris platform, maxcontig  is set as 128 by default, which will trigger read-ahead for the whole file system cluster length (128\*8 Kbytes on Solaris Sparc, 128\*4Kbytes on Solaris x86) or the maximum size of physical I/O set in maxphys system variable. In the sysbench OLTP I/O bound test (a random workload,) for example, it can saturate a disk and significantly degrade performance because of it. One way to solve this problem is to reduce the value of the maxcontig parameter. In the sysbench OLTP I/O bound tests on the T2000, changing the maxcontig value to be 2 by using the tunefs –a 2 /dev/dsk/c4t1d0s6command on the file system improved performance by 10%-13%. The shortcoming of this solution is that it will impact the performance of other sequential workloads on your system. The other way to improve performance is to disable file system caching with the UFS mount option:  forcedirectio (mount –o remount,forcedirectio /data). Since innodb has its own buffer cache for the data and index(set by innodb_buffer_pool_size) which is more efficient than the operating system cache, we can use filesystem directio to save the double buffering and automatically disable read-ahead to benefit the random workload. On a T2000 installed with Solaris 10 update 1 to update 3, it is important to add set auto_lpg_maxszc=1 to the /etc/system suggested by Aleksandr Guzovskiy to reduce max pagesize for heap/stack/mmap to be 64k(default is up to be 256M) while using filesystem directio, otherwise, you may encounter a big performance dropwith directio while multiple concurrent user threads are accessing the MySQL database. On the T2000 in the sysbench OLTP I/O bound tests, using directio improved performance by 14%-17%. The shortcoming of using filesystem directio is that it will significantly impact the performance of other applications on your system which don’t have internal caching (like the MySQL MyISAM engine which does not have its own data buffer cache) but instead depend on the filesytem caching to implement buffering.

Expected MySQL Performance On Niagara 2 UltraSPARC T2 Server

For disk I/O workload, MySQL can benefit the new features on Niagara 2 servers compared to Niagara 1 servers:

Larger L2 Cache:  The on-chip 4MB L2 cache on Niagara 2 server can cache frequently accessed memory to get better MySQL performance.

Larger memory: Up to 512GB memory of fully buffered DIMMs in the integrated memory controller with an aggregated memory bandwidth of 64 gbps on the Niagara 2 server can buffer larger databases into the memory and reduce the time the CPU spends waiting for data to arrive. By adjusting how much memory MySQL innodb uses, we can expect to get significant performance improvements.

X8 PCI Express: PCI-E directly on-chip can reduce latency to speed up MySQL disk I/O performance as expected.

 

More paper on UltraSPARC T2 Server Technology, performance, etc.

Allan Pack’s Weblog: CMT Comes Of Age

 

Example MySQL options

Here is the  example of  /etc/my.cnf  on T2000(32x1200MHz, 8GB RAM, Solaris 10 11/06) in sysbench OLTP I/O bound test(100M-row):

[mysqld]

port = 3306

socket = /tmp/mysql.sock

basedir = /usr/local/mysql

datadir = /usr/local/mysql/data

log-error = /data/error.txt

user=root

skip-locking

max_connections = 3000

table_cache = 1024

max_allowed_packet = 1M 

sort_buffer_size = 64K

thread_cache = 8

thread_concurrency = 32

query_cache_size = 0M

query_cache_type = 0

default-storage-engine = innodb

transaction_isolation = REPEATABLE-READ

tmp_table_size = 1M

innodb_data_file_path = ibdata1:100M:autoextend

innodb_buffer_pool_size = 5500M

innodb_additional_mem_pool_size = 20M

innodb_log_file_size =1900M

innodb_log_buffer_size = 8M

innodb_flush_log_at_trx_commit =1 

innodb_lock_wait_timeout = 300

innodb_max_dirty_pages_pct = 90

innodb_thread_concurrency =32

 

Example /etc/system on T2000

set pcie:pcie_aer_ce_mask=0x1

set ip:dohwcksum=0

set autoup=900

set tune_t_fsflushr=1

set auto_lpg_maxszc=1

 

https://www.digitalocean.com/community/tutorials/how-to-create-a-self-signed-ssl-certificate-for-apache-in-ubuntu-16-04

 

 

Introduction

TLS, or transport layer security, and its predecessor SSL, which stands for secure sockets layer, are web protocols used to wrap normal traffic in a protected, encrypted wrapper.

Using this technology, servers can send traffic safely between the server and clients without the possibility of the messages being intercepted by outside parties. The certificate system also assists users in verifying the identity of the sites that they are connecting with.

In this guide, we will show you how to set up a self-signed SSL certificate for use with an Apache web server on an Ubuntu 16.04 server.

Note: A self-signed certificate will encrypt communication between your server and any clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers, users cannot use the certificate to validate the identity of your server automatically.

A self-signed certificate may be appropriate if you do not have a domain name associated with your server and for instances where the encrypted web interface is not user-facing. If you do have a domain name, in many cases it is better to use a CA-signed certificate. You can find out how to set up a free trusted certificate with the Let’s Encrypt project here.

Prerequisites

Before you begin, you should have a non-root user configured with sudo privileges. You can learn how to set up such a user account by following our initial server setup for Ubuntu 16.04.

You will also need to have the Apache web server installed. If you would like to install an entire LAMP (Linux, Apache, MySQL, PHP) stack on your server, you can follow our guide on setting up LAMP on Ubuntu 16.04. If you just want the Apache web server, skip the steps pertaining to PHP and MySQL in the guide.

When you have completed the prerequisites, continue below.

Step 1: Create the SSL Certificate

TLS/SSL works by using a combination of a public certificate and a private key. The SSL key is kept secret on the server. It is used to encrypt content sent to clients. The SSL certificate is publicly shared with anyone requesting the content. It can be used to decrypt the content signed by the associated SSL key.

We can create a self-signed key and certificate pair with OpenSSL in a single command:

  • sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt

You will be asked a series of questions. Before we go over that, let’s take a look at what is happening in the command we are issuing:

  • openssl: This is the basic command line tool for creating and managing OpenSSL certificates, keys, and other files.
  • req: This subcommand specifies that we want to use X.509 certificate signing request (CSR) management. The “X.509” is a public key infrastructure standard that SSL and TLS adheres to for its key and certificate management. We want to create a new X.509 cert, so we are using this subcommand.
  • -x509: This further modifies the previous subcommand by telling the utility that we want to make a self-signed certificate instead of generating a certificate signing request, as would normally happen.
  • -nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Apache to be able to read the file, without user intervention, when the server starts up. A passphrase would prevent this from happening because we would have to enter it after every restart.
  • -days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here.
  • -newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did not create the key that is required to sign the certificate in a previous step, so we need to create it along with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long.
  • -keyout: This line tells OpenSSL where to place the generated private key file that we are creating.
  • -out: This tells OpenSSL where to place the certificate that we are creating.

As we stated above, these options will create both a key file and a certificate. We will be asked a few questions about our server in order to embed the information correctly in the certificate.

Fill out the prompts appropriately. The most important line is the one that requests the Common Name (e.g. server FQDN or YOUR name). You need to enter the domain name associated with your server or, more likely, your server’s public IP address.

The entirety of the prompts will look something like this:

Output
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:New York City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc.
Organizational Unit Name (eg, section) []:Ministry of Water Slides
Common Name (e.g. server FQDN or YOUR name) []:server_IP_address
Email Address []:admin@your_domain.com

Both of the files you created will be placed in the appropriate subdirectories of the /etc/ssl directory.

While we are using OpenSSL, we should also create a strong Diffie-Hellman group, which is used in negotiating Perfect Forward Secrecy with clients.

We can do this by typing:

  • sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048

This may take a few minutes, but when it’s done you will have a strong DH group at /etc/ssl/certs/dhparam.pem that we can use in our configuration.

Step 2: Configure Apache to Use SSL

We have created our key and certificate files under the /etc/ssl directory. Now we just need to modify our Apache configuration to take advantage of these.

We will make a few adjustments to our configuration:

  1. We will create a configuration snippet to specify strong default SSL settings.
  2. We will modify the included SSL Apache Virtual Host file to point to our generated SSL certificates.
  3. (Recommended) We will modify the unencrypted Virtual Host file to automatically redirect requests to the encrypted Virtual Host.

When we are finished, we should have a secure SSL configuration.

Create an Apache Configuration Snippet with Strong Encryption Settings

First, we will create an Apache configuration snippet to define some SSL settings. This will set Apache up with a strong SSL cipher suite and enable some advanced features that will help keep our server secure. The parameters we will set can be used by any Virtual Hosts enabling SSL.

Create a new snippet in the /etc/apache2/conf-available directory. We will name the file ssl-params.conf to make its purpose clear:

  • sudo nano /etc/apache2/conf-available/ssl-params.conf

To set up Apache SSL securely, we will be using the recommendations by Remy van Elst on the Cipherli.stsite. This site is designed to provide easy-to-consume encryption settings for popular software. You can read more about his decisions regarding the Apache choices here.

The suggested settings on the site linked to above offer strong security. Sometimes, this comes at the cost of greater client compatibility. If you need to support older clients, there is an alternative list that can be accessed by clicking the link on the page labelled “Yes, give me a ciphersuite that works with legacy / old software.” That list can be substituted for the items copied below.

The choice of which config you use will depend largely on what you need to support. They both will provide great security.

For our purposes, we can copy the provided settings in their entirety. We will just make two small changes.

Set the SSLOpenSSLConfCmd DHParameters directive to point to the Diffie-Hellman file we generated earlier. Also, take a moment to read up on HTTP Strict Transport Security, or HSTS, and specifically about the “preload” functionality. Preloading HSTS provides increased security, but can have far reaching consequences if accidentally enabled or enabled incorrectly. In this guide, we will not preload the settings, but you can modify that if you are sure you understand the implications:

/etc/apache2/conf-available/ssl-params.conf
# from https://cipherli.st/
# and https://raymii.org/s/tutorials/Strong_SSL_Security_On_Apache2.html

SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
SSLProtocol All -SSLv2 -SSLv3
SSLHonorCipherOrder On
# Disable preloading HSTS for now.  You can use the commented out header line that includes
# the "preload" directive if you understand the implications.
#Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains"
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
# Requires Apache >= 2.4
SSLCompression off 
SSLSessionTickets Off
SSLUseStapling on 
SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

SSLOpenSSLConfCmd DHParameters "/etc/ssl/certs/dhparam.pem"

Save and close the file when you are finished.

Modify the Default Apache SSL Virtual Host File

Next, let’s modify /etc/apache2/sites-available/default-ssl.conf, the default Apache SSL Virtual Host file. If you are using a different server block file, substitute it’s name in the commands below.

Before we go any further, let’s back up the original SSL Virtual Host file:

  • sudo cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak

Now, open the SSL Virtual Host file to make adjustments:

  • sudo nano /etc/apache2/sites-available/default-ssl.conf

Inside, with most of the comments removed, the Virtual Host file should look something like this by default:

/etc/apache2/sites-available/default-ssl.conf
<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
                ServerAdmin webmaster@localhost

                DocumentRoot /var/www/html

                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined

                SSLEngine on

                SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
                SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

                <FilesMatch "\.(cgi|shtml|phtml|php)$">
                                SSLOptions +StdEnvVars
                </FilesMatch>
                <Directory /usr/lib/cgi-bin>
                                SSLOptions +StdEnvVars
                </Directory>

                # BrowserMatch "MSIE [2-6]" \
                #               nokeepalive ssl-unclean-shutdown \
                #               downgrade-1.0 force-response-1.0

        </VirtualHost>
</IfModule>

We will be making some minor adjustments to the file. We will set the normal things we’d want to adjust in a Virtual Host file (ServerAdmin email address, ServerName, etc.), adjust the SSL directives to point to our certificate and key files, and uncomment one section that provides compatibility for older browsers.

After making these changes, your server block should look similar to this:

/etc/apache2/sites-available/default-ssl.conf
<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
                ServerAdmin your_email@example.com
                ServerName server_domain_or_IP

                DocumentRoot /var/www/html

                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined

                SSLEngine on

                SSLCertificateFile      /etc/ssl/certs/apache-selfsigned.crt
                SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key

                <FilesMatch "\.(cgi|shtml|phtml|php)$">
                                SSLOptions +StdEnvVars
                </FilesMatch>
                <Directory /usr/lib/cgi-bin>
                                SSLOptions +StdEnvVars
                </Directory>

                BrowserMatch "MSIE [2-6]" \
                               nokeepalive ssl-unclean-shutdown \
                               downgrade-1.0 force-response-1.0

        </VirtualHost>
</IfModule>

Save and close the file when you are finished.

As it stands now, the server will provide both unencrypted HTTP and encrypted HTTPS traffic. For better security, it is recommended in most cases to redirect HTTP to HTTPS automatically. If you do not want or need this functionality, you can safely skip this section.

To adjust the unencrypted Virtual Host file to redirect all traffic to be SSL encrypted, we can open the /etc/apache2/sites-available/000-default.conf file:

  • sudo nano /etc/apache2/sites-available/000-default.conf

Inside, within the VirtualHost configuration blocks, we just need to add a Redirect directive, pointing all traffic to the SSL version of the site:

/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
        . . .

        Redirect "/" "https://your_domain_or_IP/"

        . . .
</VirtualHost>

Save and close the file when you are finished.

Step 3: Adjust the Firewall

If you have the ufw firewall enabled, as recommended by the prerequisite guides, might need to adjust the settings to allow for SSL traffic. Luckily, Apache registers a few profiles with ufw upon installation.

We can see the available profiles by typing:

  • sudo ufw app list

You should see a list like this:

Output
Available applications:
  Apache
  Apache Full
  Apache Secure
  OpenSSH

You can see the current setting by typing:

  • sudo ufw status

If you allowed only regular HTTP traffic earlier, your output might look like this:

Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
Apache                     ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
Apache (v6)                ALLOW       Anywhere (v6)

To additionally let in HTTPS traffic, we can allow the “Apache Full” profile and then delete the redundant “Apache” profile allowance:

  • sudo ufw allow ‘Apache Full’
  • sudo ufw delete allow ‘Apache’

Your status should look like this now:

  • sudo ufw status
Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
Apache Full                ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
Apache Full (v6)           ALLOW       Anywhere (v6)

Step 4: Enable the Changes in Apache

Now that we’ve made our changes and adjusted our firewall, we can enable the SSL and headers modules in Apache, enable our SSL-ready Virtual Host, and restart Apache.

We can enable mod_ssl, the Apache SSL module, and mod_headers, needed by some of the settings in our SSL snippet, with the a2enmod command:

  • sudo a2enmod ssl
  • sudo a2enmod headers

Next, we can enable our SSL Virtual Host with the a2ensite command:

  • sudo a2ensite default-ssl

We will also need to enable our ssl-params.conf file, to read in the values we set:

  • sudo a2enconf ssl-params

At this point, our site and the necessary modules are enabled. We should check to make sure that there are no syntax errors in our files. We can do this by typing:

  • sudo apache2ctl configtest

If everything is successful, you will get a result that looks like this:

Output
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
Syntax OK

The first line is just a message telling you that the ServerName directive is not set globally. If you want to get rid of that message, you can set ServerName to your server’s domain name or IP address in /etc/apache2/apache2.conf. This is optional as the message will do no harm.

If your output has Syntax OK in it, your configuration file has no syntax errors. We can safely restart Apache to implement our changes:

  • sudo systemctl restart apache2

Step 5: Test Encryption

Now, we’re ready to test our SSL server.

Open your web browser and type https:// followed by your server’s domain name or IP into the address bar:

https://server_domain_or_IP

Because the certificate we created isn’t signed by one of your browser’s trusted certificate authorities, you will likely see a scary looking warning like the one below:

Apache self-signed cert warning

This is expected and normal. We are only interested in the encryption aspect of our certificate, not the third party validation of our host’s authenticity. Click “ADVANCED” and then the link provided to proceed to your host anyways:

Apache self-signed override

You should be taken to your site. If you look in the browser address bar, you will see a lock with an “x” over it. In this case, this just means that the certificate cannot be validated. It is still encrypting your connection.

If you configured Apache to redirect HTTP to HTTPS, you can also check whether the redirect functions correctly:

http://server_domain_or_IP

If this results in the same icon, this means that your redirect worked correctly.

Step 6: Change to a Permanent Redirect

If your redirect worked correctly and you are sure you want to allow only encrypted traffic, you should modify the unencrypted Apache Virtual Host again to make the redirect permanent.

Open your server block configuration file again:

  • sudo nano /etc/apache2/sites-available/000-default.conf

Find the Redirect line we added earlier. Add permanent to that line, which changes the redirect from a 302 temporary redirect to a 301 permanent redirect:

/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
        . . .

        Redirect permanent "/" "https://your_domain_or_IP/"

        . . .
</VirtualHost>

Save and close the file.

Check your configuration for syntax errors:

  • sudo apache2ctl configtest

When you’re ready, restart Apache to make the redirect permanent:

  • sudo systemctl restart apache2

Conclusion

You have configured your Apache server to use strong encryption for client connections. This will allow you serve requests securely, and will prevent outside parties from reading your traffic.

<?php

function objectToArray($d) {

if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/**
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}

Removing and re-installing Mysql

  1. sudo apt purge mysql*
  2. Remove /etc/mysql folder
  3. Remove /var/lib/mysql, /var/lib/mysql-files, /var/lib/mysql-keyring folders.
  4. Reboot Install mysql using: sudo apt-get install mysql-serve.
  5. Make sure to set a password for root!

The reason is that recent Ubuntu installation (maybe others also), mysql is using by default the UNIX auth_socket plugin.

Basically means that: db_users using it, will be “auth” by the system user credentias. You can see if your root user is set up like this by doing the following:

$ sudo mysql -u root # I had to use "sudo" since is new installation

mysql> USE mysql;
mysql> SELECT User, Host, plugin FROM mysql.user;

+------------------+-----------------------+
| User             | plugin                |
+------------------+-----------------------+
| root             | auth_socket           |
| mysql.sys        | mysql_native_password |
| debian-sys-maint | mysql_native_password |
+------------------+-----------------------+

As you can see in the query, the root user is using the auth_socket plugin

There are 2 ways to solve this:

  1. You can set the root user to use the mysql_native_password plugin
  2. You can create a new db_user with you system_user (recommended)

Option 1:

$ sudo mysql -u root # I had to use "sudo" since is new installation

mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;

$ service mysql restart

Option 2: (replace YOUR_SYSTEM_USER with the username you have)

$ sudo mysql -u root # I had to use "sudo" since is new installation

mysql> USE mysql;
mysql> CREATE USER 'YOUR_SYSTEM_USER'@'localhost' IDENTIFIED BY '';
mysql> GRANT ALL PRIVILEGES ON * . * TO 'YOUR_SYSTEM_USER'@'localhost';
mysql> UPDATE user SET plugin='auth_socket' WHERE User='YOUR_SYSTEM_USER';
mysql> FLUSH PRIVILEGES;
mysql> exit;

$ service mysql restart

Remember that if you use option #2 you’ll have to connect to mysql as your system username (mysql -u YOUR_SYSTEM_USER)

EventBrtie API’s

Protect API Methods

URL : https://github.com/stas/php-eventbrite/blob/master/EBAPI.class.php

protected $api_methods = array(

Discount

   ‘discount_new’       => array( ‘event_id’, ‘code’, ‘amount_off’, ‘percent_off’, ‘tickets’, ‘quantity_available’, ‘start_date’, ‘end_date’ ),

   ‘discount_update’   => array( ‘id’, ‘code’, ‘amount_off’, ‘percent_off’, ‘tickets’, ‘quantity_available’, ‘start_date’, ‘end_date’ ),

Events

   ‘event_copy’                 => array( ‘event_id’, ‘event_name’ ),

   ‘event_get’                 => array( ‘id’ ),

   ‘event_list_attendees’   => array( ‘id’, ‘count’, ‘page’, ‘do_not_display’, ‘show_full_barcodes’ ),

   ‘event_list_discounts’   => array( ‘id’ ),

   ‘event_new’                 => array( ‘title’, ‘description’, ‘start_date’, ‘end_date’, ‘timezone’, ‘privacy’, ‘personalized_url’, ‘venue_id’, ‘organizer_id’, ‘capacity’, ‘currency’, ‘status’, ‘custom_header’, ‘custom_footer’, ‘background_color’, ‘text_color’, ‘link_color’, ‘title_text_color’, ‘box_background_color’, ‘box_text_color’, ‘box_border_color’, ‘box_header_background_color’, ‘box_header_text_color’ ),

   ‘event_search’    => array( ‘keywords’, ‘category’, ‘address’, ‘city’, ‘region’, ‘postal_code’, ‘country’, ‘within’, ‘within_unit’, ‘latitude’, ‘longitude’, ‘date’, ‘date_created’, ‘date_modified’, ‘organizer’, ‘max’, ‘count_only’, ‘sort_by’, ‘page’, ‘since_id’, ‘tracking_link’ ),

   ‘event_update’    => array( ‘event_id’, ‘title’, ‘description’, ‘start_date’, ‘end_date’, ‘timezone’, ‘privacy’, ‘personalized_url’, ‘venue_id’, ‘organizer_id’, ‘capacity’, ‘currency’, ‘status’, ‘custom_header’, ‘custom_footer’, ‘background_color’, ‘text_color’, ‘link_color’, ‘title_text_color’, ‘box_background_color’, ‘box_text_color’, ‘box_border_color’, ‘box_header_background_color’, ‘box_header_text_color’ ),
Organizer

   ‘organizer_list_events’    => array( ‘id’ ),

   ‘organizer_new’       => array( ‘name’, ‘description’ ),

   ‘organizer_update’       => array( ‘id’, ‘name’, ‘description’ ),

Payment

   ‘payment_update’       => array( ‘event_id’, ‘accept_paypal’, ‘paypal_email’, ‘accept_google’, ‘google_merchant_id’, ‘google_merchant_key’, ‘accept_check’, ‘instructions_check’, ‘accept_cash’, ‘instructions_cash’, ‘accept_invoice’, ‘instructions_invoice’ ),

Ticket

   ‘ticket_new’      => array( ‘event_id’, ‘is_donation’, ‘name’, ‘description’, ‘price’, ‘quantity’, ‘start_sales’, ‘end_sales’, ‘include_fee’, ‘min’, ‘max’ ),

   ‘ticket_update’      => array( ‘id’, ‘is_donation’, ‘name’, ‘description’, ‘price’, ‘quantity’, ‘start_sales’, ‘end_sales’, ‘include_fee’, ‘min’, ‘max’, ‘hide’ ),

User

   ‘user_get’       => array( ‘user_id’, ’email’ ),

   ‘user_list_events’       => array( ‘user’, ‘do_not_display’, ‘event_statuses’, ‘asc_or_desc’ ),

   ‘user_list_organizers’     => array( ‘user’, ‘password’ ),

   ‘user_list_tickets’      => array(),

   ‘user_list_venues’      => array( ‘user’, ‘password’ ),

   ‘user_new’      => array( ’email’, ‘password’ ),

   ‘user_update’      => array( ‘new_email’, ‘new_password’ ),

Venue

   ‘venue_new’       => array( ‘organizer_id’, ‘venue’, ‘adress’, ‘adress_2’, ‘city’, ‘region’, ‘postal_code’, ‘country_code’ ),

   ‘venue_update’       => array( ‘id’, ‘venue’, ‘adress’, ‘adress_2’, ‘city’, ‘region’, ‘postal_code’, ‘country_code’ )

   );
App Key link:

http://www.eventbrite.com/myaccount/apps/

User Key:

https://www.eventbrite.com/userkeyapi

Sample File :

<?php

/**
 * File Name    : Test.php
 * Created by   : Amit Sabal
 * Created on   : 25th July 2015 
 * Motive       : To test the EventBrite API
 */

ini_set('display_errors',0);

/**
 * load the API Client library
 */ 
include "../Eventbrite.php"; 

/**
 * Authorization tokens are outlined here:
 * http://developer.eventbrite.com/doc/authorization/
 *
 * Creating object of the EventBrite Class
 */

$eb = new Eventbrite(
                    array(
                        'app_key'=>'EAMRSGJTCHNUMRIEEB',
                        'user_key'=>'1437540524147554554645'
                    )
                );

    try{
    
        /**
         * Docs on how to use the API's event_new method are located here:
         * http://developer.eventbrite.com/doc/events/event_new/
         */    
           
        // To create venue of the event
        $venueDetails = $eb->venue_new(
                                       array(
                                            'organizer_id' => '8331193967',
                                            'venue'        => 'Gopalan Mall',
                                            'adress'       => '3rd Floor',
                                            'adress_2'     => '',
                                            'city'         => 'Bangaluru',
                                            'region'       => 'Karnataka',
                                            'postal_code'  => '560018',
                                            'country_code' => 'IN',
                                        )
                                    );
        
        // Fetching the Venue ID
        $venue_id = $venueDetails->process->id;
          
        // To create the Event 
        $createEvent = $eb->event_new(
                                array(
                                    'title'        => 'Test Amit Event 3',
                                    'start_date'   => '2015-07-28 14:00:00',
                                    'end_date'     => '2015-07-30 22:00:00',
                                    'status'       => 'Live',
                                    'shareable'    => '1',
                                    'privacy'      => '1',                               
                                    'organizer_id' => '8331193967',
                                    'venue_id'     => $venue_id,
                                    //'custom_header' => '<img src="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" width="100%"/>'
                                    )
                                );
        
        // Fetching the newly created Event ID
        $event_id = $createEvent->process->id;
        
        
        // Update the existing Event based on the ID
        $eventUpdate = $eb->event_update(
                                            array(
                                                'event_id' => '17858523324',
                                                'title'    => 'First Test Event',                                              
                                            )
                                        );
        
        // To create the Ticket
        $ticketCreate = $eb->ticket_new(
                                        array(
                                            'event_id'     => $event_id,
                                            'is_donation'  => '0',
                                            'name'         => 'Confer',
                                            'description'  => 'this is the test ticket',
                                            'price'        => '0',
                                            'quantity'     => '10',
                                            'start_sales'  => '2015-07-01 14:00:00',
                                            'end_sales'    => '2015-07-30 22:00:00',
                                            'include_fee'  => '',
                                            'min'          => '',
                                            'max'          => '',
                                            'status'       => '1',
                                        )
                                    );
        
        // Fetching the Ticket ID
        $ticket_id = $ticketCreate->process->id;
        
       
        // Update the existing Ticket based on the Ticket ID
        // Still to test
        $ticketUpdate = $eb->ticket_update(
                                            array(
                                                'id'           => '37823530',
                                                'is_donation'  => '1',
                                                'name'         => 'Global Meet',
                                                'include_fee'  => '',
                                                'min'          => '',
                                                'max'          => '',
                                                'status'       => '1',
                                                'hide'         => '1',
                                            )
                                        );
        
        // Searching the Event based on the parameter passed.
        
        /**
        $eventSearch = $eb->event_search(
                                            array(
                                                'keywords'       => '',
                                                'category'       => '',
                                                'address'        => '',
                                                'city'           => '',
                                                'region'         => '',
                                                'postal_code'    => '560085',
                                                'country'        => '',
                                                'within'         => '',
                                                'within_unit'    => '',
                                                'latitude'       => '',
                                                'longitude'      => '',
                                                'date'           => '',
                                                'date_created'   => '',
                                                'date_modified'  => '',
                                                'organizer'      => '',
                                                'max'            => '',
                                                'count_only'     => '',
                                                'sort_by'        => '',
                                                'page'           => '',
                                                'since_id'       => '',
                                                'tracking_link'  => '',
                                            )
                                        );
        */
        // Still to test
        $eventSearch = $eb->event_search(
                                            array(
                                                'keywords'       => 'First',
                                                'category'       => '',
                                                'address'        => '',
                                                'city'           => '',
                                                'region'         => '',
                                                'postal_code'    => '',
                                                'country'        => '',
                                                'within'         => '',
                                                'within_unit'    => '',
                                                'latitude'       => '',
                                                'longitude'      => '',
                                                'date'           => '',
                                                'date_created'   => '',
                                                'date_modified'  => '',
                                                'organizer'      => '',
                                                'max'            => '',
                                                'count_only'     => '',
                                                'sort_by'        => '',
                                                'page'           => '',
                                                'since_id'       => '',
                                                'tracking_link'  => '',
                                            )
                                        );
        
        // To list the user events
        $events = $eb->user_list_events();    
        
    }catch( Exception $e){
        
        var_dump($e);
    }
?>
<h1>List User Events:</h1>
<?= Eventbrite::eventList( $events, 'eventListRow'); ?>

 

eventbrite.php

<?php
class Eventbrite {
/**
* Eventbrite API endpoint
*/
var $api_endpoint = “https://www.eventbrite.com/json/&#8221;;
var $auth_tokens;
var $api_url;

/**
* Eventbrite API key (REQUIRED)
* http://www.eventbrite.com/api/key/
* Eventbrite user_key (OPTIONAL, only needed for reading/writing private user data)
* http://www.eventbrite.com/userkeyapi
*
* Alternate authorization parameters (instead of user_key):
* Eventbrite user email
* Eventbrite user password
*/
function __construct( $tokens = null, $user = null, $password = null ) {
$this->api_url = parse_url($this->api_endpoint);
$this->auth_tokens = array();
if(is_array($tokens)){
if(array_key_exists(‘access_code’, $tokens)){
$this->auth_tokens = $this->oauth_handshake( $tokens );
}else{
$this->auth_tokens = $tokens;
}
}else{
$this->auth_tokens[‘app_key’] = $tokens;
if( $password ){
$this->auth_tokens[‘user’] = $user;
$this->auth_tokens[‘password’] = $password;
}
else {
$this->auth_tokens[‘user_key’] = $user;
}
}
}

function oauth_handshake( $tokens ){
$params = array(
‘grant_type’=>’authorization_code’,
‘client_id’=> $tokens[‘app_key’],
‘client_secret’=> $tokens[‘client_secret’],
‘code’=> $tokens[‘access_code’] );

$request_url = $this->api_url[‘scheme’] . “://” . $this->api_url[‘host’] . ‘/oauth/token’;

// TODO: Replace the cURL code with something a bit more modern –
//$context = stream_context_create(array(‘http’ => array(
// ‘method’ => ‘POST’,
// ‘header’ => “Content-type: application/x-www-form-urlencoded\r\n”,
// ‘content’ => http_build_query($params))));
//$json_data = file_get_contents( $request_url, false, $context );

// CURL-POST implementation –
// WARNING: This code may require you to install the php5-curl package
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$json_data = curl_exec($ch);
$resp_info = curl_getinfo($ch);
curl_close($ch);

$response = get_object_vars(json_decode($json_data));
if( !array_key_exists(‘access_token’, $response) || array_key_exists(‘error’, $response) ){
throw new Exception( $response[‘error_description’] );
}
return array_merge($tokens, $response);
}

// For information about available API methods, see: http://developer.eventbrite.com/doc/
function __call( $method, $args ) {
// Unpack our arguments
if( is_array( $args ) && array_key_exists( 0, $args ) && is_array( $args[0]) ){
$params = $args[0];
}else{
$params = array();
}

// Add authentication tokens to querystring
if(!isset($this->auth_tokens[‘access_token’])){
$params = array_merge($params, $this->auth_tokens);
}

// Build our request url, urlencode querystring params
$request_url = $this->api_url[‘scheme’].”://”.$this->api_url[‘host’].$this->api_url[‘path’].$method.’?’.http_build_query( $params,”,’&’);

// Call the API
if(!isset($this->auth_tokens[‘access_token’])){
$resp = file_get_contents( $request_url );
}else{
$options = array(
‘http’=>array( ‘method’=> ‘GET’,
‘header’=> “Authorization: Bearer ” . $this->auth_tokens[‘access_token’])
);
$resp = file_get_contents( $request_url, false, stream_context_create($options));
}

// parse our response
if($resp){
$resp = json_decode( $resp );
if( isset( $resp->error ) && isset($resp->error->error_message) ){
//echo $resp->error->error_message;
// throw new Exception( $resp->error->error_message );// Commented as it is giving error
}
}
return $resp;
}

/*
* Helpers:
*/
public static function OAuthLogin($auth_tokens, $get_token=’getAccessToken’, $save_token=’saveAccessToken’, $delete_token=’deleteAccessToken’){
$user = false;
$response = array();
# Attempt to authenticate this user using an access_token, if available
if(!isset($auth_tokens[‘access_token’])){
if(is_callable($get_token)){
$auth_tokens[‘access_token’] = $get_token();
}elseif(is_callable(array(‘self’,$get_token))){
$auth_tokens[‘access_token’] = self::$get_token();
}
}
if( isset($auth_tokens[‘access_token’]) ){
try{
// Example using an access_token to initialize the API client:
$eb = new Eventbrite(array(‘access_token’ => $auth_tokens[‘access_token’]));
$user = $eb->user_get()->user;
}catch(Exception $e){
$user = false;
// This token may no longer be valid
// refresh it, or clear it
$response[‘login_error’] = $e->getMessage();
if(is_callable($delete_token)){
$delete_token( $auth_tokens[‘access_token’] );
}elseif(is_callable(array(‘self’,$delete_token))){
self::$delete_token( $auth_tokens[‘access_token’] );
}
}
}

# We do not have a valid access token for this user so far
if( $user == false ){
# This user is not yet authenticated –
# it is their first visit,
# or they are returning with an access_code that we will exchange for an access_token,
# or they were redirected here after logout
if( isset($auth_tokens[‘access_code’]) ){
# This user has just authenticated, get their access token and store it
try{
$eb = new Eventbrite($auth_tokens );
$response[‘access_token’] = $eb->auth_tokens[‘access_token’];
// save this access_token for future use!
if(is_callable($save_token)){
$save_token( $response[‘access_token’] );
}elseif(is_callable(array(‘self’,$save_token))){
self::$save_token( $response[‘access_token’] );
}
header(‘Location: ‘ . $_SERVER[‘PHP_SELF’] );
exit;
}catch (Exception $e){
$response[‘login_error’] = $e->getMessage();
}
}else if( isset($auth_tokens[‘error_message’] )){
if($auth_tokens[‘error_message’] == ‘access_denied’){
$response[‘login_error’] = “Account access denied.”;
}else{
$response[‘login_error’] = $auth_tokens[‘error_message’];
}
}
}else if(is_object($user)){
$response[‘user_email’] = $user->email;
$response[‘user_name’] = $user->first_name . ‘ ‘ . $user->last_name;
}
return $response;
}

public static function widgetHTML( $params ){
// Replace this example with something that works with your Application’s templating engine
$html = ”

Hi.

Here is some information on how to change the SSH keys of an instance. This assumes that you have the current private key of the instance and can SSH into the instance. These steps will need to be taken on each of the instances for which you wish to change the SSH keys.

1. Generate a new keypair.

$ ec2-add-kepair my-keypair-name

2. Copy the output of this command and save it to a file named my-private-key.pem (or whatever name you choose) as described in http://docs.amazonwebservices.com/AWSEC2/2008-08-08/GettingStartedGuide/index.html?running-an-instance.html#connecting-to-an-instance. This is the private part of the SSH keypair.

3. You now need to get the public part of the keypair. You can do this in one of three ways:

a. The easiest way is to use the PuttyGen application to generate the public key file and to convert the private key into a Putty .ppk file. You can find the PuttyGen application here: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

b. Use the following command to regenerate the public ssh key from the private key:

$ ssh-keygen -y -f my-private-key.pem

c. Launch a completely new instance (not a replacement) using the new keypair to get the public key of your keypair from ~/.ssh/authorized_keys

4. SSH into the instance that you wish to update using your existing keypair.

5. Remove the old public key from ~/.ssh/authorized_keys

6. Add the new keypair’s public key to ~/.ssh/authorized_keys

7. Keep this existing SSH session open in case something went wrong with the above change. Open a new SSH session and try to login using the new private key file (my-private-key.pem). If you are using Putty and didn’t follow step 3.a, you will need to convert this .pem file to a .ppk file as described here http://docs.amazonwebservices.com/AWSEC2/2008-08-08/GettingStartedGuide/index.html?putty.html

You might find these tutorials on changing SSH keypairs helpful:

http://www.eng.cam.ac.uk/help/jpmg/ssh/authorized_keys_howto.html
http://www.networknewz.com/networknewz-10-20030707AuthenticatingbyPublicKeyOpenSSH.html

Alternatively, assuming that you have lost your key and also assuming that it’s an EBS backed instance, you can go to your instance in the AWS management console, right click your instance and choose ” launch more like this”. This time it will create a clone of your EC2 instance. You can specify a new key for this instance. Make sure you select the same security group.

This way, you will not loose your data and you will gain access to your ec2 instance with the new key.

Note: If your old instance had an Elastic IP then you will need to re-assign that EIP to new instance.

If your instance does not have EIP then you need to make sure you update your other instances with new private IP address or URL so that connectivity will not be broken.

If there are any EBS volumes attached to your previous instance then you will need to attach them to new instance.

Termination of the old instance can be done as a last step.

Please let me know if this helps you or if you still require further assistance.

Regards,

Create your own website, free on WordPress.com.Create your own website.
Start free