Skip navigation

Tag Archives: object oriented programming

So similarly to the logging class object I posted back on December 16th; I’m posting a dictionary wrapper object I’ve built to enhance it’s (scripting.dictionary) usage for creating indexed arrays, concatenating strings, etc…

As with the Logging class object, it must be instantiated to use, so…

Dim Dict
Set Dict = New cls_Dict
 
Call Dict.Add("stuff","my message")
	Wscript.Echo Dict.Key("stuff") 

Wscript.Quit(0)

The object code is below, I’ll give a walkthrough on it’s usage after the code.

'============================================================================
'Dictionary Class ===========================================================
'============================================================================

Class cls_Dict
'Class wrapper for the scripting.dictionary
	Private oDict, oNet, Comparemode, strSplit, oFso, oWShell

'---------------------------------------------------------

Private Sub Class_Initialize()
'Dictionary class init subroutine    
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
		Set oDict 	= CreateObject("Scripting.Dictionary")
		Set oNet	= CreateObject("Wscript.Network")
		Set oFso	= CreateObject("Scripting.FileSystemObject")
		Set oWShell = CreateObject("Wscript.Shell")
		oDict.CompareMode = 1
			strSplit = "|:|"
		Call oDict.Add("CurrentDir",Left(WScript.ScriptFullName, _
			(Len(WScript.ScriptFullName)-Len(WScript.ScriptName))))
		Call oDict.Add("computername", oNet.Computername)
		Call oDict.Add("Windir",LCase(oWShell.ExpandEnvironmentStrings _
			("%windir%")))
		Call oDict.Add("CurrentUser",LCase(oNet.UserName))
		Call SetOsVer
End Sub

'---------------------------------------------------------

Private Sub Class_Terminate()
'Dictionary class termination subroutine
	If IsObject(oDict) then Set oDict = Nothing
End Sub

'---------------------------------------------------------

Public Property Get CurrentDir
'Returns Current Directory for the script
	CurrentDir = oDict.Item("CurrentDir")
End Property

'---------------------------------------------------------

Public Property Get ComputerName
'Returns the machine name for the current machine
	ComputerName = oDict.Item("computername")
End Property

'---------------------------------------------------------

Public Property Get CurrentUser
'Returns the machine name for the current machine
	CurrentUser = oDict.Item("CurrentUser")
End Property

'---------------------------------------------------------

Public Property Get Windir
'Returns the windows directory for the local machine
	Windir = oDict.Item("windir")
End Property

Public Property Get SystemRoot
'Returns the appropriate system directory system32 or syswow64

	If InStr(StrReverse(oDict.Item("CurrentOsVer")), "46x") <> 0 Then 
		SystemRoot = Windir & "\syswow64"
	Else
		SystemRoot = Windir & "\system32"
	End If

End Property
'---------------------------------------------------------

Public Sub Add(strKey,strValue)
'Method to Add a key and item
	If Debugmode Then On Error Goto 0 Else On Error Resume Next

    Dim EnvVariable, strSplit

    	strSplit = Split(strValue, "%")
	If IsArray(strSplit) Then 
    	EnvVariable = oWShell.ExpandEnvironmentStrings _
    		("%" & strSplit(1) & "%")
    	strValue = strSplit(0) & EnvVariable & strSplit(2)
    			If strValue = "" Then
    				strValue = strSplit(0)
    			End If
    End If
	If oDict.Exists(strKey) Then
		oDict(strKey) = Trim(strValue)
	Else
		oDict.Add strKey, Trim(strValue)
	End If
End Sub

'---------------------------------------------------------

Public Function Exists( strkey)
'Method to check existance of a key
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	
	If oDict.Exists(strKey) then 
		Exists = True
	Else
		Exists = False
	End If

End Function

'---------------------------------------------------------

Public Function Keys()
'Method to retrieve an array of keys
    If Debugmode Then On Error Goto 0 Else On Error Resume Next

	If IsObject(oDict) Then
		Keys = oDict.Keys
	End If
End Function

'---------------------------------------------------------

Public Function Items()
'Method to retrieve an array of items
    If Debugmode Then On Error Goto 0 Else On Error Resume Next

	If IsObject(oDict) Then
		Items = oDict.Items
	End If
End Function

