Taking baby steps in Lisp

Lisp can be both fascinating and frustrating. Fascinating, because you can write compact code to solve really complex problems. Frustrating, because you can easily get lost in its maze of parentheses. I, for one, have been truly smitten by Lisp. My initial encounter with Lisp did not yield much success as I tried to come to terms with its strange syntax. The books I read on the Lisp language typically gloss over the exotic features of Lisp like writing Lisp code to solve the Towers of Hanoi or the Eight Queens problem. They talk about functions returning functions, back quotes and macros that can make your head spin.

I found this approach extremely difficult to digest the language. So I decided to view Lisp through the eyes of any other regular programming language like C, C++,, Java, Perl, Python or Ruby. I was keen on being able to do regular things with Lisp before I try out its unique features. So I decided to investigate Lisp from this view point and learn how to make Lisp do mundane things like an assignment, conditional, loop, array, input and output etc.

This post is centered on this fact.

Assignment statement

The most fundamental requirement for any language is to perform an assignment. For e.g. these are assignment statements in Lisp and its equivalent in C for e.g.

$ (setf x 5)                                                         -> $ x = 5
$ (setf x (+  (* y 2) (* z 8))                               -> $x = 2y + 8z

Conditional statement
 
There are a couple of forms of conditional statement in Lisp. The most basic is the ‘if’ statement which is special case. You can do if-then-else without the possibility of if-then-else if-else if – else

if (condition) statement else-statement

In Lisp this is written as
$(setf x 5)
$ (if (= x 5)
(setf x  (+ x 5))
(setf  (- x 6)))
10

In C this equivalent to
$ x = 5
$ if (x == 5)
x = x + 5;
else
x = x -6;

However Lisp allows the if-then-else if – else if –else through the use of the COND statement

So we could write

$ (setf x 10)
$ (cond ((< x 5) (setf x (+ x 8)) (setf y (* 2 y)))
((= x 10) (setf x (* x 2)))
(t (setf x 8)))
20

The above statement in C would be
$ x = 2
$ y = 10
$ if (x < 5)
{
x = x + 8;
y = 2 * y;
}
else if (x == 10)
{
x = x * 2;
}
else
x = 8;

Loops
Lisp has many forms of loops dotimes, dolist, do , loop for etc. I found the following most intuitive and best to get started with
$  (setf x 5)
$ (let ((i 0))
(loop
(setf y (* x i))
(when (> i 10) (return))
(print i) (prin1 y)
(incf i
)))

In C this could be written as
$ x = 5
(for i = 0; i < 10; i++)
{
y = x * i
printf(“%d %d\n”,i,y);
}

Another easy looping construct in C is
(loop for x from 2 to 10 by 3
do (print x))
In C this would be
(for x=2; x < 10; x = x+3)
print x;

Arrays
To create an array of 10 elements with initial value of 20
(setf numarray (make-array 10 :initial-element 20))
#(20 20 20 20 20 20 20 20 20 20)
To read an array element it is
$ (aref  numarray 3)                    – – – > numarray[3]
For e.g.
(setf x (* 2 (aref numarray 4)))     – – – – > x = numarray[4] * 2

Functions
(defun square (x)
(* x x))
This is the same as

int square (x)
{
return (x * x)
}

While in C you would invoke the function as
y = square (8)

In Lisp you would write as
(setf y (square 8))

Note: In Lisp the function is invoked as (function arg1 arg2… argn) instead of (function (arg1 arg2  … argn))

Structures
a) Create a global variable *db*
(defvar *db* nil)
 

b) Make a function to add an employee
$(defun make-emp (name age title)
(list :name name :age age :title title))
$(add-emp (make-emp “ganesh” 49 “manager”))
$(add-emp (make-emp “manish” 50 “gm”))
$(add-emp (make-emp “ram” 46 “vp”))
$ (dump-db)

For a more complete and excellent post on managing a simple DB looks at Practical Common Lisp by Peter Siebel

Reading and writing to standard output
To write to standard output you can use
(print “This is a test”) or
(print ‘(This is a test))
To read from standard input use
(let ((temp 0))
(print ‘(Enter temp))
(setf temp (read))
(print (append ‘(the temp is) (list temp))))

Reading and writing to a file
The typical way to do this is to use

a) Read
(with-open-file (stream “C:\\acl82express\\lisp\\count.cl”)
(do ((line (read-line stream nil)
(read-line stream nil)))
((null line))
(print line)))

b) Write
(with-open-file (stream “C:\\acl82express\\lisp\\test.txt”
:direction :output
:if-exists :supersede)
(write-line “test” stream)
nil)

I found the following construct a lot easier
(let ((in (open “C:\\acl82express\\lisp\\count.cl” :if-does-not-exist nil)))
(when in
(loop for line = (read-line in nil)
while line do (format t “~a~%” line))
(close in)))

With the above you can get started on Lisp. However with just the above constructs the code one writes will be very “non-Lispy”. Anyway this is definitely a start.

Find me on Google+

Experiences with VMWare Workstation 8.0.3 – The good,bad and the ugly

VMs( virtual machines) are the fundamental unit of the cloud. So I was interested in getting my hands around virtualization and virtual machines. Fortunately VMWare’s Workstation provides you with the opportunity. VMWare gives the user a 30 day evaluation license to evaluate Workstation 8.0.3. So I downloaded VMWare’s Workstation 8.0.3 to my desktop in Windows XP. If you had read my earlier post “Installing and configuring Fedora 16 with Windows XP using a bootable USB”  I had a dual boot desktop running either XP or Fedora 16.

Installing and getting Workstation 8.0.3 started was a breeze. I then created a VM using the Fedora 16 ISO file which I had downloaded for creating the dual boot Fedora & XP. The Workstation created a VM for me in a couple of minutes. As before the VM running Fedora 16 has LiveCD in its top right corner. Or in other words it is running the OS of a virtual CD. Anyway it was great and seemed really easy to get started.

The Ugly: I wanted to do more things with the VM. I read up the documentation on “Using the WorkStation” etc.  I wanted to install the VMWare Tools, clone a VM, save a snapshot etc. When I tried to install Vmware Tools I got a message saying the CDRom was in use. I checked the setting and found the CDRom was being used to boot Fedora. I actually needed to “install to disk”. .  As in previous post I decided I needed to create free space. Unfortunately I got ahead of myself I think. While the workstation was running I tried to access Windows Disk Management. This took a long time and I also got a message saying that the device was busy. As an afterthought it appears perfectly reasonable as the Workstation must have allocated space for the VM on the disk and must have held the disk. My disk had a primary partition C: drive with Win XP, a free logical drive D: and a partition holding my Fedora 16. I foolishly deleted drive D: This is where all hell broke loose. This took a long time. When I opened Disk Management again I found that the values it was showing was out of whack. It was C: drive 1820 GB when it should have been 70GB. D:drive as 2087 GB and also sorts vague figures. I realized that I had messed up my disk.

 

Here a thought struck me. Maybe if I restart the system the OS will work things out. But alas when I rebooted I got this

error: No such partition

grub rescue>

I knew I had really messed up. I could not boot my system. As I had mentioned before I could not boot Windows from my CD drive as it did not work. After trying a couple of different things I tried to boot with my USB drive.

Thank God I was able to boot Fedora. I then used fdisk to see my partitions. I realized I had clobbered my 2nd partition which was showing an incorrect size. I used fdisk to set the size right. I then installed Fedora 16 on my PC by writing to disk. Unfortunately I lost my XP drive and I was left with a Linux only PC. Thanks to my fortune there was no data that I had lost. This was a new PC which I had got.

The Bad: Now with Fedora 16 up and running I decided I thought I will try to install Workstation 8.0.3 on Fedora 16. I downloaded Workstation 8.0.3 bundle and extracted it. But when it tried to run it I ran into my 1st problem.

Cannot load module pk-gtk-module & canberra-gtk-module and I also got a message “Failed”

So with some googling I found that I needed to do

yum install PackageKit-gtk-module &

yum install libcanberra-gtk2 libcanberra-gtk3 libcanberra-gtk2.i686 libcanberra-gtk3.i686

I also got the message that some kernel files needed to be compiled. When I went and checked

/lib/modules/3.1.0-7.fc16.i686 I founf that the “build” link was broken.  So I set off on another google search on how to fix the fedora build broken situation. Finally I found the answer here

