Friday, October 23, 2015

YAML Loader - Ruby

Sample YAML Loader:


Assume your yaml file 'email_credential.yml' exists in same directory and in the format below:

email:
  smtp_server: smtp.gmail.com
  smtp_port: 587


Here is the simple snippet to load YAML and collect data:

begin
  yml = YAML.load_file("email_credentials.yml")
  
  email = yml['email']['smtp_server']
  eport = yml['email']['smtp_port']
  
rescue Exception => e
  puts "Email credential YAML loading issue \n" + e.to_s
end

Website Monitor - Ruby Script

Simple Ruby Script file to check the web site and post an email using gmail service.

This script contains 2 main parts

  1. Checking website - for response OK and content
  2. Email to admin on failure [using gmail]

Checking Website:

    url = URI.parse(web_url)
  net_conn = Net::HTTP.new(url.host, url.port)
  net_conn.use_ssl = url.scheme == "https"
  res = net_conn.get('/')

   We can check res.code == 200 and verify res.body includes the content we wanted to see.

Email [Using gmail]

  NOTE: Gmail needs TLS encryption; so enable it before start sending msg
   
    smtp = Net::SMTP.new("smtp.gmail.com", 587)
    smtp.enable_starttls #gmail needs this encryption
    smtp.start("DOMAIN_FILLER", <gmail_acc>, <gmail_pwd>, :logindo |s| 
      s.send_message(<msg>, <gmail_acc>, <to>)
    end  

  Sample GMAIL Msg format:
   msg = [
    "From: WebMonitor <from_addr>",
    "To: Admin <to_addr>",
    "Subject: <subject>",
    "",
    "Hi,",
    "!!MORE DETAILED MSG!!"
  ].join("\r\n");


Gist: https://gist.github.com/sivajankan/8278d75c39bc5a8260ae

The script can be added to crontab to do automated testing

Thursday, August 20, 2015

Selenium - IE remote browser setup

Setup Selenium -  IE remote browser


  1. Install Java. If you are setting up from a base level testing VM, you may need to first install Java.
  2. Download following files from https://code.google.com/p/selenium/downloads/list into your windows machine (This page mostly has latest versions. Pick them)
    • a. selenium-server-standalone-2.39.0.jar
    • b. IEDriverServer _Win32_2.39.0.zip (There is version for 64 bit; pick appropriate version)
  3. Place the jar file and extracted exe file from zip, into C:\SeleniumServer folder
  4. In Command Prompt and navigate to 'C:\SeleniumServer'
  5. Run the command to start the standalone selenium server
java -jar selenium-server-standalone-2.35.0.jar -Djava.util.logging.Level=OFF -Dwebdriver.ie.driver="C:\SeleniumServer\IEDriverServer.exe"

Monday, July 6, 2015

Cap Deploy [Capistrano]

Capistrano

Ref:
http://capistranorb.com/
https://github.com/capistrano/ # Shows list of all capistrano repos
https://github.com/capistrano/capistrano
https://github.com/capistrano/rails
https://github.com/capistrano/passenger



Gemfile


gem 'capistrano'
gem 'capistrano-rails'
gem 'capistrano-passenger'
gem 'capistrano-rvm'  #if your preference is RVM



$> bundle install
$> bundle exec cap install #Make sure files are created
$> bundle exec cap install STAGES=production  #add additional env seperated by ','

Limited gem installation [selected env]
$> bundle install --without development test


Capfile


require 'capistrano/rails'

#or
require 'capistrano/rvm'
require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano/passenger'

#For rbenv
require 'capistrano/rbenv'
require 'capistrano/chruby'



Ref: http://capistranorb.com/documentation/getting-started/configuration/

config/deploy.rb


set :application, '<app_name>'
set :repo_url, 'git@.... <git repo>'

set :linked_files, fetch(:linked_files, []).push('config/database.yml')
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system')

set :keep_releases, 5



config/deploy/production.rb

server '<dest_server>', user: '<dest_server_user>', roles: %w{web db app}
set :deploy_to, "/var/www/html/<dir>"

set :passenger_restart_command, 'passenger-config restart-app'

set :passenger_restart_options, -> { "#{deploy_to} --ignore-app-not-running" }

Adding tasks

Ref: http://capistranorb.com/documentation/getting-started/cold-start/

in create lib/capistrano/tasks/access_check.rake file, and add

  namespace :check do
    desc "Check that we can access everything"
    task :write_permissions do
      on roles(:all) do |host|
        if test("[ -w #{fetch(:deploy_to)} ]")
          info "#{fetch(:deploy_to)} is writable on #{host}"
        else
          error "#{fetch(:deploy_to)} is not writable on #{host}"
        end
      end
    end
  end

$> bundle exec cap -T #to check the task existence
$> bundle exec cap production check:write_permissions #to verify the write permission


[Still working on Cap Scripting]

Basic Commands

cap production deploy:check
cap production deploy 
cap production deploy:rollback



Advance Comments [from capistrano Git page]


# list all available tasks
$ bundle exec cap -T

# deploy to the staging environment
$ bundle exec cap staging deploy

# deploy to the production environment
$ bundle exec cap production deploy

# simulate deploying to the production environment
# does not actually do anything
$ bundle exec cap production deploy --dry-run

# list task dependencies
$ bundle exec cap production deploy --prereqs

# trace through task invocations

$ bundle exec cap production deploy --trace


Advance Learning

https://github.com/capistrano/sshkit


Deploy issue with git

When you get: git stdout: permission denied (publickey).

$> eval $(ssh-agent)
$> ssh-add



Rails Life

Ruby Self Help Steps

Installation required Ruby setups!

http://code.tutsplus.com/tutorials/how-to-install-ruby-on-a-mac--net-21664
https://gorails.com/setup/osx/10.10-yosemite
http://railsapps.github.io/installrubyonrails-mac.html

Xcode installation if mac
RVM installation
Ruby installation
git installation
PostgreSQL or SQLite3


RVM Ruby version Preparation

rvm current #shows current default
rvm list #lists local installation

rvm get stable #get latest stable version
rvm reload # reload rvm
rvm list remote #all available to install
rvm install 2.2.5
rvm reinstall 2.2.0 --disable-binary

rvm --default use 2.1.5 #to make 2.1.5 as default

gem setup
$ echo 'gem: --no-document' >> ~/.gemrc

To create gemset
$ rvm use 2.2.1@gemset-2.2.1 --create

Install rails before the next step
$ gem install rails

Good start for first project
Ref: https://github.com/RailsApps/rails-composer/

#sudo gem install rails
rails new myapp -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb



#Standard way
$rails new <project_name>

use .ruby-version  file to specify ruby version for the project
Example: 2.2.1@gemset_2_2_1

rspec
https://relishapp.com/rspec/rspec-rails/docs/gettingstarted

in Gemfile, development and test section
gem "rspec-rails"

bundle install
rails generate rspec:install

Remember: rake db:test:prepare

rake spec #to run tests


Cucumber
in Gemfile - development 

gem 'cucumber-rails', :require => false
gem 'database_cleaner'

  
bundle install
rails generate cucumber:install


Haml

add
gem "haml-rails", "~> 0.9" #Check version from https://github.com/indirect/haml-rails


rails generate haml:application_layout convert

rake haml:erb2haml # to convert existing erb files to haml



Devise
Add gem "devise" in Gemfile 
bundle install

rails generate devise:install
Follow suggestions


Registeration Email issue

Google account access blocking
SMTPAuthenticationError

http://stackoverflow.com/questions/18124878/netsmtpauthenticationerror-when-sending-email-from-rails-app-on-staging-envir

Add gem 'sass-rails' in Gemfile





Pry
http://pryrepl.org/


pry -r ./config/environment.rb





Passenger for Rails : CentOS

System Info

CentOS Linux release 7.0.1406 (Core) 
3.7GB Memory 
50GB diskspace
DUAL Core - Intel(R) Xeon(R) CPU E5-2680 v2 @ 2.80GHz
X86_64 - Architecture

Ref: 
https://www.digitalocean.com/community/tutorials/how-to-use-capistrano-to-automate-deployments-getting-started
https://www.digitalocean.com/community/tutorials/how-to-setup-a-rails-4-app-with-apache-and-passenger-on-centos-6

Root access:
yum -y update
yum groupinstall -y 'development tools'
curl -L get.rvm.io | bash -s stable  
  -- didnt work; and suggested next step in error
  >gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

curl -L get.rvm.io | bash -s stable
source /etc/profile.d/rvm.sh 
rvm reload
rvm get stable
rvm requirements
rvm reload
rvm install 2.1 #installed 2.1.5p273
rvm --default use 2.1.5

CONTINUE
https://www.rosehosting.com/blog/install-ruby-on-rails-with-apache-and-passenger-on-centos-6/

install rvm for newuser


adduser newuser
passwd newuser 
usermod -G wheel newuser #pick a fair name for new user
visudo #uncomment next line
  #%wheel ALL=(ALL) NOPASSWD:ALL
vim /etc/ssh/sshd_config #add next line to avoid ssh access using new user name
  DenyUsers newuser
service sshd restart
su - newuser

sudo yum -y update
sudo yum -y install curl curl-devel httpd-devel httpd mod_ssl
sudo curl -L get.rvm.io | bash -s stable  

  gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
#then sudo curl -L get.rvm.io | bash -s stable  
rvm get stable
rvm reload
rvm install 2.1.5
rvm use 2.1.5 --default
vim ~/.gemrc #put following lines to avoid lot of ri doc installations

---
:backtrace: false
:benchmark: false
:bulk_threshold: 1000
:sources:
- http://rubygems.org/
- http://gemcutter.org
:update_sources: true
:verbose: true
gem:
  --no-document
  --no-ri
  --no-rdoc

gem install rails
gem install passenger
passenger-install-apache2-module #follow the suggestions


PostgreSQL Installation

CentOS

#Postgres installation
ref: https://wiki.postgresql.org/wiki/YUM_Installation
ref2: http://karolgalanciak.com/blog/2013/07/19/centos-6-4-server-setup-with-ruby-on-rails-nginx-and-postgresql/

#as root
vim /etc/yum.repos.d/CentOS-Base.repo
 #add following line into [base] and [updates] section
 exclude=postgresql*

yum localinstall http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-centos94-9.4-1.noarch.rpm
yum install postgresql94-server

yum install postgresql94 postgresql94-devel postgresql94-server postgresql94-libs postgresql94-contrib


Installation is complete: next setup
/usr/pgsql-9.4/bin/postgresql94-setup initdb
  #service postgresql-9.4 init db - failed
  #systemctl initdb postgresql-9.4.service - didnt work

chkconfig postgresql-9.4 on #postgres start on startup

#CONFIG 
vi /var/lib/pgsql/9.3/data/pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5


service postgresql-9.4 restart


#db setup
https://wiki.postgresql.org/wiki/First_steps

$>su - postgres
$>psql
psql>alter user postgres with password 'postgres-user-password';
psql>ctrl+d
exit

$> su - newuser #user in rails installation
$> psql postgres -U postgres #postgres password from previous step

psql>create user username with password 'secretPassword'; #username - new db account user
psql>create database testdb owner=username;


To delete postgres:
yum erase postgresql94*




Sunday, July 5, 2015

Git

Git server
http://git-scm.com/book/en/v2/Git-on-the-Server-Setting-Up-the-Server

cd ~

git config --global merge.ff false

mkdir repos
cd repos
mkdir ur_project.git
cd ur_project.git
git init --bare


Local machine

git remote add <urid>  git@your_ip:repos/ur_project.git
git remote -v


#To see the added url

git remote show origin


Git Cheat Sheet
ref: http://git.or.cz

Remember: git command --help

Global Git configuration is stored in $HOME/.gitconfig (git config --help)

Create
From existing data
cd ~/projects/myproject
git init
git add .

From existing repo
git clone ~/existing/repo ~/new/repo
git clone git://host.org/project.git
git clone ssh://you@host.org/proj.git

Show

Files changed in working directory
git status

Changes to tracked files
git diff

What changed between $ID1 and $ID2
git diff $id1 $id2

History of changes
git log

History of changes for file with diffs
git log -p $file $dir/ec/tory

Who changed what and when in a file
git blame $file

A commit identified by $ID
git show $id

A specific file from a specific $ID
git show $id:$file

All local branches
git branch

List remote
git remote -v

git remote --help


Git Repo Browser
git instaweb --httpd webrick

Log
git log
git reflog

Youtube video:
  https://www.youtube.com/watch?v=sevc6668cQ0


http://stackoverflow.com/questions/6565357/git-push-requires-username-and-password
A common mistake is cloning using the default (HTTPS) instead of SSH. You can correct this by going to your repository, clicking the ssh button left to the URL field and updating the URL of your origin remote like this:
git remote set-url origin git@github.com:username/repo.git

Monday, June 29, 2015

BeanShell - Java Scripting in Shell

BeanShell

  Ruby's IRB equivalent Java Scripting in console.

Home:
  http://www.beanshell.org/home.html


Get the latest beanShell jar file
   http://www.beanshell.org/download.html


To install as an extension place the bsh.jar file in your $JAVA_HOME/jre/lib/ext folder.

For Mac os: place the bsh.jar in /Library/Java/Extensions
( ~/Library/Java/Extensions for individual users)


CLASSPATH Update:
  unix:     export CLASSPATH=$CLASSPATH:bsh-xx.jar #update your bashrc
  windows:  set classpath %classpath%;bsh-xx.jar #update environment variables

NOTE: xx - should match you downloaded jar version


Start new Shell window

$ java bsh.Console # Starts bean console
$ java bsh.Interpreter   // run as text-only on the command line
$ java bsh.Interpreter filename [ args ] // run script file

Trial:
$ java bsh.Interpreter 
bsh %  int add(int a, int b) { return a+b;}
bsh % print(add(1,2)); //3

Manual
 http://www.beanshell.org/manual/bshmanual.html

Groovy Gears

Started from  http://www.groovy-lang.org/learn.html.

Decided to use GVM:

$ curl -s get.gvmtool.net | bash

  Installation went well; Updated bashrc and zshrc files.

  Started new shell window

$ gvm help # Showed help 

$ gvm install groovy #installed latest version

$ groovy -version # showed installed version


Create a (text) file hello_groovy
$ vim hello_groovy

Enter: System.out.println("Hello Groovy")
Save file

$ groovy hello_groovy #print "Hello Groovy"


Manual
http://www.vogella.com/tutorials/Groovy/article.html

Monday, May 25, 2015

Rails 4: Page Specific JS Load

To load JS files only on particular page:


1. Stop loading it globally
    In application.js file, stub (stop) loading the js file, you don't want to load.
 
    Example:
     //stub file_name


2. Add to Precompile
     Update config/initializer/assets.rb with following line to enable assets precompile.
      Rails.application.config.assets.precompile += %w( file_name.js )

     Rails throws 'AssetFilteredError', if the file is not precompiled.


3. Load JS file in specific folder
    Load the application JS and specific file JS where needed.
    Example:
      = javascript_include_tag 'application''data-turbolinks-track' => true
   = javascript_include_tag 'file_name''data-turbolinks-track' => true 




To call document ready for specific page:


1. Introduce new class to body or div of the page
2. Use jQuery selector for that class

Example:
  %div{"class": "_class_name"}


:javascript
   $("._class_name").on("ready", ready_function);
  

Monday, May 18, 2015

Mac iCal Shared Calendar (Exchange)

One liner:
iCal - Menu =>  'Preferences'  => 'Accounts' => 'Delegation'. Add accounts using the '+' sign in 'Accounts I can access'.

TLDR;

After a weekly MS Office update, MS Outlook stopped working in Mac 10.10.3 (Yosemite); Often it went to frozen mode, and every time I had to rebuild the using Microsoft Database Utility [Press alt(option) key and click on outlook icon to open DB utility]. This made me force to use the iCal.

Followed standard Exchange integration given by current outlook provider. But adding shared calendar was tricky with iCal 8.0.

To add Shared calendar, go to 'Preferences', then select 'Accounts' tab; then go to 'Delegation'; Add accounts using the '+' sign in 'Accounts I can access'.

The 'Accounts ...' and 'Add Account ..' options in iCal menu is kind of confusing when you try to access shared calendar with existing calendar account.


Tuesday, May 5, 2015

log4j - File & Format

Sample codes to configure log4j

General logger initialization

 Logger logger = Logger.getLogger(YourClass.class);

log4j.properties file sample (writes to file too)

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
#log4j.appender.stdout.layout.ConversionPattern=%d{DATE} %5p [%c]:%L - %m%n
#log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %5p [%c]:%L - %m%n
#Same as ISO8601
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.S Z} %5p [%c]:%L - %m%n
log4j.appender.stdout.Threshold=trace

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${user.dir}/you_log_file.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=trace, stdout, file



