AE6382 Introduction to Scripting AE 6382. What is a scripting l Scripting is the process of programming using a scripting language l A scripting language,

Slides:



Advertisements
Similar presentations
Perl Practical Extration and Reporting Language An Introduction by Shwen Ho.
Advertisements

Introducing JavaScript
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
The Web Warrior Guide to Web Design Technologies
Programming in Visual Basic
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
Tutorial 10 Programming with JavaScript
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
SCRIPTING LANGUAGE. The first interactive shells were developed in the 1960s to enable remote operation of the first time-sharing systems, and these,
Scripting Languages CS351 – Programming Paradigms.
Guide To UNIX Using Linux Third Edition
XP Tutorial 1 New Perspectives on JavaScript, Comprehensive1 Introducing JavaScript Hiding Addresses from Spammers.
Chapter 11 ASP.NET JavaScript, Third Edition. 2 Objectives Learn about client/server architecture Study server-side scripting Create ASP.NET applications.
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
Computer Science 101 Introduction to Programming.
1 Chapter One A First Program Using C#. 2 Objectives Learn about programming tasks Learn object-oriented programming concepts Learn about the C# programming.
A First Program Using C#
4.1 JavaScript Introduction
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Programming with JavaScript (Chapter 10). XP Various things Midterm grades: Friday Winter Career Fair – Thursday, April 28, 2011 (11 am to 3 pm). – MAC.
COMPUTER PROGRAMMING Source: Computing Concepts (the I-series) by Haag, Cummings, and Rhea, McGraw-Hill/Irwin, 2002.
Windows Administration How to automate Windows MSDN: “Windows Script Host (WSH) is a Windows Administration Tool.”
1 Perl Perl basics Perl Elements Arrays and Hashes Control statements Operators OOP in Perl.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Tutorial 10 Programming with JavaScript. XP Objectives Learn the history of JavaScript Create a script element Understand basic JavaScript syntax Write.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Java Applets. 2 Introduction to Java Applet Programs Applications are ___________________ programs –executed with Java interpreter Applet is a small program.
Sed, awk, & perl CS 2204 Class meeting 13 *Notes by Mir Farooq Ali and other members of the CS faculty at Virginia Tech. Copyright 2003.
EIW - ASP Introduction1 Active Server Pages VBScript.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
JavaScript Syntax, how to use it in a HTML document
AE6382 Scripting in Windows AE Documentation l The most difficult aspect of scripting in Windows is finding the documentation. l Microsoft produces.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Chapter Twelve sed, awk & perl1 System Programming sed, awk & perl.
TCL TK. Tcl/Tk C functions can become Tcl commands that are invoked interactively Tk = scriptable, portable user interface –Windows, X (Unix), MacOS,
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
1 JavaScript in Context. Server-Side Programming.
Week Four Agenda Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems Upcoming deadlines.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
A S P. Outline  The introduction of ASP  Why we choose ASP  How ASP works  Basic syntax rule of ASP  ASP’S object model  Limitations of ASP  Summary.
Introduction to Algorithm. What is Algorithm? an algorithm is any well-defined computational procedure that takes some value, or set of values, as input.
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
Basic 1960s It was designed to emphasize ease of use. Became widespread on microcomputers It is relatively simple. Will make it easier for people with.
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
JavaScript an introduction.
Java Applets.
PHP.
Tutorial 10 Programming with JavaScript
PHP an introduction.
Presentation transcript:

AE6382 Introduction to Scripting AE 6382

What is a scripting l Scripting is the process of programming using a scripting language l A scripting language, like C, Fortran, and Java, has expressions, conditional statements, and loop statements. l Unlike C, Fortran, and Java a scripting language has u Loose typing u Interpreted rather than compiled u Usually as some higher level abstractions or built-in functionality

AE6382 Scripting Features l Scripting languages are generally interpreted rather than compiled l This results in slower execution times compared to a compiled language u C and Fortran are generally fastest u Java is compiled to bytecode that runs on a virtual machine and is slower u The implementation of each individual interpreter varies greatly – Perl, Python, and Ruby are compiled at runtime into an internal format that increases performance – Shell scripts and MATLAB re-evaluate each statement every time l Development cycle is shortened – edit/run

AE6382 Scripting Features l Scripting languages do not, in general, use strong typing of variables u A variable may during the course of execution contain strings, integers, and objects l Scripting languages frequently build into the basic language higher order abstractions u Text processing u Regular expressions u System interface mechanisms l Most scripting interpreters can be embeddedt into other programs to provide scripting capability within that program u Microsoft Office uses Visual Basic for Applications