http://www.linuxquestions.org/questions/linux-newbie-8/broken-link-fedora-build-rpmtree-does-not-exist-520474/

I did a

yum install kernel-devel

As mentioned in the link above I rebooted the system. This seemed to create

/lib/modules/3.3.7-1.fci6.686.

The build in this directory was fine. Also giving uname -a showed that the kernel was updated to the new version.

I tried to start the Workstation 8.0.3 again. Now the number of complaints was less. I got a message saying the files needed to be compiled. When I clicked ok it went through the compilation process. I knew I was making progress. But anyway it once again bailed out with

Gtk-Message: Failed to load module “pk-gtk-module”: libpk-gtk-module.so: cannot open shared object file: No such file or directory

Gtk-Message: Failed to load module “canberra-gtk-module”: libcanberra-gtk-module.so: cannot open shared object file: No such file or directory

It appears that there is a patch which needs to be applied to fix the kernel. I used the following from this post

http://communities.vmware.com/thread/343441/

I downloaded workstation-8.0.2-linux3.2patch (15K) and ran the commands

cd /usr/lib/vmware/modules/source

tar xfv vmnet.tar

patch -p0 < ~/workstation-8.0.2_linux-3.2.patch

tar cfv vmnet.tar vmnet-only/

vmware-modconfig –console –install-all

Though my workstation 8.0.3 this went through fine.

I also did

LD_LIBRARY_PATH=/usr/lib/gtk-2.0/modules

export LD_LIBRARY_PATH

I started the workstation 8.0.3 and lo and behold it finally came up.

I then downloaded Fedora 17 ISO file (http://fedoraproject.org/en/get-fedora-options( and created a VM with that. My PC with about ~ 1G ram groaned. It tool nearly 20 mins to be up and running.

The searching and fixing took me nearly 7 – 8 hours. I was finally able to get workstation 8.0.3 up and running with Fedora 17 VM

Also do take a look at  the good part of  VMWare Workstation 8.0.3 Sneak preview of Windows 8 with VMWare Workstation 8.0.3

Find me on Google+

Installing and configuring a dual boot Fedora 16 with Windows XP using a bootable USB

Here the steps to create a  dual boot of Fedora 16 with Windows XP using a bootable USB. I was forced to install from a USB as my DVD/CD drive had other ideas and wouldn’t read my Fedora 16 DVD.

Anyway creating a dual boot option with a USB was fairly straightforward.  I have outlined the steps below

1)       Download an image of Fedora 16 based on your hardware architecture. I downloaded Fedora 16 (Fedora-16-i686-Live-Desktop .iso) from this site http://fedoraproject.org/get-fedora

2)       Next download and install the LiveUSB creator from https://fedorahosted.org/liveusb-creator/

3)       Insert your USB stick into a USB slot.

4)       Run the LiveUSB creator. This will detect your USB stick. (It is possible to skip step 1 and have the LiveUSB creator download the Fedora 16 image but I was getting a SHA error. So it is better to go through Step 1)

5)       In the LiveUSB Creator window, click browse and open your downloaded ISO image, Fedora-16-i686-Live-Desktop .iso. Set the persistent storage to around 750 MB and then click create USB

6)       This will verify your download and create a bootable USB stick for you.

7)       At this point you would have to do the following. For a dual boot option you need to create free space on your disk on which you can install your Fedora 16.So I did the following. I had a primary partition C drive with 70GB and an extended partition with the logical drive D. Fortunately my PC had no data. So I deleted the D drive and then created an extended partition with 35 GB and left around 35 GB of free space.

8)       Now restart your PC. Before it boots hit F2 so that you get the BIOS setting.

9)       Go to the “boot” tab and choose Boot from USB and click Enable. Save your settings with F10.

10)   With your USB still in the USB slot the PC will continue to boot but will do so from the USB stick

11)   The system will continue to Boot. Select Start Fedora 16. The right corner should show LiveCD

12)   Click Applications. You should see “Install to hard drive”

13)   Click this. At this point please see these 2 links as they have many screen shots for configuring Fedora 17

http://www.howtoforge.com/the-perfect-desktop-fedora-16-i686-gnome

http://www.if-not-true-then-false.com/2011/fedora-16-verne-install-guide-with-screenshots/

14)   I followed these links except the step “Installation Type”. Here I chose the 4th Option “Use Free space” which I had created for 35 GB. This does not touch your data & files.

15)   In the Select Storage devices make sure you choose the “Data Storage device” (your free space) and move it right to “Install target devices”

16)   You will get a Confirm changes to disk popup. Choose write changes to disk.

17)   The installation will start and will install your Fedora 16.

18)   You can then set system time, create users etc.

19)   Your Fedora 16 installation is now ready.

20)   You might want to restart the system. You will see now options to either boot from Fedora 16 or Windows XP.

I would suggest that you select F2, go to the boot tab and disable the boot from USB first option. Now you have a dual boot option Fedora 16 or Windows XP.

Note: I personally did not like the default desktop which Fedora 16 provides. For one the terminal window does not have a minimize, maximize and close icons on the title bar. Also the Window/Application is pain. If you want the default desktop interface this is what you have to do.

Click the username on the top right corner of the Fedora 16 Click System Settings, scroll down to System Info. Select Graphics and set Forced Fallback Mode to “On”. Log out and log in and hey presto , all terminal windows have the the icons properly and the desktop has the older menu style.

Find me on Google+

Powershell GUI – Adding bells and whistles

In my previous post “Getting your feet wet with Powershell GUI” I had mentioned how difficult it was get a concise documentation on creating Powershell GUI. To my surprise I discovered that there is a real cool tool developed by Sapien Technologies that allows you to create a Powershell GUI. They have a free Powershell Form creator – Primal Forms Community Creator” which enables you to create a nifty GUI. I was able to create a neat Form and then fill in the details of actually manipulating the controls I added. For details about the controls of a textBox, comboBox etc in Powershell refer to the MSDN library. This was the Powershell GUI I had created.

I have included the code below to execute some basic commands

Note: You can clone the code below from GitHub : Creating a GUI in powershell

#########################################################################################################
# Developed by Tinniam V Ganesh
# Date 24 Apr 2012
# Powershell GUI generated by Primal Forms CE from Sapien Technologies (http://www.sapien.com/)
#########################################################################################################
function Get-SysInfo ($strComputer)
{
write-host “reached here”
$statusBar1.Text =”Working …”
if ($radiobutton1.checked -eq $True)
{
$wmi = Get-WmiObject Win32_ComputerSystem -Namespace “root\CIMV2″ -ComputerName $strComputer|Export-csv -force “test.csv”
}
else
{
$wmi =Get-WmiObject Win32_ComputerSystem -Namespace “root\CIMV2″ -ComputerName $strComputer|ConvertTo-Html|out-file -append “test.html”
}

$statusBar1.Text =”Done.”
}

#*=============================================================================
Function Get-BIOSInfo ($strComputer)
{
$statusBar1.Text =”Working …”
if ($radiobutton1.checked -eq $True)
{
$wmi = Get-WmiObject Win32_BIOS -Namespace “root\CIMV2″ -computername $strComputer|Export-csv -force “test.csv”
}
else
{
$wmi = Get-WmiObject Win32_BIOS -Namespace “root\CIMV2″ -computername $strComputer|ConvertTo-Html|out-file -append “test.html”
}

$statusBar1.Text =”Done.”
}

Function Get-OSInfo {
$statusBar1.Text =”Working …”
if ($radiobutton1.checked -eq $True)
{
$wmi = Get-WmiObject Win32_OperatingSystem -Namespace “root\CIMV2″ -Computername $strComputer|Export-csv -force “test.csv”
}
else
{
$wmi = Get-WmiObject Win32_OperatingSystem -Namespace “root\CIMV2″ -Computername $strComputer|out-file -append “test.html”
}

$statusBar1.Text =”Done.”
}

Function Get-CPUInfo {

$statusBar1.Text =”Working …”
if ($radiobutton1.checked -eq $True)
{
$wmi = Get-WmiObject Win32_Processor -Namespace “root\CIMV2″ -Computername $strComputer|Export-csv -force “test.csv”
}
else
{
$wmi = Get-WmiObject Win32_Processor -Namespace “root\CIMV2″ -Computername $strComputer|out-file -append “test.html”
}

$statusBar1.Text =”Done.”
}