Additional file outputs [2 sample layouts]


//Load the file handler for the logger 1
Appender fh = new FileAppender(new SimpleLayout(),  workingDir + File.separator + logfile);
logger.addAppender(fh);
fh.setLayout(new SimpleLayout());


//Load the file handler for the logger 2
TTCCLayout logLayout = new TTCCLayout();
logLayout.setDateFormat("dd MMM yyyy HH:mm:ss,SSS");
Appender fh = new FileAppender(logLayout,  workingDir + File.separator + logfile);
logger.addAppender(fh);
fh.setLayout(logLayout);


More options available with 'Enhanced Pattern Layout' and 'Layout'

Ref:
http://www.mkyong.com/logging/log4j-log4j-properties-examples/
http://stackoverflow.com/questions/4474646/how-to-write-to-a-text-file-using-to-log4j

API:
https://logging.apache.org/log4j/1.2/apidocs/index.html


Thursday, April 30, 2015

Excel - Hyperlink - Tying to a cell

Lately one friend asked my help to figure out the way to use hyperlink to a specific cell in Excel Sheet; Which was easy after trying 4-5 options and 2 hours of Google search. So I decided to document it for future reference!

One liner:
  The technique is 'define the name' for the cell to be linked and use that 'defined name' in hyper link.

Ref:
http://excelribbon.tips.net/T006195_Tying_a_Hyperlink_to_a_Specific_Cell.html
http://www.k2e.com/tech-update/tips/418-tip-fastest-way-to-create-defined-names-in-excel