AE6382 Scripting Languages l Simple command/shell scripting, level 1, is the simplest form of scripting l Intended to provide a “batch” execution capability l Unix/Linux u bash, ksh (Korn shell), sh (Bourne shell) u csh (C shell), tsch u These shells can work interactively or in script mode u Have basic programming constructs (if, loops, …) l Windows u cmd/command have no programming constructs u Windows PowerShell (4Q2006) will have extensive scripting based on C# language

AE6382 Scripting Languages l Limited scripting languages, level 2, have more sophisticated language structure but are limited in their native functionality u No native file I/O capability for example l JavaScript / Jscript / ECMAScript u Available on Unix/Linux and Windows u C based syntax u Used almost exclusively as the client-side scripting language in the various web browsers u Can be used as a system scripting language in Windows via the Windows Scripting Host u Not generally used in Unix/Linux for general purpose scripting – SpiderMonkey is C based JS interpreter – Rhino is Java based JS interpreter

AE6382 Scripting Languages l VBScript u Available only on Windows, based on Visual Basic for Applications (VBA) u Can be used as the client-side scripting language in Internet Explorer u Most often used with Windows Active Server Pages (ASP) for IIS based web sites u Can be used as a system scripting language in Windows via the Windows Scripting Host

AE6382 Scripting Languages l Full scripting languages, level 3, have a sophisticated language structure and extensive application support l Perl – Practical Extraction and Reporting Language u A procedure based language with support for objects u Extensive text processing capabilities and regular expressions u Extensible using modules u C based syntax with plethora of symbols u Developed in late 1980’s l Python (also Jython) u An object oriented language with some procedure traits u Extensible u A format based syntax u Developed in early 1990’s

AE6382 Scripting Languages l Ruby u An object oriented language u Extensible u C like syntax with minimal symbols (no {} () …) u Developed in early 1990’s l TCL – Tool Command Language u A procedural language u Extensible u A stack evaluation syntax, similar to Lisp (lots of []) u Developed as an embeddable scripting language u Developed in late 1980’s

AE6382 Scripting Languages l Other niche scripting languages u BeanShell – Makes it possible to use Java as a scripting language u REXX – C-like, objects, cross-platform, has a Java version

AE6382 Perl l General purpose scripting language – Practical Extraction and Reporting Language l Based on the Unix program awk in its early incarnation l Runs everywhere u On Unix/Linux it runs standalone using #! script file convention u On Windows it can run standalone or as an ActiveX scripting engine l Pros u Extensive text processing capabilities including built-in regular expressions u Can be easily extended, there is extensive support for all types of system programming u Has syntax to support object based programming u Most Unix system calls are built-in functions u The built-in system calls will do the right thing in Windows

AE6382 Perl l Cons u Can be difficult for beginners to learn u Variable naming scheme is initially confusing u There is a high learning curve

AE6382 Perl l Has 3 classes of variables u $var-scalar (integer, real, string,...) of scalars, $var[0] u %var-hash of scalars, $var{key} l Has local, lexical, and global scoping of variables l Namespace separation l Objects and references are supported l Has the same set of operators as C plus some l Lexical and global scoping of variables l Statements end with ; l Comments are everything after # on a line l Functions sub name {... }

AE6382 Perl l Has the same set of operators as C plus some additional l Statements end with ; (semi-colon) l Comments are everything after # on a line l The usual complement of conditional statements u if – then – else (also unless – then – else) l The usual loop statements u for u for each u while l Functions and methods are defined similarly u sub name (…) { … }