Function Get-DiskInfo {

$statusBar1.Text =”Working …”
if ($radiobutton1.checked -eq $True)
{
$wmi = Get-WmiObject Win32_DiskDrive -Namespace “root\CIMV2″ -ComputerName $strComputer|Export-csv -force “test.csv”
}
else
{
$wmi = Get-WmiObject Win32_DiskDrive -Namespace “root\CIMV2″ -ComputerName $strComputer|out-file -append “test.html”
}

$statusBar1.Text =”Done.”
}

Function Get-NetworkInfo {

$statusBar1.Text =”Working …”
if ($radiobutton1.checked -eq $True)
{
$wmi = Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace “root\CIMV2″ -ComputerName $strComputer | where{$_.IPEnabled -eq “True”}|Export-csv -noclobber “test.csv”
}
else
{
$wmi = Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace “root\CIMV2″ -ComputerName $strComputer | where{$_.IPEnabled -eq “True”}|out-file -append “test.html”
}

$statusBar1.Text =”Done.”
}

#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 4/24/2012 2:46 PM
# Generated By: tvganesh
########################################################################

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname(“System.Windows.Forms”) | Out-Null
[reflection.assembly]::loadwithpartialname(“System.Drawing”) | Out-Null
#endregion

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$statusBar1 = New-Object System.Windows.Forms.StatusBar
$label2 = New-Object System.Windows.Forms.Label
$button3 = New-Object System.Windows.Forms.Button
$button2 = New-Object System.Windows.Forms.Button
$tabControl1 = New-Object System.Windows.Forms.TabControl
$tabControl = New-Object System.Windows.Forms.TabPage
$groupBox1 = New-Object System.Windows.Forms.GroupBox
$radioButton2 = New-Object System.Windows.Forms.RadioButton
$radioButton1 = New-Object System.Windows.Forms.RadioButton
$label1 = New-Object System.Windows.Forms.Label
$textBox1 = New-Object System.Windows.Forms.TextBox
$comboBox1 = New-Object System.Windows.Forms.ComboBox
$Database = New-Object System.Windows.Forms.TabPage
$tabPage1 = New-Object System.Windows.Forms.TabPage
$tabPage2 = New-Object System.Windows.Forms.TabPage
$button1 = New-Object System.Windows.Forms.Button
$fontDialog1 = New-Object System.Windows.Forms.FontDialog
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#———————————————-
#Generated Event Script Blocks
#———————————————-
#Provide Custom Code for events specified in PrimalForms.
$button3_OnClick=
{
$form1.Close()

}

$button2_OnClick=
{
$textBox1.text=””
# Set to the first item
$comboBox1.SelectedIndex = 0;

}

$handler_button1_Click=
{
$x = $textbox1.text
$vals = $x.split(“,”)
forEach($strComputer in $vals)
{
switch($combobox1.selectedItem)
{
“SysInfo” {Get-SysInfo ($strComputer)}
“BiosInfo” {Get-BiosInfo($strComputer)}
“CPUInfo” {Get-cpuInfo($strComputer)}
“DiskInfo” {Get-diskInfo($strComputer)}
“OSInfo” {Get-OSInfo($strCOmputer)}
“NetworkInfo” {Get-NetworkInfo($strComputer)}
}
}
}

$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}

#———————————————-
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 444
$System_Drawing_Size.Width = 704
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Name = “form1”
$form1.Text = “Primal Form”

$statusBar1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 422
$statusBar1.Location = $System_Drawing_Point
$statusBar1.Name = “statusBar1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 22
$System_Drawing_Size.Width = 704
$statusBar1.Size = $System_Drawing_Size
$statusBar1.TabIndex = 8
$statusBar1.Text = “Ready”

$form1.Controls.Add($statusBar1)

$label2.DataBindings.DefaultDataSourceUpdateMode = 0
$label2.Font = New-Object System.Drawing.Font(“Microsoft Sans Serif”,14.25,1,3,1)

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 205
$System_Drawing_Point.Y = 22
$label2.Location = $System_Drawing_Point
$label2.Name = “label2”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 34
$System_Drawing_Size.Width = 341
$label2.Size = $System_Drawing_Size
$label2.TabIndex = 7
$label2.Text = “Windows Resource Management”

$form1.Controls.Add($label2)
$button3.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 439
$System_Drawing_Point.Y = 343
$button3.Location = $System_Drawing_Point
$button3.Name = “button3”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$button3.Size = $System_Drawing_Size
$button3.TabIndex = 6
$button3.Text = “Exit”
$button3.UseVisualStyleBackColor = $True
$button3.add_Click($button3_OnClick)

$form1.Controls.Add($button3)
$button2.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 330
$System_Drawing_Point.Y = 343
$button2.Location = $System_Drawing_Point
$button2.Name = “button2”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$button2.Size = $System_Drawing_Size
$button2.TabIndex = 5
$button2.Text = “Cancel”
$button2.UseVisualStyleBackColor = $True
$button2.add_Click($button2_OnClick)

$form1.Controls.Add($button2)

$tabControl1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 136
$System_Drawing_Point.Y = 83
$tabControl1.Location = $System_Drawing_Point
$tabControl1.Name = “tabControl1”
$tabControl1.SelectedIndex = 0
$tabControl1.ShowToolTips = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 231
$System_Drawing_Size.Width = 453
$tabControl1.Size = $System_Drawing_Size
$tabControl1.TabIndex = 4

$form1.Controls.Add($tabControl1)
$tabControl.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 4
$System_Drawing_Point.Y = 22
$tabControl.Location = $System_Drawing_Point
$tabControl.Name = “tabControl”
$System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
$System_Windows_Forms_Padding.All = 3
$System_Windows_Forms_Padding.Bottom = 3
$System_Windows_Forms_Padding.Left = 3
$System_Windows_Forms_Padding.Right = 3
$System_Windows_Forms_Padding.Top = 3
$tabControl.Padding = $System_Windows_Forms_Padding
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 205
$System_Drawing_Size.Width = 445
$tabControl.Size = $System_Drawing_Size
$tabControl.TabIndex = 0
$tabControl.Text = “Basic Commands”
$tabControl.UseVisualStyleBackColor = $True

$tabControl1.Controls.Add($tabControl)

$groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 271
$System_Drawing_Point.Y = 123
$groupBox1.Location = $System_Drawing_Point
$groupBox1.Name = “groupBox1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 49
$System_Drawing_Size.Width = 124
$groupBox1.Size = $System_Drawing_Size
$groupBox1.TabIndex = 3
$groupBox1.TabStop = $False
$groupBox1.Text = “Save As”

$tabControl.Controls.Add($groupBox1)

$radioButton2.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 48
$System_Drawing_Point.Y = 19
$radioButton2.Location = $System_Drawing_Point
$radioButton2.Name = “radioButton2”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 104
$radioButton2.Size = $System_Drawing_Size
$radioButton2.TabIndex = 1
$radioButton2.TabStop = $True
$radioButton2.Text = “HTML”
$radioButton2.UseVisualStyleBackColor = $True

$groupBox1.Controls.Add($radioButton2)
$radioButton1.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 19
$radioButton1.Location = $System_Drawing_Point
$radioButton1.Name = “radioButton1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 104
$radioButton1.Size = $System_Drawing_Size
$radioButton1.TabIndex = 0
$radioButton1.TabStop = $True
$radioButton1.Text = “CSV”
$radioButton1.UseVisualStyleBackColor = $True
$radioButton1.checked =$True

$groupBox1.Controls.Add($radioButton1)
$label1.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 26
$label1.Location = $System_Drawing_Point
$label1.Name = “label1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 192
$label1.Size = $System_Drawing_Size
$label1.TabIndex = 2
$label1.Text = “Enter comma separated server list”

$tabControl.Controls.Add($label1)

$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 220
$System_Drawing_Point.Y = 26
$textBox1.Location = $System_Drawing_Point
$textBox1.Name = “textBox1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 203
$textBox1.Size = $System_Drawing_Size
$textBox1.TabIndex = 1

$tabControl.Controls.Add($textBox1)

$comboBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$comboBox1.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 220
$System_Drawing_Point.Y = 79
$comboBox1.Location = $System_Drawing_Point
$comboBox1.Name = “comboBox1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 200
$comboBox1.Size = $System_Drawing_Size
$comboBox1.TabIndex = 0