Before going on step by step, please find what is 'Name Box'. [courtesy link from http://blog.accountants.intuit.com/ways-to-be-more-productive/low-tech-excel-tips/]

Name box:


 The left most cell in 'Formula bar' is the Name Box. When you hover the Name Box cell, it shows 'Enter a name for a cell range, or select a named range from the list' [in MSOffice 2013]


Step by Step:

Create the Defined Name:
  1. Select the cell you want to be hyperlinked (to be jumped to). In the 'Name Box' [check the image above], enter a 'reference' name and press return key. [Assumed 'Reference1' for our example case]
Use the Defined Name in Hyperlink
  1. Go to the cell where you want to place the hyperlink (to be jumped from), right click and click on 'Hyperlink' from the menu
  2. In the 'Insert Hyperlink' popup window, in 'Anchor' ['Link to' for older version] section, click on 'locate'; which opens another popup window
  3. In the 'Select Place in Document' popup, expand the 'Defined Names' by clicking the small triangle [or + icon] next to it [make the triangle point down, or change + to -, by clicking], and select the reference you made in step 2. [Our example 'Reference1']


Now your hyperlink pointed to the reference; so inserting or deleting any rows or columns won't affect your hyperlink pointing cell location.


All the best!

Tuesday, April 21, 2015

Java Working Directory - Wrong GDD

Lately I spend almost a day, actually a whole day to figure out jar file running directory. Actually what I needed was 'System.getProperty("user.dir")'



Here is the function first I wrote which worked across Mac, Linux and Windows 8

private static String workingDirectory() {
  File currentJavaJarFile = new File(<any>Util.class
                            .getProtectionDomain()
                            .getCodeSource()
                            .getLocation()
                            .getPath());
  String currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath();
  String parentDir = currentJavaJarFile.getParent();
  String jarFilename = currentJavaJarFile.getName();
  parentDir = parentDir.toString().replace("\\", "\\\\"); //backslash directory separator error in windows
  String directory = currentJavaJarFilePath.replaceAll(parentDir.toString(), "").replace((File.separator + jarFilename), "");
  return directory;

Monday, April 13, 2015

OneJar - Cool Experience

Lately I had to build a executable jar with many other dependencies jars; Failed with 2 solutions, same as Simon Tuffs,  then I decided to use what he offered, the OneJar.


Here are the Steps used in Mac 10.10, Eclipse IDE 3.7

Ref: http://obscuredclarity.blogspot.com/2011/05/java-one-jar-example-using-ant-and.html


One time OneJar Load in IDE


  1. Downloaded one-jar-ant-task-0.97.jar
  2. Copied the file into /Applications/Eclipse/plugins
  3. In Eclipse IDE (3.7), Preferences -> Ant -> Runtime, in right side window, click on 'Ant Home Entries (Default)'; Then use 'Add External JARs...' to add the newly added one-jar-ant-task jar file.




Ant Build Changes

NOTE: Assuming the project build is successful, and you have to create the new exec bundled onejar

Copy and paste the follow code snippet to build onejar and execute the one jar file; Dont forget to edit main jar file location and lib jar file locations to fit the main Ant build


<taskdef name="one-jar" classname="com.simontuffs.onejar.ant.OneJarTask" onerror="report" />
  <target name="onejar" depends="jar">
    <!-- Construct the One-JAR file -->
    <one-jar destfile="${ant.project.name}Exec.jar">
      <manifest>
        <attribute name="One-Jar-Main-Class" value="${main-class}"/>
      </manifest>
      <main jar="${ant.project.name}.jar" />
      <lib>
        <fileset dir="${lib.dir}" />
      </lib>
      <fileset dir="${src.dir}" includes="log4j.properties"/>
    </one-jar>
  </target>

  <target name="run onejar" depends="onejar">
    <java jar="${ant.project.name}Exec.jar" fork="true" />
  </target>



Thanks Simon Tuffs!

Ant build xml in Gist

More Example: http://one-jar.cvs.sourceforge.net/viewvc/one-jar/one-jar-log4j/

Other Ref:
http://j2stuff.blogspot.com/2011/07/onejava-example.html


Monday, March 23, 2015

Windows 8.1 VM - Oracle Virtual Box

Build VM

  1. Collect your licensed windows iso [Used Window 8.1 iso image. Downloaded 3.65GB file locally]
  2. Start Oracle Virtual Box
  3. Click New in Oracle Virtual Box window
  4. Name: 'Windows_8_1'
  5. Type: Select 'Microsoft Windows' 
  6. Version: Pick 'Windows 8.1 (64 bit)'
  7. Memory size: pick 2048 [It is the default value picked for Windows 8.1. So leave it]
  8. Hard drive: Check 'Create a virtual hard drive now'
  9. Click 'Create'
  10. In next window, leave all default: File size: 25GB, Hard disk file type: 'VDI (VirtualBox Disk Image)', Storage on physical hard drive: 'Dynamically allocated'
  11. Click 'Create' in this window too
  12. Now, you can see 'Windows_8_1' vm image created with 'Powered Off' state
  13. Start the 'Windows_8_1' vm
  14. In popup window, pick the iso file downloaded in first step and click 'Start'
  15. It will go like regular Windows 8.1 installation
  16. Pick zonal setting - I left as it is!
  17. Click 'Install now' once prompted
  18. 'Accept' the license terms in 'Windows Setup' and click 'Next'
  19. Click on 'Custom: Install Windows only (advanced)'
  20. Select default 25GB harddrive and click 'Next'
  21. Let the process continue
  22. Let it restart and restart
  23. Once it is ready, give your pc name 'vm-pc'
  24. Use 'Express setting' on next level
  25. 'Create local account'
  26. Enter your credentials and Password/hints
  27. Finish - Your VM is ready. 
  28. Windows 8.1 does some app installs and entertain you with some screen color changes. Please don't fall that cleverness. Still it is windows!


Export for future use


  1. In Oracle VirtualBox, click File -> Export Appliance
  2. Select 'Windows_8_1' from 'Virtual machines to export' list, then click 'Continue'
  3. File: Update with correct file location and file name [Pick ova format in this window]
  4. Format: Pick OVF 2.0 
  5. Check 'Write Manifest file'
  6. Click 'Continue'
  7. In new dialog, check the options and leave as it is, click 'Export'
  8. This creates the VM image for future imports
  9. You can import the VM image to create new VM

Guest Additions


Ref: https://ludwigkeck.wordpress.com/2012/11/03/virtualbox-guest-additions-in-a-windows-8-virtual-machine/

Guest additions needed for seamless mode. Here is the steps I could use;


  1. In VirtualBox VM: Devices menu, select 'Insert Guest Additions CD Image (Host+D)'. It suppose to popup some dialog, which didnt show up. 
  2. Assume you didnt see any popups, in Windows 8.1 VM running instance, go to 'Explorer' and CD Drive
  3. Double click on VBoxWindowsAdditions(.exe) file and follow the basic installation with default setup
  4. At end of installation, select 'Reboot'
  5. After rebooting, you can use normal VM and Seamless mode too.



Connecting To Local Domain


  1. Right click on My Computers [For Windows 8.1, right click on desktop; In popup dialog click 'Change Desktop Icon'; In the following 'Desktop Icon Settings' dialog, check 'Computer' to show 'My Computer' in desktop. Pick other icons if needed], then select 'Properties'.
  2. In 'System' dialog window, click 'Advance system settings'.
  3. In 'System Properties' dialog, select 'Computer Name' tab
  4. Click the 'Change' icon to change computer domain/workgroup
  5. In bottom, 'Member of' section, check 'Domain' radio button, then fill the your local domain name [Check with your IT]
  6. Depends your domain setup, you may prompted to enter user id and password; and possible restart too.
  7. After restart, instead of login as default system user, click '<-' left arrow and select 'Other user'
  8. Now, you see user name and password field and 'Sign in to:' DOMAIN name
  9. Use your local domain account to login; Now your new domain profile is created in VM!









Thursday, March 19, 2015

Oracle PL/JSON - Installation

Had good great experience with PL/JSON for a year; Here the steps I followed to install PL/JSON into my oracle 12C DB.

Installation


  1. Got PL/JSON from GitHub using git clone
  2. Opened 'install.sql' file in SQLDeveloper and selected the DB connection to run the release
  3. Used 'Run Script' option from SQLDeveloper. 
  4. Watched 'Script Output' for no errors


Test


  1. Opened another 'SQL WorkSheet' and copy and pasted the Example-1 and executed the Script. 
  2. In Script output, verified the JSON data print.


Friday, March 6, 2015

Oracle 12C VM & SqlPlus InstantClient setup

VM Setup:

Really handy helpful tips: http://www.thatjeffsmith.com/archive/2014/02/introducing-the-otn-developer-day-database-12c-virtualbox-image/

VM Image download: http://www.oracle.com/technetwork/database/enterprise-edition/databaseappdev-vm-161299.html


Once you downloaded 5.6GB VM image, use import in Oracle Virtual Box. It might 2GB memory and 1GB disk space. It has default port forwarding setup. After import, start the VM and you can test your application with SQLDeveloper in VM itself (Already configured). 

 The connection params: 
     Username: system
  Password: oracle
  Hostname: localhost or 127.0.0.1
  Port: 1521
  Service name: orcl or cdb1


  NOTE: PDB1 setting didnt work for me (on March 6, 2015)
     PDB1 credentials suggested
  Username: HR
  Password: oracle
  Hostname: localhost or 127.0.0.1
  Port: 1521
  Service name: PDB1


   In VM service, you can use sqlplus to access Oracle DB. Use 'sqlplus sys as sysdba' or 'sqlplus system@orcl' with password 'oracle' to access.

Challenge: 
   Getting alert for password expiry in 7 days; While trying to password change with 'alter user system container=all identified by oracle;', getting following error: 'SQL Error: ORA-65050: Common DDLs only allowed in CDB$ROOT'.

Fix:
 In SQLDeveloper, login using system/oracle, 127.0.0.1:1521, service name: cdb1, run `alter user system identified by oracle container=all;`. It fixes the issue.


SQLPlus in local machine

Ref: http://www.talkapex.com/2013/03/oracle-instant-client-on-mac-os-x.html

Download all instantclient zip files. Unzip them and move the 'instantclient_11_2' into '/oracle' folder. Create '/oracle/instantclient_11_2/network/admin/tnsnames.ora' and following lines

localvm =
 (description=
   (address_list=
     (address = (protocol = TCP)(host = 127.0.0.1)(port = 1521))
   )
 (connect_data = (server=DEDICATED)(service_name=orcl))
)

Note: If you have to map more than one tns, don't seperate them with ','.


Set path and export following in ~/.bash_profile

#Oracle tools
ORACLE_HOME=/oracle/instantclient_11_2
export ORACLE_HOME
LD_LIBRARY_PATH=$ORACLE_HOME
export LD_LIBRARY_PATH
DYLD_LIBRARY_PATH=$ORACLE_HOME
export DYLD_LIBRARY_PATH
SQLPATH=$ORACLE_HOME
export SQLPATH
TNS_ADMIN=$ORACLE_HOME/network/admin
export TNS_ADMIN
PATH=$PATH:$ORACLE_HOME:.
export PATH


 Open new terminal. You can connect your vm Oracle 12C DB using sqlplus, by typing 'sqlplus system@//localhost:1521/orcl' or 'sqlplus system@localvm' with 'oracle' password.

More sqlplus help: http://dba.fyicenter.com/faq/oracle/Main-Features-of-SQL-Plus.html

SSH

 ConfigureVM network with (HOST) 127.0.0.1:2222 to GUEST 22 port. You can use 'ssh oracle@localhost -p 2222' to login with 'oracle' password.


For Ruby Dev:


In terminal:

cd /oracle/instantclient_11_2
sudo ln -s libclntsh.dylib.11.1 libclntsh.dylib
sudo ln -s libocci.dylib.11.1 libocci.dylib
gem install ruby-oci8

Make sure gem installed without errors; Use 'irb' to check your connection

>require 'oci8'
>conn = OCI8.new('system', 'oracle', 'localvm') 
#OCI8.new('<user>', '<password>', '<tnsmap>')
>conn.exec("select 'string' from dual") {|r| puts r}
#prints string


SQL Developer:


To load tnsnames.ora

Preference -> Database -> Advanced -> Tnsnames Directory (Browse and load tnsnames.ora directory)

NLS (National Language Support)

Preference -> Database -> NLS -> Change setting or keep it default by selecting 'skip NLS Settings'