'---------------------------------------------------------
Private Sub SetOsVer()
'Sets a comparable OSVer key item into the dictionary
		If DebugMode Then On Error Goto 0 Else On Error Resume Next

		Dim x, VersionCheck	
		
	VersionCheck = owShell.RegRead("HKLM\software\microsoft\" _
					& "windows nt\currentversion\productname")

			If ofso.folderexists("c:\windows\syswow64") Then
				x = "x64"
			Else
				x = "x86"
			End If
		Call oDict.Add("CurrentOsVer",VersionCheck & " " & x)
End Sub
	Public Property Get OsVer()
		OsVer = oDict.Item("CurrentOsVer")
	End Property

'---------------------------------------------------------
Public Property Get AppName()

	AppName = Left(WScript.ScriptName, Len(WScript.ScriptName) - 4)
End Property 

'---------------------------------------------------------

Public Property Get Key( strKey)
'Property to retrieve item value from specific key
    If Debugmode Then On Error Goto 0 Else On Error Resume Next

		Key = Empty
	If IsObject(oDict) Then
		If oDict.Exists(strKey) Then Key = oDict.Item(strKey)
	End If
End Property

'---------------------------------------------------------

Public Sub ItemJoin(strKey, strItem)
'Method to concactenate new items under one key at the end of the string
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	Dim concat
	If Not oDict.Exists(strKey) Then
		Call oDict.Add(strkey, stritem)
	Else
		concat = oDict.Item(strKey)
		concat = concat & " " & strItem
			oDict.Remove(strKey)
		Call oDict.Add(strKey,concat)
	End If
End Sub

'---------------------------------------------------------

Public Sub ItemList( strKey,  strItem)
'Method to concactenate new items under one key at the end of the string
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	Dim concat
	If Not oDict.Exists(strKey) Then
		Call oDict.Add(strkey, stritem)
	Else
		concat = oDict.Item(strKey)
		concat = concat & "|:|" & strItem
			oDict.Remove(strKey)
		Call oDict.Add(strKey,concat)
	End If
End Sub

'---------------------------------------------------------

Public Sub ItemJoinRev( strKey,  strItem)
'Method to concactenate new items under one key at the start of the string
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	Dim concat
	If Not oDict.Exists(strKey) Then
		Call oDict.Add(strkey, stritem)
		Exit Sub
	Else
		concat = oDict.Item(strKey)
		concat = strItem & " " & concat
			oDict.Remove(strKey)
		Call oDict.Add(strKey,concat)
	End If
End Sub
	
'---------------------------------------------------------	

Public Function ReturnArray( strKey)
'Method to return an item as an array
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	
	Dim ItemToSplit, ItemArray
	
	ItemToSplit = oDict.item(strKey)
	
	ItemArray = Split(ItemToSplit, strSplit)
	
	ReturnArray = ItemArray	
	
End Function
	
'---------------------------------------------------------	

Public Sub Remove( strKey)
'Method to remove a key value
	oDict.Remove(strKey)
End Sub

'---------------------------------------------------------

Public Sub RemoveAll()
'Method to remove all data from the dictionary
	oDict.RemoveAll
End Sub

End Class

 

So let’s look at the exposed functionality added to or exposed from the scripting dictionary by this object. 

Methods:

 

  • Add

Modified to resolve and accept environment variables, and is also the sole method for adding and replacing keys and their item values

  • ItemJoin

Concatenates the item value to the end of the existing key item

  • ItemJoinRev

Concatenates the item value to the beginning of the existing key item

  • ItemList

Creates an array under an existing key or creates if it doesn’t exist

  • ReturnArray

Returns an array if array exists under the key

  • Exists

Checks if key exists, returns boolean value

  • Items

Returns all items in an array

  • Keys

Returns all keys in an array

  • Remove

Remove a key and item value

  • RemoveAll

Dump entire contents of the dictionary object

 

Properties:

 

  • Key

This is modified from the original usage, and returns the item for the given key. Add is used to modify the key only.

  • AppName

Returns script name, minus extension value

  • ComputerName

Returns the netbios name of the machine

  • CurrentDir

Returns the current working directory of the script

  • CurrentUser

Returns the current logged on user ID (or executing id)

  • OsVer

Returns a OS Version and arch

  • SystemRoot

Returns the environment path for the system root

  • Windir

Returns the environment path for the Windows directory