$commands = @(“SysInfo”,”BIOSInfo”,”OSInfo”,”CPUInfo”,”DiskInfo”,”NetworkInfo”)
ForEach ($command in $commands){
$comboBox1.items.add($command)
}
$tabControl.Controls.Add($comboBox1)

# Set to the first item
$comboBox1.SelectedIndex = 0;
$Database.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 4
$System_Drawing_Point.Y = 22
$Database.Location = $System_Drawing_Point
$Database.Name = “Database”
$System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
$System_Windows_Forms_Padding.All = 3
$System_Windows_Forms_Padding.Bottom = 3
$System_Windows_Forms_Padding.Left = 3
$System_Windows_Forms_Padding.Right = 3
$System_Windows_Forms_Padding.Top = 3
$Database.Padding = $System_Windows_Forms_Padding
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 205
$System_Drawing_Size.Width = 445
$Database.Size = $System_Drawing_Size
$Database.TabIndex = 1
$Database.Text = “Database”
$Database.UseVisualStyleBackColor = $True

$tabControl1.Controls.Add($Database)

$tabPage1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 4
$System_Drawing_Point.Y = 22
$tabPage1.Location = $System_Drawing_Point
$tabPage1.Name = “tabPage1”
$System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
$System_Windows_Forms_Padding.All = 3
$System_Windows_Forms_Padding.Bottom = 3
$System_Windows_Forms_Padding.Left = 3
$System_Windows_Forms_Padding.Right = 3
$System_Windows_Forms_Padding.Top = 3
$tabPage1.Padding = $System_Windows_Forms_Padding
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 205
$System_Drawing_Size.Width = 445
$tabPage1.Size = $System_Drawing_Size
$tabPage1.TabIndex = 2
$tabPage1.Text = “Active Directory”
$tabPage1.UseVisualStyleBackColor = $True

$tabControl1.Controls.Add($tabPage1)

$tabPage2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 4
$System_Drawing_Point.Y = 22
$tabPage2.Location = $System_Drawing_Point
$tabPage2.Name = “tabPage2”
$System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
$System_Windows_Forms_Padding.All = 3
$System_Windows_Forms_Padding.Bottom = 3
$System_Windows_Forms_Padding.Left = 3
$System_Windows_Forms_Padding.Right = 3
$System_Windows_Forms_Padding.Top = 3
$tabPage2.Padding = $System_Windows_Forms_Padding
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 205
$System_Drawing_Size.Width = 445
$tabPage2.Size = $System_Drawing_Size
$tabPage2.TabIndex = 3
$tabPage2.Text = “Backup & Restore”
$tabPage2.UseVisualStyleBackColor = $True

$tabControl1.Controls.Add($tabPage2)

$button1.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 226
$System_Drawing_Point.Y = 343
$button1.Location = $System_Drawing_Point
$button1.Name = “button1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$button1.Size = $System_Drawing_Size
$button1.TabIndex = 0
$button1.Text = “Submit”
$button1.UseVisualStyleBackColor = $True
$button1.add_Click($handler_button1_Click)

$form1.Controls.Add($button1)

$fontDialog1.ShowHelp = $True

#endregion Generated Form Code

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
GenerateForm

Related posts
1. Stir fry a VBA application quickly
2.Building a respectable VBA with Excel application
3. Get your feet wet with Powershell GUI
4. Powershell GUI – Adding bells and whistles
5. Slicing and dicing with LogParser & VBA
6. Adventures in LogParser, HTA and charts.

Also see
Brewing a potion with Bluemix, PostgreSQL, Node.js in the cloud
A Bluemix recipe with MongoDB and Node.js A Cloud medley with IBM Bluemix, Cloudant DB and Node.js
– A crime map of India in R: Crimes against women
– What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1
– Bend it like Bluemix, MongoDB with autoscaling – Part 1
– Analyzing cricket’s batting legends – Through the mirage with R
– Masters of spin: Unraveling the web with R

 

Find me on Google+

Get your feet wet with Powershell GUI

Here’s my latest attempt in creating a simple GUI using Powershell for Windows Resource Management Tasks. Powershell by itself is easy but there is hardly any documentation on the web for creating a cool GUI. You have to put together various bits and pieces by the trial and error method. Anyway I did come up with some success. However there is a lot to be desired. For some reason the results only show up when the GUI is closed through the Cancel or Exit button. Feel free to tweak the code as you please. The Windows Management Commands are some basic scripts taken from Powershell Pro.

This is the GUI I created. Do read my post Powershell GUI – Adding bells & whistles for creating a full-fledged Powershell GUI

Feel free to send me any comments.

[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Drawing”)
[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)

# Add functions
#*=============================================================================
Function BIOSInfo {
$colItems = Get-WmiObject Win32_BIOS -Namespace “root\CIMV2″ -computername $strComputer
foreach($objItem in $colItems) {
“—————————— Bios Info ———————”
“Computer Name: “+ $strComputer
“BIOS Characteristics: “+ $objItem.BiosCharacteristics
“BIOS Version: “+ $objItem.BIOSVersion
“Build Number: “+ $objItem.BuildNumber
“Caption: “+ $objItem.Caption
“Code Set: “+ $objItem.CodeSet
“Current Language: “+ $objItem.CurrentLanguage
“Description: “+ $objItem.Description
“Identification Code: “+ $objItem.IdentificationCode
“Installable Languages: “+ $objItem.InstallableLanguages
“Installation Date: “+ $objItem.InstallDate
“Language Edition: “+ $objItem.LanguageEdition
“List Of Languages: “+ $objItem.ListOfLanguages
“Manufacturer: “+ $objItem.Manufacturer
“Name: ” + $objItem.Name
“Other Target Operating System: “+ $objItem.OtherTargetOS
“Primary BIOS: “+ $objItem.PrimaryBIOS
“Release Date: “+ $objItem.ReleaseDate
“Serial Number: “+ $objItem.SerialNumber
“SMBIOS BIOS Version: “+ $objItem.SMBIOSBIOSVersion
“SMBIOS Major Version: “+ $objItem.SMBIOSMajorVersion
“SMBIOS Minor Version: “+ $objItem.SMBIOSMinorVersion
“SMBIOS Present: “+ $objItem.SMBIOSPresent
“Software Element ID: “+ $objItem.SoftwareElementID
“Software Element State: “+ $objItem.SoftwareElementState
“Status: “+ $objItem.Status
“Target Operating System: “+ $objItem.TargetOperatingSystem
“Version: “+ $objItem.Version

}
}

Function OSInfo {
$colItems = Get-WmiObject Win32_OperatingSystem -Namespace “root\CIMV2” -Computername $strComputer
foreach($objItem in $colItems) {
“—————————— OS Info ———————”
“Computer Name: “+ $strComputer
“Operating System:” + $objItem.Name
}
}

Function CPUInfo {
$colItems = Get-WmiObject Win32_Processor -Namespace “root\CIMV2” -Computername $strComputer
foreach($objItem in $colItems) {
“————————CPU Info ————————-”
“Computer Name: “+ $strComputer
“Caption: ”+ $objItem.Caption
“CPU Status: ”+ $objItem.CpuStatus
“Current Clock Speed: ”+ $objItem.CurrentClockSpeed
“Device ID: ”+ $objItem.DeviceID
“L2 Cache Size: ”+ $objItem.L2CacheSize
“L2 Cache Speed: ”+ $objItem.L2CacheSpeed
“Name: ”+ $objItem.Name
“System Name:” + $objItem.SystemName

}
}

Function DiskInfo {
$colItems = Get-WmiObject Win32_DiskDrive -Namespace “root\CIMV2″ -ComputerName $strComputer
foreach($objItem in $colItems) {
“————————- Disk Info ——————–”
“Computer Name: “+ $strComputer
“Description: ”+ $objItem.Description
“Device ID: ”+ $objItem.DeviceID
“Interface Type: ”+ $objItem.InterfaceType
“Media Type: ”+ $objItem.MediaType
“Model: ”+ $objItem.Model
“Partitions: ”+ $objItem.Partitions
“Size: ”+ $objItem.Size
“Status: ”+ $objItem.Status

}
}