AE6382 Perl l Loop statements for ($i=0 ; $i < 10 ; $i++) { printf “i=%4d\n”,$i; } while ( ) { print; = (0,5,8,12); foreach $value { print “Value=$value\n”; } foreach $value (0,5,8,12) { print “Value=$value\n”; } %hash = (part1=>0,part3=>70,part2=>4); foreach $key (sort keys %hash) { print “Value=$hash{$key}\n”; }

AE6382 Perl l Logical statements if ($i == 1) { print “i=$i\n”; $i++; } die “Unable to open file” if !open(IN,”filename”); if ($i == 1) { print “Group 1\n”; } else { print “Unknown group\n”; } if ($i == 1) { print “Group 1\n”; } elsif ($i == 2) { print “Group 2\n”; } elsif ($i == 3) { print “Group 3\n”; } else { print “Unknown group\n”; } unless ($i == 1) { print “Error: i != 1\n”; $i++; }

AE6382 Perl l Native Regular Expression Support while (<>) { next if m/.*error.*/; print; } foreach $line { next if $line =~ = ($line =~ m/.+a=([0-9]+).+c=([0-9]+)/); print “$values[0] $values[1]\n”; contains (an array of strings): # a b c a=10 b=23 c=16 a=12 b=43 c=17 a=63, b=2, c=999

AE6382 Perl l Support for objects u use Modulename; (include class definition) u $var = Modulename::new(); (instantiate object) u $var->method(...); (invoke method) u $var->{property}; (access property) l Does not have a class keyword, a class is defined as a Perl module where the functions are invoked as methods and the use of the bless keyword.

AE6382 M/S Scripting Documentation l Script56.chm is the Windows scripting documentation file l Local copy 382/MS_scripting/

AE6382 JavaScript / JScript l General purpose scripting language l Usually appears only in web browsers l Available on most platforms u In Windows Jscript is available as an ActiveX scripting engine, when run under the Windows Scripting Host it can functions as a general scripting system l Pros u Its syntax is very much like C u It has support for objects l Cons u Limited availability u Has limited access to host system (security feature)

AE6382 JavaScript / JScript l Variables u Typeless, refer to primitive types and objects u Can be arrays u Declared with var statement l Uses the usual set of C operators with some additions l Statements are terminated with ; l Comments marked with // and /*... */ l Functions and methods are declared with function name (...) {... }

AE6382 JavaScript / JScript l Loop statements var stdout = WScript.StdOut; var i; for (i=0 ; i < 10 ; i++) { stdout.WriteLine(“i=“+i); } var stdout = WScript.StdOut; var stdin = WScript.StdIn; while (! stdin.AtEndOfStream) { line = stdin.ReadLine() stdout.WriteLine(line); } var stdout = WScript.StdOut; var array = new Array(3); array[0] = 2; array[1] = 12; array[2] = 70; for (var value in array) { stdout.WriteLine("Value: "+array[value]); }

AE6382 JavaScript / JScript l Logical statements if (i == 5) { stdout.WriteLine(“Equality failed); } if (i == 1) { stdout.WriteLine(“Group 1”); } else { stdout.WriteLine(“Unknown group”); } if (i == 1) { stdout.WriteLine(“Group 1”); } else if (i == 2) { stdout.WriteLine(“Group 2”); } else if (i == 3) { stdout.WriteLine(“Group 3”); } else { stdout.WriteLine(“Unknown group”); }

AE6382 JavaScript / JScript l Regular Expression Support var stdout = WScript.StdOut; var stdin = WScript.StdIn; var re = new RegExp(".*error.*","i"); while (! stdin.AtEndOfStream) { var line = stdin.ReadLine(); if (line.match(re)) { stdout.WriteLine(line); }

AE6382 JavaScript / JScript l Regular Expression Support var stdout = WScript.StdOut; var stdin = WScript.StdIn; var re1 = new RegExp("^#","i"); var re2 = new RegExp(".+a=([0-9]+).+c=([0-9]+)"); var lines = new Array(4); lines[0] = "# a b c"; lines[1] = " a=10 b=23 c=16"; lines[2] = " a=12 b=43 c=17"; lines[3] = " a=63, b=2, c=999"; for (var line in lines) { stdout.WriteLine(lines[line]); if (lines[line].match(re1)) continue; re2.exec(lines[line]); var avalue = RegExp.$1; var cvalue = RegExp.$2; stdout.WriteLine(avalue+", "+cvalue); } // lines contains (an array of strings): // # a b c // a=10 b=23 c=16 // a=12 b=43 c=17 // a=63, b=2, c=999

AE6382 JavaScript / JScript l Object support u var obj = new Object(); (instantiate object) u obj.method(...); (invoke method) u obj.property;(access property) u obj[“property”]; (access property)

AE6382 M/S Scripting Documentation l Script56.chm is the Windows scripting documentation file l Local copy 382/MS_scripting/

AE6382 VBScript l General purpose scripting language l Only available on Windows u Available as an ActiveX scripting engine, when run under the Windows Scripting Host it has general usage u Can be used as the client-side scripting in IE l Pros u Simple syntax (Basic) u Has support for objects l Cons u Windows only

AE6382 VBScript l Variables u Typeless, refer to primitive types and objects u Can be arrays u Declared with Dim statement l Uses a small subset of C operators l Statements are terminated by the end of line l Comments marked with ‘ (single quote character) l Subroutines Sub name

AE6382 VBScript l Loop statements Dim i i = 0 For i=0 To 9 Step 1 WScript.StdOut.WriteLine "i=" & i Next Do While Not WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.ReadLine() WScript.StdOut.WriteLine(line) Loop Dim d 'Create a variable Set d = CreateObject("Scripting.Dictionary") d.Add "0", "Athens" 'Add some keys and items d.Add "1", "Belgrade" d.Add "2", "Cairo" For Each I in d Document.frmForm.Elements(I).Value = D.Item(I) Next Do Until WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.ReadLine() WScript.StdOut.WriteLine(line) Loop

AE6382 VBScript l Logical statements If i = 5 Then WScript.StdOut.WriteLine “Value is “ & i End If If i = 1 Then WScript.StdOut.WriteLine“Group 1” Else WScript.StdOut.WriteLine “Unknown group” End If If i = 1 Then WScript.StdOut.WriteLine “Group 1” ElseIf i = 2 Then WScript.StdOut.WriteLine “Group 2” ElseIf i = 3 Then WScript.StdOut.WriteLine “Group 3” Else WScript.StdOut.WriteLine “Unknown group” End If

AE6382 VBScript l Regular Expression Support Dim re Set re = New RegExp re.Pattern = ".*error.*" re.IgnoreCase = True Do While Not WScript.StdIn.AtEndOfStream Dim line line = WScript.StdIn.Readline If re.Test(line) Then WScript.StdOut.WriteLine line End If Loop

AE6382 VBScript l Regular Expression Support Dim line Dim i Dim match Dim re1, re2, matches, submatches Dim lines(4) lines(0) = "# a b c" lines(1) = " a=10 b=23 c=16" lines(2) = " a=12 b=43 c=17" lines(3) = " a=63, b=2, c=999" set re1 = New RegExp set re2 = New RegExp re1.Pattern = "^#" re2.Pattern = ".+a=([0-9]+).+c=([0-9]+)" For i=0 To 3 line = lines(i) WScript.StdOut.WriteLine "--> " & line If Not re1.Test(line) Then ' WScript.StdOut.WriteLine line Set matches = re2.Execute(line) Set match = matches(0) WScript.StdOut.WriteLine match.SubMatches(0) & ", " & match.SubMatches(1) End If Next ' lines contains (an array of strings): ' # a b c ' a=10 b=23 c=16 ' a=12 b=43 c=17 ' a=63, b=2, c=999

AE6382 VBScript l Object support u Set obj = New Object(instantiate object) u obj.method(...)(invoke method) u obj.property(access property)

AE6382 Tcl l General purpose scripting language l Available on most platforms u In Windows it can run standalone an is also available as an ActiveX scripting engine l Pros u Interpreter has a small footprint u Easily embedded u Extensible using C l Cons u Strange syntax

AE6382 Tcl l Variables u Strings are the basic type u Can create lists and arrays l Uses the expr command to evaluate expressions l Format cmd op op... op l set var value (set counter 5) l Reference value: $counter (set i $counter) l Use [... ] to evaluate immediately

AE6382 Tcl l Loop statements for (set i 0} {$i < 10} {incr i 3} { lappend aList $i } set aList set i 1 foreach value { } { set i [expr $i * $value] } set i foreach x [list $a $b [foo]] { puts stdout “x = $x” } set i 1 while {$i <= 10} { set product [expr $product * $i] incr i } set product

AE6382 Tcl l Logical statements if {$i == 5} { puts stdout “Equality failed” } if {i == 1} { puts stdout “Group 1” } else { puts stdout “Unknown group” } if {i == 1} { puts tdout “Group 1” } elseif (i == 2) { puts tdout “Group 2” } elseif (i == 3) { puts stdout “Group 3” } else { puts stdout “Unknown group” }

AE6382 Tcl l Logical statements if {$x == 0} { puts stderr “Divide by zero” if (i == 1) { stdout.WriteLine(“Group 1”); } else { stdout.WriteLine(“Unknown group)”; } if (i == 1) { stdout.WriteLine(“Group 1”); } else if (i == 2) { stdout.WriteLine(“Group 2”); } else if (i == 3) { stdout.WriteLine(“Group 3”); } else { stdout.WriteLine(“Unknown group”); }

AE6382 Python l General purpose scripting language l Available on most platforms u On Unix/Linux it runs standalone using #! script file convention u In Windows it can run standalone an is also available as an ActiveX scripting engine l Designed from the start as an object oriented language l Pros u Has wide support and runs everywhere u Jython is a version coded in Java and can access Java classes directly l Cons u Has a syntax based on formatting

AE6382 Python l Variables u Typeless u Scalar name = “sam” u Lists names = [“sam”, “bill”, “ted”] u Tuples (1,2,5,20) u Dictionaries rooms = {“sam”:302,”bill”:305,”ted”:401} l Namespace separation (packages) l Block structure is indicated by spacing l Strings are immutable

AE6382 Python l Loop statements Count = 0 for line in range(0..10): count = count + 1 print count Count = 10 While count < 10: count = count + 1

AE6382 Python l Conditional statements Value = 2 if value%2 == 0: print “Value is even” else: print “Value is odd”

AE6382 Python l Object support u Class definition u Object instantiation – obj = Special() u Method invocation – obj.method1(…) class Special: def __init__(self): self.count = 0 def method1(self,…): … def method2(self,…): …

AE6382 Ruby l General purpose scripting language l Available on most platforms u On Unix/Linux it runs standalone using #! script file convention l Designed from the start as an object oriented language l Pros u Is becoming widely used u Has a more conventional syntax without the clutter of C and Perl l Cons u Is relatively new on scene

AE6382 Ruby l Variables u Typeless u $global_variable u u local_variable l Types of variables u Scalar name = “sam” u Arrays names = [“sam”, “bill”, “ted”], names[2] u Hashes rooms = {“sam”:302,”bill”:305,”ted”:401}, rooms{“sam} l Namespace separation

AE6382 Ruby l Loop statements count = 1 while count < 10 count = count + 1 end count = 1 until count == 10 count = count + 1 end loop count = count + 1 end count = 1 begin count = count + 1 end while count < 10 count = 1 begin count = count + 1 end until count == 10

AE6382 Ruby l Conditional statements value = 6 if value%3 == 0 print “remainder 0” elsif value%3 == 1 print “remainder 1” else print “remainder 2” end value = 6 unless value == 6 print “value is not 6 end print “stop” if value == 0

AE6382 Ruby l Object support u Class definition u Object instantiation – obj = special.new u Method invocation – obj.method1(…) class special def initialize … end def method1(…) … end def method2(…) … end

AE6382 Scripting in Unix l The usual method of executing a script in Unix/Linux is to include the location of the interpreter on line 1 u #!/usr/bin/perl u #!/usr/bin/sh l The script must be readable and executable by the user attempting to run it

AE6382 Scripting in Windows l The usual method of executing a script in windows is to associate a file extension with the interpreter u file.plPerl script u file.pyPython script u file.cmdCommand file l Alternate methods are used for scripts that are to be run by resident ActiveX scripting engines u wscript u cscript u wsf – Windows Scripting File u hta – HTML Applications

AE6382 M/S Scripting Documentation l Script56.chm is the Windows scripting documentation file l Local copy 382/MS_scripting/

AE6382 Scripting in Windows l sample1.js u execute from cmd prompt> cscript sample1.js // Get the stdin and stdout descriptors // The WScript object is created automatically by WSH var stdin = WScript.StdIn; // properties var stdout = WScript.StdOut; // Get the value to pass to program stdout.WriteLine("Enter value for i: "); var i = stdin.ReadLine(); stdout.WriteLine("Enter value for j: "); var j = stdin.ReadLine(); // Create an instance of the WshShell object (COM object) var WshShell = new ActiveXObject("WScript.Shell"); // Run with access to programs I/O var WshScriptExec = WshShell.Exec("program1"); // Write to the running programs stdio WshScriptExec.StdIn.WriteLine(" "+i+" "+j); // Wait for the running program to exit while (WshScriptExec.Status != 1) { ; } // Read from the running programs stdout var output = WshScriptExec.StdOut.ReadLine(); stdout.WriteLine("Output from program: "+output);

AE6382 Scripting in Windows l sample1.wsf u execute from cmd prompt> sample1.wsf // Get the stdin and stdout descriptors // The WScript object is created automatically by WSH var stdin = WScript.StdIo; // properties var stdout = WScript.StdOut; // Get the value to pass to program stdout.WriteLine("Enter value for i: "); var i = stdin.ReadLine(); stdout.WriteLine("Enter value for j: "); var j = stdin.ReadLine(); // Create an instance of the WshShell object (COM object) var WshShell = new ActiveXObject("WScript.Shell"); // Run with access to programs I/O var WshScriptExec = WshShell.Exec("program1"); // Write to the running programs stdio WshScriptExec.StdIn.WriteLine(" "+i+" "+j); // Wait for the running program to exit while (WshScriptExec.Status != 1) { ; } // Read from the running programs stdout var output = WshScriptExec.StdOut.ReadLine(); stdout.WriteLine("Output from program: "+output);

AE6382 Windows Scripting Host l WSH is the context within which VBScript and JScript run l PerlScript and PythonScript are also available l Start WSH scripts using cscript or wscript u cscript - console mode u wscript - windows mode, no stdin, stdout, or stderr l The WSF format can contain several scripts in one text file

AE6382 Component Object Model COM l Why use COM l The Component Object Model (COM) is the key to making full use of Windows l COM is accessible from C++ and scripting l Scripting an application is called automation l Also referred to as ActiveX and OLE

AE6382 Objects in COM l A class defines an object u Properties are variables u Methods are functions l When a class is instantiated an object is created u Each object has its own copy of the properties u When a method is invoked it operates on only the object that is the target of the invocation

AE6382 Objects in COM l An application can make many classes available for use via COM l The client code (a script for example) must create an instance of the class (an object) and save a reference in a variable l The application’s methods may then be invoked on that object to access the application l Using Windows Script Components (see Script56.CHM) scripts can be made available to other COM clients via COM

AE6382 Objects in COM l Two methods for accessing COM u vtables – C/C++ u Dispatch – scripts l Classes contain properties and methods l Collections are classes that enumerate objects Dim worksheets, worksheet, excel... Set worksheet = excel.Worksheets(“sheet1”)... Set worksheet = excel.Worksheets(2)... ‘ excel is an instance of Excel.Application ‘ worksheet is an instance of Worksheet class ‘ ‘ implied Item method ‘ Set worksheet = excel.Worksheets.Item(2)

AE6382 Creating a COM Object Instance l Scripting languages have a mechanism for instantiating a COM class Perl: use Win32::OLE;... my $excel = Win32::OLE->new(‘Excel.Application’); JScript: var excel = new ActiveXObject(“Excel.Application”); VBScript: Dim excel Set excel = CreateObject(“Excel.Application”); Python: import win32com.client... excel = win32com.client.Dispath(“Excel.Application”);

AE6382 Creating a COM Object Instance l Once top level object has been created the remaining hierarchy is accessed as per the language’s normal object mechanism l Tcl and Ruby can also instantiate COM objects

AE6382 Object Models l Every COM enabled Windows application has an object model l Requires knowledge of object model to access application l Discovering the object model u Use documentation (Office is documented) u Use an object browser and trial and error – ActiveState Perl includes a simple Object Browser – Visual Studio include an Object Browser

AE6382 Example - Perl #!/usr/bin/perl use strict; use Win32::OLE qw(in with); use Win32::OLE::Const 'Microsoft Excel'; use Win32::OLE::Variant; use Win32::OLE::NLS qw(:LOCALE :DATE); # Program dies on errors $Win32::OLE::Warn = 3; # The use of ' rather than " is noted my $excel_file = 'c:\latham\ae8801d\perltut.xls'; # Create a connection to Excel # Try to use an existing object else create a new object my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application','Quit'); print "ERROR: ",$Win32::OLE::LastError,"\n" if $Win32::OLE::LastError; # Turn off any alter boxes (such as the SaveAs response) $Excel->{DisplayAlerts} = 0; # Make Excel visible on the desktop $Excel->{Visible} = 1; # Add a workbook and save the file my $Book = $Excel->Workbooks->Add(); $Book->SaveAs($excel_file); # To open an existing file replace above with # my $Book = $Excel->Workbooks->Open($excel_file);

AE6382 Example – Perl # Create a reference to a worksheet my $Sheet = $Book->Worksheets('Sheet1'); $Sheet->Activate(); $Sheet->{Name} = "sample_sheet"; # Insert some data into the worksheet my ($mday,$mon,$year) = (localtime(time))[3,4,5]; $year += 1900; my $str = $mon.'/'.$mday.'/'.$year; $Sheet->Range("a1")->{Value} = $str; $Sheet->Range("c1")->{Value} = "This is a long piece of text"; # Save $Book->SaveAs($excel_file); # Set cell colors via a loop foreach my $y (1..56) { my $range = 'b'.$y; $Sheet->Range($range)->Interior->{ColorIndex} = $y; $Sheet->Range($range)->{Value} = $y } # Re-format existing cell my $range = 'A1'; $Sheet->Range($range)->Interior->{ColorIndex} = 27; $Sheet->Range($range)->Font->{FontStyle} = "Bold"; $Sheet->Range($range)->{HorizontalAlignment} = xlHAlignCenter; # Set column widths = qw(A:B); foreach my $range { $Sheet->Columns($range)->AutoFit(); } $Sheet->Columns("c")->{ColumnWidth} = 56;

AE6382 Example - Perl # Insert borders around cells = qw(xlEdgeBottom xlEdgeLeft xlEdgeRight xlEdgeTop xlInsideHorizontal xlInsideVertical); $range = "b1:c56"; foreach my $edge { with (my $Borders = $Sheet->Range($range)->Borders(eval($edge)), LineStyle => xlContinuous, Weight => xlThin, ColorIndex => 1); } # Insert a picture my $picture1 = $Excel->Worksheets('Sheet2')->Shapes->AddPicture('c:\latham\ae8801d\image.jpg',-1,-1,0,0,200,200); $Excel->Worksheets('Sheet2')->{Name} = "B-17"; #$picture1->{Left} = 100; #$picture1->{Top} = 100; # Save $Book->SaveAs($excel_file); # Create a chart my $Sheet3 = $Excel->Worksheets('Sheet3'); my $Chart1 = $Sheet3->ChartObjects->Add(200,200,200,200); $Sheet3->{Name} = "Chart Example"; $Chart1->Chart->ChartWizard({Source => $Sheet3->Cells(1)}); $Chart1->Chart->SeriesCollection(1)->{Values} = [19,3,24,56,34,33,16,10,3,100]; # Print a list of the worksheets foreach my $Sheet (in $Book->{Worksheets}) { print "Worksheet:\t",$Sheet->{Name},"\n"; } print "Ready to quit"; <>; exit;

AE6382 Example - JScript // var fso = new ActiveXObject("Scripting.FileSystemObject"); var excel = new ActiveXObject("Excel.Application"); excel.DisplayAlerts = 0; excel.Visible = 1; var book = excel.Workbooks.Add(); var sheet = book.Worksheets("Sheet1"); sheet.Activate(); sheet.Name = "sample sheet"; var wk2 = excel.Worksheets("Sheet2"); var pic1 = wk2.Shapes.AddPicture("c:\\latham\\ae8801d\\image.jpg",-1,-1,100.,100.,100.,50.); wk2.Name = "B-17"; pic1.Left = 100; pic1.Top = 100; WScript.Echo("Hello"); WScript.Sleep(2000); excel.Worksheets(1).Activate(); WScript.Sleep(2000); excel.Worksheets(2).Activate(); WScript.Sleep(2000); excel.Worksheets(3).Activate(); WScript.Sleep(2000); //var stdout = WScript.StdOut; //var stdin = WScript.StdIn; //var answer = stdin.ReadLine(); //stdout.WriteLine(answer); excel.Quit(); // var in = File("stdin"); // fgets(in);

AE6382 Example - Python import win32com.client excel = win32com.client.Dispatch("Excel.Application","Quit") excel.DisplayAlerts = 0 excel.Visible = 1 book = excel.Workbooks.Add() sheet = book.Worksheets("Sheet1") sheet.Activate() sheet.Name = "sample sheet" picture = excel.Worksheets("Sheet2").Shapes.AddPicture("c:\\latham\\ae8801d\\image.jpg",-1,-1,100.,100.,100.,50.) excel.Worksheets("Sheet2").Name = "B-17" picture.Left = 100 picture.Top = 100 # Create a chart #sheet = excel.Worksheets('Sheet3'); #chart1 = sheet.ChartObjects.Add(200,200,200,200); #sheet.Name = "Chart Example"; #chart1.Chart.ChartWizard({Source => $Sheet3->Cells(1)}); #chart1.Chart.SeriesCollection(1)->{Values} = [19,3,24,56,34,33,16,10,3,100]; print "Hello from excel1.py" answer = raw_input("Quit ? ") excel.Quit();