Feel free to hit me up about usage or any other questions you might have regarding why I did things a certain way, or with any changes you might have made to improve this code.

Alright, so I received a pretty loaded technical topic from my good friend Matthew.  Mind you I asked for a technical topic to write about, and he did provide one but the question was:

What is an API and why/when would you use one?

Now seeing as how I already stated that is a loaded question, it deserves a bit of programming fundamentals.  I promise to keep this high level, but with enough detail that a novice programmer could glean a bit of workable information from it.

First I want to explain some basic program flow and design (paradigms).  I’m going to provide some very basic examples of procedural programming and object oriented programming using php (high level).  Lets begin with a very basic example of procedural code.

Put simply procedural programming is just building things to run in a sequence but dividing it up into functions or subroutines.  I’ve demonstrated examples of this in previous posts, but here’s a simple example:


<?php
	example("functions");
	echo '<br />';
	endthis("example");

function example($arg)
{
	echo "This is a very simple example of $arg";
}

function endthis($arg)
{
	echo "This is the end of our $arg";
}
?>

Ok, so what do we have here?

We have a prescribed run order, with a fixed goal in mind.  We are calling the function example with the argument string “functions”, echoing a break, then calling the function endthis with the string argument “example”. 

Simple enough, now why is this important?

Well it’s important to see the way I am passing arguments INTO the function in order for it to produce an output.

Now in more complex applications the best thing to do is to break apart your code and build it into objects (a collection of functions and variables) that perform like tasks and tie them together.  This is object oriented programming.

Lets just take a quick look at a sample object and how it works (stick with me, this is will become relevant to APIs I promise):


<?php
	$object = New SaySomething;
	
$object->set_words("jimmy crack corn and I don't care");

echo $object->get_words();

class SaySomething {
	var $words;
		
		function set_words($new_name) {
			$this->words = $new_name;
		}
		
		function get_words() {
			return $this->words;
		}
}
?>

Ok, we instantiated the object we created, passed a string to it, then retrieved the sting.

Think of it like this, we have a program, we are loading it.  Once we have that program loaded we can begin to tell it what to do.  You can have as many instances of this object or other objects as your memory can handle. 

This paradigm affords us a massive amount of flexibility by giving us a standalone object for completing multiple like tasks.  It’s also easily extensible, allowing us to create child objects that inherit the functionality of their parent without having to modify the parent.  That will allow us over time to build a framework so to speak that we could use to quickly develop new applications on.

So, what does this all have to do with an API?

Looking at how the OOP paradigm communicates with each individual part, instantiating and then passing and receiving content.  An API isn’t much different than that.  The API simply exposes an application for communication.  It allows for interoperability from one application to another by passing messages to each other.

An example of common social networking APIs allow you to call for user information, as well as passing user information back.  Let’s use Twitter for an example. 

I want to post something to twitter, but from a custom application I’ve made.  I need a way to pass that information from my application to twitter.  The API is the interface point to allow that communication.  In a sense, twitter becomes my applications twitter object by virtue of calling and using the API (there are some stark differences, but generally this is a true statement).

The difference is, using the API doesn’t require intimate knowledge of what is going on behind the scenes.  I won’t be modifying anything within the application.  I’m simply sending and receiving information through the API.  The same is true for building an API, less is often more.  As you can imagine exposing your applications to external input and output can be a dangerous game; but that’s a much larger subject. 

The general take a way here is that although the application may consist of multiple functions and/or objects the API simply allows you to interlink one or more applications via messages.

A friend of mine Tom Miller put it rather well in a conversation we had over the subject.  “An API is a lot like a remote control”

I want the TV to change channels, I pick up the remote, press the channel up button, and the channel changes.  The remote IS the API.  My hand is the program communicating to it, and the TV is the program receiving the signal.  At no point do I need to understand how the remote works, or how the TV changed it’s channel. 

Ok, so when/why would I use an API?

That’s generally a design thing, but in most cases when you are building a platform or an application you want to improve it’s usability and not limit it.  Extensibility is the name of the game, so it makes sense to make something that would allow users to integrate other things with your application.

It’s good design because it achieves two major things towards (what I would consider) application design success.

1) It opens your platform up to the imagination of it’s user which can produce some really neat things.

2) It creates an operating environment for users with applications that depend on your platform which increases usage.

Hopefully this hasn’t left you completely confused, but like I said, it was a loaded question.