Function NetworkInfo {
$colItems = Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace “root\CIMV2” -ComputerName $strComputer | where{$_.IPEnabled -eq “True”}
foreach($objItem in $colItems) {
“—————————— Network Info ———————”
“Computer Name: “+ $strComputer
“DHCP Enabled:” + $objItem.DHCPEnabled
“IP Address:” + $objItem.IPAddress
“Subnet Mask:” + $objItem.IPSubnet
“Gateway:” + $objItem.DefaultIPGateway
“MAC Address:” + $ojbItem.MACAddress
}
}
Function SysInfo {

$colItems = Get-WmiObject Win32_ComputerSystem -Namespace “root\CIMV2” -ComputerName $strComputer
foreach($objItem in $colItems) {
“—————————— Sys Info ———————”
“Computer Name: “+ $strComputer
“Computer Manufacturer: ” + $objItem.Manufacturer
“Computer Model: ” + $objItem.Model
“Total Memory: ” + $objItem.TotalPhysicalMemory + “bytes”
}
}

# Create a GUI Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = “Data Entry Form”
$objForm.Size = New-Object System.Drawing.Size(800,600)
$objForm.StartPosition = “CenterScreen”

$objForm.KeyPreview = $True
#$objForm.Add_KeyDown({if ($_.KeyCode -eq “Enter”)
# {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq “Escape”)
{$objForm.Close()}})

# Add a drop-down Combo box
$objComboBox = New-Object System.Windows.Forms.Combobox
$objComboBox.Location = New-Object System.Drawing.Size(250,250)
$objComboBox.Size = New-Object System.Drawing.Size(280,20)
$objComboBox.Text = “Please select”

# Add items to Combo box
$commands = @(“SysInfo”,”BIOSInfo”,”OSInfo”,”CPUInfo”,”DiskInfo”,”NetworkInfo”)
ForEach ($command in $commands){
$objComboBox.items.add($command)
}

# Add combo box to Userform
$objForm.Controls.Add($objComboBox)

# Set to the first item
$objComboBox.SelectedIndex = 0;

# Set selection to ComboBox selected text.
$selection = $objComboBox.Text;
write-host $selection

# Add a text box to the Userform
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(250,200)
$objTextBox.Size = New-Object System.Drawing.Size(280,20)
$objForm.Controls.Add($objTextBox)

# Add an OK button and name it as “Submit”
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(250,400)
$OKButton.Size = New-Object System.Drawing.Size(75,25)
$OKButton.Text = “Submit”
$objForm.Controls.Add($OKButton)

# Add a Cancel button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(350,400)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = “Cancel”
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

# Add an Exit button
$ExitButton = New-Object System.Windows.Forms.Button
$ExitButton.Location = New-Object System.Drawing.Size(450,400)
$ExitButton.Size = New-Object System.Drawing.Size(75,23)
$ExitButton.Text = “Exit”
$ExitButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($ExitButton)

# Add a Text label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(250,180)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = “Please enter a comma separated list of servers:”
$objForm.Controls.Add($objLabel)

# Add a Text label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(260,100)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = “Windows Resource Management Tool”
$objForm.Controls.Add($objLabel)

# Set form on top
$objForm.Topmost = $True

# Show fim
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

$x = $objTextbox.text
$vals = $x.split(“,”)
foreach ($strComputer in $vals){
write-host $strComputer
}

$OKButton.Add_Click({

switch ($objComboBox.SelectedItem)
{
“SysInfo” {SysInfo}
“BIOSInfo” {BiosInfo}
“OSInfo” {OSInfo}
“CPUInfo” {CPUInfo}
“DiskInfo” {DiskInfo}
“NetworkInfo” {NetworkInfo}

}
$objForm.Close()})

# Set selection to ComboBox selected text.
$selection = $objComboBox.Text;
write-host $selection
foreach ($strComputer in $vals){
switch($selection) {
“SysInfo” { SysInfo }
“BIOSInfo” {BiosInfo}
“OSInfo” {OSInfo}
“CPUInfo” {CPUInfo}
“DiskInfo” {DiskInfo}
“NetworkInfo” {NetworkInfo}
}
}

$x

Related posts
1. Stir fry a VBA application quickly
2.Building a respectable VBA with Excel application
3. Get your feet wet with Powershell GUI
4. Powershell GUI – Adding bells and whistles
5. Slicing and dicing with LogParser & VBA
6. Adventures in LogParser, HTA and charts.

Also see
Brewing a potion with Bluemix, PostgreSQL, Node.js in the cloud
A Bluemix recipe with MongoDB and Node.js A Cloud medley with IBM Bluemix, Cloudant DB and Node.js
– A crime map of India in R: Crimes against women
– What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1
– Bend it like Bluemix, MongoDB with autoscaling – Part 1
– Analyzing cricket’s batting legends – Through the mirage with R
– Masters of spin: Unraveling the web with R

Find me on Google+

Building a respectable VBA with Excel Application

VBA with Excel is not the right tool/language to solve mankind’s perennial question regarding the purpose of life. But it can come quite handy for several tasks for e.g. in quickly creating a Proof of Concept (PoC) or a prototype. It can also be quite useful for smaller tasks for e.g. 3G networks dimensioning, determining an investment portfolio, insurance schemes or maybe a smaller version of a Windows Resource Management tool.  To take a quick look at how put together a VBA application quickly take a look at my earlier post “Stir fry a VBA with Excel application quickly”.

This post takes a look at some key aspects in building a respectable, decent tool. Some of essential elements are as follows

a)      Launch button: Launch the application from the Excel sheet. For this you could add a button to the Excel sheet. For this select “View->Toolbars-Forms”. From the toolbar select a button and place it in the Excel sheet. Once you place the button appropriately select the button and choose the “Edit code” from the Forms toolbox. Add the following code

Sub Button1_Click ()

UserForm1.Show

End Sub

The Userform1 is the form that you created with VBA toolbox.

b)      Minimize button:  Now that you are able to launch the VBA application from the Excel spreadsheet you will also want to minimize the VBA form to check the output on the Excel sheet. For this add a button to the Userform probably “_” the icon for minimizing and add

Private Sub CommandButton13_Click()

Unload UserForm1

End Sub

You could also do a Userform1. Hide but I found that once you did that and re-launched the application the combo-box’s list started to repeat.  Unload essentially resets the Form and that was fine with me.

c)      Getting control of the Excel sheet: This is extremely important. Make sure that in the properties window of your userform you have ShowModal set as “false”. This will allow you to edit/change your Excel sheet even when the VBA application is running.

d)     Status bar: VBA does provide a “Status” control in the additional controls for the Userform toolbox. But I could not get it to work. So I added a textbox and update the text box with “Working …” and “Done.”

e)      Progress bar: If you want to add a progress bar do so by adding this control. For this right-click in the toolbox and choose additional controls. I did not have the need to use this but a good write up is available at O’Reilly Hacks

My VBA Userform

Here is the sample code for this ….

Option Explicit
Dim servername
Dim row
Dim value

Private Sub CommandButton13_Click()
Unload UserForm1
End Sub
Private Sub CommandButton14_Click()
Unload UserForm1
End Sub

Private Sub CommandButton2_Click()
ComboBox1.ListIndex = 0
Me.OptionButton1.value = True
TextBox1.value = “”
End Sub

Private Sub CommandButton3_Click()
Unload UserForm1
End Sub

Private Sub TextBox1_Change()
servername = TextBox1.value
End Sub
Private Sub UserForm_Activate()
With ComboBox1
ComboBox1.AddItem “Physical Memory Properties”
ComboBox1.AddItem “Get Server Info”

….
End With
Me.Label17.Font.Bold = True
Me.MultiPage1.ForeColor = vbBlue
ComboBox1.ListIndex = 0
Me.OptionButton1.value = True
row = 25
End Sub
Private Sub ComboBox1_Click()
Dim x
Select Case ComboBox1.Text
Case “Physical Memory Properties”
value = 1
Case “Get Server Info”
value = 2


End Select

End Sub
Private Sub CommandButton1_Click()

If OptionButton1.value = True Then

Select Case value
Case 1
Call phy_mem_prop
Case 2
Call GetServerInfo


End Select
Else
If OptionButton2.value = True Then

Select Case value
Case 1
Call phy_mem_prop_csv
Case 2
Call GetServerInfo_csv


End Select
End If

End If
End Sub

Private Sub phy_mem_prop()
On Error Resume Next
Dim strComputer, i, objWMIService, strMemory, colItems
Dim strCapacity, objItem, installedModules, totalSlots
Dim strCapacityGB
Dim r As Range
Dim arrstring
Dim slogFile, objFs, objFile
Dim col
row = row + 3

arrstring = Split(servername, “,”)
For Each strComputer In arrstring
i = 1
Application.StatusBar = “Working…”
UserForm1.TextBox5.Font.Italic = True
UserForm1.TextBox5.Font.Bold = False
UserForm1.TextBox5.Font.Size = 10
UserForm1.TextBox5 = “Working…”

Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colItems = objWMIService.ExecQuery(“Select * from Win32_PhysicalMemory”)

For Each objItem In colItems
strCapacity = objItem.Capacity
If strMemory <> “” Then strMemory = strMemory & vbCrLf
strMemory = strMemory & “Bank” & i & ” : ” & (objItem.Capacity / 1048576) & ” Mb”
i = i + 1
Next
installedModules = i – 1

Set colItems = objWMIService.ExecQuery(“Select * from Win32_PhysicalMemoryArray”)
For Each objItem In colItems
totalSlots = objItem.MemoryDevices
strCapacity = (objItem.MaxCapacity / 1024)
strCapacityGB = strCapacity / 1024
Next
‘MsgBox “Total Slots: ” & totalSlots & vbCrLf & _
“Free Slots: ” & (totalSlots – installedModules) & vbCrLf & _
vbCrLf & “Installed Modules:” & vbCrLf & strMemory & vbCrLf & vbCrLf & _
“Maximum Capacity for ” & strComputer & “: ” & strCapacityGB & ” GB”, vbOKOnly + vbInformation, “PC Memory Information”

Sheet1.Cells(row, 1).Font.Bold = True
Cells(row, 1) = “Physical Memory Properties”
row = row + 1

For col = 1 To 5
Sheet1.Cells(row, col).Interior.Color = vbCyan
Sheet1.Cells(row, col).Font.Bold = True
Next

Cells(row, 1) = “Computer Name: ”
Cells(row, 2) = “Total Slots”
Cells(row, 3) = “Free Slots”
Cells(row, 4) = “Installed Modules”
Cells(row, 5) = “Maximum Capacity for”
row = row + 1
Cells(row, 1) = strComputer
Cells(row, 2) = totalSlots
Cells(row, 3) = totalSlots – installedModules
Cells(row, 4) = strMemory
Cells(row, 5) = strCapacityGB
Next
UserForm1.TextBox5.Font.Italic = False
UserForm1.TextBox5 = “Done.”
Application.StatusBar = “Done.”
Application.StatusBar = False
End Sub

Private Sub phy_mem_prop_csv()
On Error Resume Next
Dim arrstring
Dim strComputer, i, objWMIService, strMemory, colItems
Dim strCapacity, objItem, installedModules, totalSlots
Dim strCapacityGB
Const FOR_APPEND = 8
Dim slogFile
Dim objFs, objFile
arrstring = Split(servername, “,”)
For Each strComputer In arrstring
i = 1

Application.StatusBar = “Working…”
UserForm1.TextBox5.Font.Italic = True
UserForm1.TextBox5.Font.Bold = False
UserForm1.TextBox5.Font.Size = 10
UserForm1.TextBox5 = “Working…”

Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colItems = objWMIService.ExecQuery(“Select * from Win32_PhysicalMemory”)
For Each objItem In colItems
strCapacity = objItem.Capacity
If strMemory <> “” Then strMemory = strMemory & vbCrLf
strMemory = strMemory & “Bank” & i & ” : ” & (objItem.Capacity / 1048576) & ” Mb”
i = i + 1
Next
installedModules = i – 1

Set colItems = objWMIService.ExecQuery(“Select * from Win32_PhysicalMemoryArray”)

For Each objItem In colItems
totalSlots = objItem.MemoryDevices
strCapacity = (objItem.MaxCapacity / 1024)
strCapacityGB = strCapacity / 1024
Next

slogFile = “logfile.txt”
Set objFs = CreateObject(“scripting.FileSystemObject”)
Set objFile = objFs.OpenTextFile(slogFile, FOR_APPEND, True)
objFile.writeline
objFile.writeline
objFile.writeline
objFile.writeline
objFile.writeline

objFile.writeline “Physical Memory Properties”
objFile.writeline “Total slot = ” & totalSlots & _
“Free Slots = ” & totalSlots – installedModules & _
“Installed Modules = ” & strMemory + _
“Max capacity = ” & strCapacityGB

objFile.Close
Set objFile = Nothing
Set objFs = Nothing
Next

UserForm1.TextBox5.Font.Italic = False
UserForm1.TextBox5 = “Done.”
UserForm1.TextBox5 = “Output in logfile.txt”
Application.StatusBar = “Done.”
Application.StatusBar = False
End Sub
Sub GetServerInfo()
On Error Resume Next

Dim r As Range, i As Integer, N As Integer
Dim arrstring
Dim strComputer, colDisks, objDisk, objWMIService
Dim col
row = row + 3
Application.StatusBar = “Working…”
UserForm1.TextBox5.Font.Italic = True
UserForm1.TextBox5.Font.Bold = False
UserForm1.TextBox5.Font.Size = 10
UserForm1.TextBox5 = “Working…”

arrstring = Split(servername, “,”)
For Each strComputer In arrstring
Worksheets(“sheet1”).Activate
Set objWMIService = GetObject _
(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colDisks = objWMIService.ExecQuery _
(“Select * From Win32_LogicalDisk”)

Sheet1.Cells(row, 1).Font.Bold = True
Cells(row, 1) = “Server Information”
row = row + 1

For col = 1 To 4
Sheet1.Cells(row, col).Interior.Color = vbCyan
Sheet1.Cells(row, col).Font.Bold = True
Next
Cells(row, 1) = “Computer Name: ”
Cells(row, 2) = “Disk”
Cells(row, 3) = “Free Space”
Cells(row, 4) = “Total Size”
row = row + 1
Cells(row, 1) = strComputer
For Each objDisk In colDisks
Cells(row, 2) = objDisk.DeviceID
If objDisk.FreeSpace < 1073741824 Then
Cells(row, 3) = objDisk.FreeSpace / 1024 / 1024
Else

Cells(row, 3) = objDisk.FreeSpace / 1024 / 1024
End If
Cells(row, 4) = objDisk.Size / 1024 / 1024
row = row + 1
Next
Next
UserForm1.TextBox5.Font.Italic = False
UserForm1.TextBox5 = “Done.”
Application.StatusBar = “Done.”
Application.StatusBar = False
End Sub

Sub GetServerInfo_csv()
On Error Resume Next

Dim arrstring
Dim strComputer, colDisks, objDisk, objWMIService
Dim slogFile
Dim objFs, objFile
Const FOR_APPEND = 8
arrstring = Split(servername, “,”)
For Each strComputer In arrstring
Application.StatusBar = “Working…”
UserForm1.TextBox5.Font.Italic = True
UserForm1.TextBox5.Font.Bold = False
UserForm1.TextBox5.Font.Size = 10
UserForm1.TextBox5 = “Working…”
Set objWMIService = GetObject _
(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colDisks = objWMIService.ExecQuery _
(“Select * From Win32_LogicalDisk”)
slogFile = “logfile.txt”
Set objFs = CreateObject(“scripting.FileSystemObject”)
Set objFile = objFs.OpenTextFile(slogFile, FOR_APPEND, True)
objFile.writeline
objFile.writeline
objFile.writeline
objFile.writeline
objFile.writeline
objFile.writeline “Server Information”
objFile.writeline “Computer Name: ,Disk, Free Space, Total Size”
objFile.write strComputer & “,”
For Each objDisk In colDisks
objFile.write objDisk.DeviceID & “,”
If objDisk.FreeSpace < 1073741824 Then
objFile.write objDisk.FreeSpace / 1024 / 1024 & “,”
Else

objFile.write objDisk.FreeSpace / 1024 / 1024 & “,”
End If
objFile.writeline objDisk.Size / 1024 / 1024 & “,”

Next
Next
objFile.Close
Set objFile = Nothing
Set objFs = Nothing

UserForm1.TextBox5.Font.Italic = False
UserForm1.TextBox5 = “Done.”
UserForm1.TextBox5 = “Output in logfile.txt”
Application.StatusBar = “Done.”
Application.StatusBar = False

End Sub

Sub GetService()
On Error Resume Next
Dim strstring
Dim r As Range, i As Integer, N As Integer
Dim col
Dim arrstring
Dim strComputer, colWMIThings, objItem, objWMIService
row = row + 4
Application.StatusBar = “Working…”
UserForm1.TextBox5.Font.Italic = True
UserForm1.TextBox5.Font.Bold = False
UserForm1.TextBox5.Font.Size = 10
UserForm1.TextBox5 = “Working…”
arrstring = Split(servername, “,”)
For Each strComputer In arrstring
‘MsgBox (servername)
Worksheets(“sheet1”).Activate
Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colWMIThings = _
objWMIService.ExecQuery(“SELECT * FROM Win32_service”)
Sheet1.Cells(row, 1).Font.Bold = True
Cells(row, 1) = “Services”
row = row + 1
For col = 1 To 4
Sheet1.Cells(row, col).Interior.Color = vbCyan
Sheet1.Cells(row, col).Font.Bold = True
Next
Cells(row, 1) = “Computer Name: ”
Cells(row, 2) = “Service name”
Cells(row, 3) = “Status”
Cells(row, 4) = “Strtup Mode”
row = row + 1
Cells(row, 1) = strComputer
For Each objItem In colWMIThings
If objItem.State = “Stopped” And objItem.StartMode = “Auto” Then
Cells(row, 2) = objItem.DisplayName
Else
Cells(row, 2) = objItem.DisplayName
End If
Cells(row, 3) = objItem.State
Cells(row, 4) = objItem.StartMode
row = row + 1
Next
Next
UserForm1.TextBox5.Font.Italic = False
UserForm1.TextBox5 = “Done.”
Application.StatusBar = “Done.”
Application.StatusBar = False
End Sub

Related posts
1. Stir fry a VBA application quickly
2.Building a respectable VBA with Excel application
3. Get your feet wet with Powershell GUI
4. Powershell GUI – Adding bells and whistles
5. Slicing and dicing with LogParser & VBA
6. Adventures in LogParser, HTA and charts.

Also see
Brewing a potion with Bluemix, PostgreSQL, Node.js in the cloud
A Bluemix recipe with MongoDB and Node.js A Cloud medley with IBM Bluemix, Cloudant DB and Node.js
– A crime map of India in R: Crimes against women
– What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1
– Bend it like Bluemix, MongoDB with autoscaling – Part 1
– Analyzing cricket’s batting legends – Through the mirage with R
– Masters of spin: Unraveling the web with R

Find me on Google+

Windows Resource Management Tool – Technology choices

There are the following technology choices for a Windows Automation Tool

a)      VBA with Excel

b)      Perl

c)      Powershell

d)     HTML for Applications (HTA)

1. VBA with Excel

VBA (Visual Basic for Applications) with Excel is good option to consider. VBA allows for a quick development of a fairly reasonable user interface. VBA includes a Userform to which one can controls like textbox, listbox, combo box, radio button etc.  These controls can then invoke VBscripts in the background which can perform resource management tasks. For some more detail on how to create the Userform with controls look at my earlier post Stir fry a VBA application quickly. Besides, the results can be populated in the Excel sheet

A screen shot of a VBA with Excel is shown below

Pros

  1. Ease of building a GUI using the Visual Basic User form with appropriate controls
  2. The VBA will include VBscripts that will perform resource management tasks
  3. Can populate the results into Excel sheet.
  4. The  results from the Excel sheet can be saved as CSV, HTML etc

Cons

  1. Not all client sites have MS Office installed on them. This makes it difficult to deploy Excel with VBA.

2. Perl

Perl allows for easy creation of scripts to manage Windows Resources. The language is easy to use and facilitates quick prototyping. However Perl by itself does not provide for the creation of a GUI. Perl scripts can only be run in command line mode.

Pros

  1. Ease of scripting

Cons

  1. Does not allow for creation of a GUI

3. Powershell

Powershell is a convenient way for creating resource management scripts. It is surprising the Microsoft took such a long time to progress from the clunky “command” shell to Powershell which is more on the lines of Korn, Bourne and Unix shell. The nice part is that instead of the cryptic Unix commands the commands have a verb-noun combination for e.g. get-date, get-command etc. The benefit of Powershell is the extensive help that is available for each command. Powershell is in many ways similar to Perl. Building a GUI with Powershell is quite involved and requires quite a bit of programming. Moreover Powershell is installed by default only on Windows 7 and later. For an excellent tutorial on Powershell do read Powershell tutorial by Jesse Hamrick

Pros

  1. Ease of scripting for resource management
  2. Extensive help available for query while building resource management commands
  3. Can format output easily into list, table or Excel sheet
  4. Easy to build stand-alone scripts

Cons

a. Building a GUI based tool is fairly involved

4. HTML Applications (HTA)

HTML application brings the power of the browser for the front end with VBscript or JScript as the backend. But to build a easy to use GUI there is a need to use Web page builders like Microsoft’s FrontPage, Dreamweaver etc. The controls on the Web page can invoke VBScript to run resource management tasks

Pros

  1. Can build a user-friendly front-end using Web page builder tools
  2. Resource management tasks can be executed by VBscript

Cons

  1. Needs a regular Web page building tool like MS FrontPage or Dreamweaver

Find me on Google+

Stacks of protocol stacks – A primer

Communication protocols like any other technology arrive on the scene to solve a particular problem. Some protocols endure while many perish. The last 60 years or so have seen a true proliferation of protocols in various domains.

So what is a protocol?

In my opinion a protocol is any pre-defined set of communication rules. For e.g. consider the exchange between you and me.

Me: “Thank You”
You: “You’re welcome”.

A more complex exchange could be
You: “How are you doing today?”
Me:” Fine. And yourself?”
You: “Great”

These are “protocols of courtesy or decorum”. There are many such protocols in daily use so there is little wonder that the technological world is full of protocols.

So then what is a protocol stack?

Let us take this hypothetical example. Assume that the CEO of company ABC Inc. wants to talk to CEO of XYZ Inc. This is how this would work in the context of an organizational protocol stack.

CEO (ABC Inc.) to secretary: “Can you arrange for a call with CEO (XYZ Inc.)?”
Secretary (ABC Inc.): “Sure.”

Next the secretary of ABC Inc. will make a call to secretary of XYZ Inc. The exchange would go like this.

Secretary (ABC Inc.): “My CEO would like to have a talk with your CEO”.
Secretary (XYZ Inc.) looks up her CEOs calendar and says
Secretary (XYZ Inc.): My CEO will be free between 3.00 pm – 3.30 pm

So at 3.15 pm
CEO (ABC Inc.) calls CEO (XYZ Inc.): “Can we have a round of golf this weekend?”
CEO (XYZ Inc.): “Absolutely!”

This is typically what also happens in communication protocol stacks. The lower layers provide functions to upper layers (for e.g. the secretary to CEO). Once the lower layers establish the communication channels the upper layers (CEOs) can communicate.

Now is that all there is protocols and protocol stack? In a way, yes. However if we return to our 2nd exchange we could have received any of the following responses

You: “How are you doing today?”
Me:” Will you shut up?”

Or

You: “How are you doing today?”
Me: Sigh.

In other words the protocol suite must take into account all the moods of the communicating parties at either end. So there will be what is known as “sunny day” scenarios and “error scenarios”

This is essentially the basics of any communication protocol whether it is in the internet domain, telecom (SS7 domain), IEEE or any other domain.

Find me on Google+

Stacks of protocol stacks

Communication protocols like any other technology arrive on the scene to solve a particular problem. Some protocols endure while many perish. The last 60 years or so have seen a true proliferation of protocols in various domains.

So what is a protocol?
In my opinion a protocol is any pre-defined set of communication rules.

For e.g. consider the exchange between me and you
Me: “Thank You”
You: “You’re welcome”.

A more complex exchange could be
You: “How are you doing today?”
Me:”Fine. And yourself?”
You: “Great”

These are “protocols of courtesy or decorum”. There are many such protocols in daily use so there is little wonder that the technological world is full of protocols.

A couple of decades back there were 3 main standard bodies that came up with protocols namely IEEE (for LANs), IETF for the internet and ITU-T for telecom. Now there are many more bodies for e.g. CableLabs for cable television, WiMAX forum for WiMAX, NFC Forum etc.

Also protocols exist both for wired and the wireless domain. The protocols differ based on the distance for which the protocol will apply. This post will try to take a look at the some of most important in this. Certainly many will slip through the cracks, so beware!

Near Field Communication (NFC): This is a wireless protocol of the order of a few centimeters primarily for contactless data transfers. Its primary use is for mobile payment. As opposed to Bluetooth there will be no necessity for device pairing. The NFC standards are maintained by the NFC Forum.

Bluetooth: This is another wireless protocol and uses the 2.4- 2.48 GHz band for data exchange and is commonly used in mobile phones, TVs, and other devices. This protocol requires pairing of devices prior to data transfer. The Bluetooth details are maintained in Bluetooth Special Interest Group.

Zigbee:  Zigbee is a low powered, low cost wireless protocol that will connect devices within residential homes. Zigbee has a data rate of 250 kbps and is based on the IEEE 802 standard for Personal Area Network (PAN) or Home Area Network (HAN). Zigbee will be protocol of choice in the Smart Home which will be part of Smart Grid concept. More details can be found at the Zigbee Alliance.

LAN protocols:  LAN protocols are wired protocols. The main 3 LAN protocols are IEEE 802.3 (Ethernet), IEEE 802.4 (Token Bus) & IEEE (Token Ring) are used in enterprises, schools or small buildings of the order of a few 100 meters. LAN protocols ensure transmission speeds of the order of 10 Mbps – 40 Mbps.

WiFi: WiFi provides wireless access in residential homes, airports, cafes at a distance of 20 meters with speeds of 2 Mbps – 8 Mbps (802.11a/b/e/g). Wireless hotspots use WiFi protocols

Super WiFi/Whitespaces: Whitespaces refers to using abandoned TV frequency bands for wireless data transmission around the 700 MHz range. Whitespaces can travel larger distances typically around 100 km and through trees and walls. This is nascent technology and is based on IEEE 802.22 protocol. A new forum for taking this technology forward is the Whitespace Alliance.

Telecom protocols

ISDN:  This protocol is governed by the Q.931 standards and was supposed to carry high speed data (64 kbps???) from residential homes, This protocol went into relative obscurity soon.

Wired Trunk protocols: There are several trunk protocols that connect digital exchanges (digital switches) for e.g. ISUP (Q.763), BTUP, TUP. These protocols exchange messages between central offices and are used for setting up, maintaining and release of STD voice calls.

Internet Protocols

The predominant protocol of the internet is TCP/IP (RFC 793). There are several other protocols that work in the internet. A few of them

Exterior Gateway Protocol (EGP)

OSPF Open Shortest Path First protocol

Interior Gateway Protocol (IGP)

RSVP & DiffServ

WAN protocols: There is a variety of protocols to handle communication between regions or across a large metropolitan area. The most common among these are

MPLS: Multi-protocol Label System.

ATM : Asynchronous Transfer Mode

Frame relay:

X.25:

Protocols that are exist in both the Internet & Telecom domain

A number of protocols work in concert to setup, maintain and release multi-media sessions

SIP/SDP: Session Initiation Protocol (RFC 3261 et al) /Session Description Protocol (RFC 2327)

SCTP/RTP/RTSP: Session Control Transport Protocol/Real Time Protocol/Real Time Secure Protocol – These protocols are used to send and control media packets.

MGCP/Megaco: This is a protocol used to control the Softswitch.or the Media Gateway Controller (MGC)

WiMAX: (Worldwide Interoperability for Microwave Access) is a technology for wirelessly delivering high-speed Internet service to large geographical areas. WiMAX offers data speeds in the range of 40 Mbps – 70 Mbps. This is an IEEE 802.16 family of protocols. Details about WiMAX can be obtained at WiMAX Forum.

DOCSIS: DOCSIS is the protocol that is used in cable TV and uses hybrid fiber co-axial cables for transmission. This protocol is also used these days for internet access. More details regarding the DOCSIS protocol can be found at CableLabs.

Note: I will be adding more substance and body to this post soon …

Find me on Google+

The Next Frontier

Published in Telecom Asia – The next frontier, 21, Mar, 2012

In his classic book “The Innovator’s Dilemma” Prof. Clayton Christensen of Harvard Business School presents several compelling cases of great organizations that fail because they did not address disruptive technologies, occurring in the periphery, with the unique mindset required in managing these disruptions.

In the book the author claims that when these disruptive technologies appeared on the horizon there were few takers for these technologies because there were no immediate applications for them. For e.g. when the hydraulic excavator appeared its performance was inferior to the existing predominant manual excavator. But in course of time the technology behind hydraulic excavators improved significantly to displace existing technologies. Similarly the appearance of 3.5 inch disk had no immediate takers in desktop computers but made its way to the laptop.

Similarly the mini computer giant Digital Equipment Corporation (DEC) ignored the advent of the PC era and focused all its attention on making more powerful mini-computers. This led to the ultimate demise of DEC and several other organizations in this space. This book includes several such examples of organizations that went defunct because disruptive technologies ended up cannibalizing established technologies.

In the last couple of months we have seen technology trends pouring in.  It is now accepted that cloud computing, mobile broadband, social networks, big data, LTE, Smart Grids, and Internet of Things will be key players in the world of our future. We are now at a point in time when serious disruption is not just possible but seems extremely likely. The IT Market Research firm IDC in its Directions 2012 believes that we are in the cusp of a Third Platform that will dominate the IT landscape.

There are several technologies that have been appearing on the periphery and have only gleaned marginal interest for e.g. Super Wi-Fi or Whitespaces which uses unlicensed spectrum to access larger distances of up to 100 kms. Whitespaces has been trialed by a few companies in the last year. Another interesting technology is WiMAX which provides speeds of 40 Mbps for distances of up to 50 km. WiMAX’s deployment has been spotty and has not led to widespread adoption in comparison to its apparent competitor LTE.

In the light of the technology entrants, the disruption in the near future may occur because of a paradigm shift which I would like to refer as the “Neighborhood Area Computing (NAC)” paradigm.  It appears that technology will veer towards neighborhood computing given the bandwidth congestion issues of WAN. A neighborhood area network (NAN) will supplant the WAN for networks which address a community in a smaller geographical area

This will lead to three main trends

Neighborhood Area Networks (NAN):  Major improvements in Neighborhood Area Networks (NAN) are inevitable given the rising importance of smart grids and M2M technology in the context of WAN latencies. Residential homes of the future will have a Home Area Network (HAN) based on bluetooth or Zigbee protocols connecting all electrical appliances. In a smart grid contextNAN provides the connectivity between the Home Area Network (HAN) of a future Smart Home with the WAN network. While it is possible that the utility HAN network will be separate from the IP access network of the residential subscriber, the more likely possibility is that the HAN will be a subnet within the home network and will connect toNAN network.

The data generated from smart grids, m2m networks and mobile broadband will need to be stored and processed immediately through big data analytics on a neighborhood datacenter. Shorter range technologies like WiMAX, Super WiFi/ Whitespaces will transport the data to a neighborhood cloud on which a Hadoop based Big Data analytics will provide real time analytics

Death of the Personal Computer:  The PC/laptop will soon give way to a cloud based computing platform similar to Google’s Chrome book. Not only will we store all our data on the cloud (music, photos, videos) we will also use the cloud for our daily computing needs. Given the high speeds of theNAN this should be quite feasible in the future. The cloud will remove our worries about virus attacks, patch updates and the need to buy new software.  We will also begin to trust our data in the cloud as we progress to the future. Moreover the pay-per-use will be very attractive to consumers.

Exploding Datacenters:  As mentioned above a serious drawback of the cloud is the WAN latency. It is quite likely that with the increases in processing powers and storage capacity coupled with dropping prices that cloud providers will have hundreds of data centers with around 1000 servers for each city rather than a few mega data centers with 10,000’s of servers.  These data centers will address the computing needs of a community in a small geographical area. Such smaller data centers, typically in a small city, will solve 2 problems. One it will build into the cloud geographical redundancy besides also providing excellent performance asNAN latencies will be significantly less in comparison to WAN latencies.

These technologies will improve significantly and fill in the need for handling neighborhood high speed data

The future definitely points to computing in the neighborhood.

Find me on Google+