Array.Push in VBScript

For those of you who develop in PHP and Javascript (and I’m sure it exists in other languages as well), the Array.Push method is something that is lacking in VBScript. Many other people have tried to implement a method to achieve this; some better than others.

This is my solution below.

Eventually, I’ll be putting this into an Array class that I will distribute on here. For now, here is the function that I’ve created to push data into an array.

Features:

  • It can push content into a 1 dimensional array or a 2 dimensional matrix.
  • You can pass an existing array to the push function or an empty variable (that intend on becoming your array)
  • You can pass a string or an array to push. If you push an array, it expects that the array is a row to add to the array.

Usage

push(yourArray, yourData)

Requires:

  • yourArray As Array or yourEmptyVar: A variable that will be passed to the function By Reference that is either an array or an empty variable. The returned item will be an array (naturally);
  • yourData As Array or a variable containing any type of data: The information that is to be added to your array. If it’s an array, it will expect that the data is in the form of a row (meaning that this array contains one row (y axis)  and multiple columns (x axis)).

Example:

Dim myArray

Call push(myArray, "some data")

Function push(ByRef arr, ByVal row)
	Dim cellValue
	Dim r: r=0
	Dim c: c=0
	Dim dummyVar

	If IsArray(arr) Then

		On Error Resume Next
		dummyVar = UBound(arr, 2) 'Determine if it's a 2D matrix.

		If (CLng(Err.Number) > 0) = TRUE Then ' 1D arrays go thru here.
			On Error Goto 0
			c = UBound(arr) + 1
			Redim Preserve arr(c)
			arr(UBound(arr)) = row

		Else 'Matrices go through here.
			On Error Goto 0
			Redim Preserve arr(UBound(arr), UBound(arr, 2) + 1) 'add a row
			If IsArray(row) Then
				For r = 0 To UBound(row) ' run thru each column in row
					arr(r, UBound(arr,2)) = row(r) 'add the cell
				Next
			Else
				arr(0, UBound(arr,2)) = row
			End If

		End If

	Else

		If IsArray(row) Then
			If UBound(row) < 2 Then 'If this is an array, then it should only contain one row.
				arr = row
			End If
		Else
			Redim arr(0)
			arr(0) = row
		End If

	End If

	If IsArray(arr) Then push = UBound(arr)

End Function
Posted in VBScript | Leave a comment

Cryptography Class: Encrypt a String in VBScript

Introducing the Cryptography Class: this is a method to encrypt a string using nothing but VBScript, and it doesn’t require any installed components. It’s based on one of the simplest cipher methods known as the Vernum Cipher, and although it would take some time for a hacker to crack, I wouldn’t rely on it solely to protect data. It merely adds another layer of security.

I used it to encrypt my data going from one page to another. If I really want to protect my data from phishing techniques, I encrypt the data coming from my form and then decrypt it once it reaches the server.

This code was mostly developed by 4GuysFromRolla, and I adapted their code into this class.

The Vernam Cipher was invented by none other than Gilbert Vernam (he was an AT&T engineer), in 1918. The ciphertext is generated by combining ASCII plaintext with a “one-time pad” or key. The key is combined with the plaintext stream by mod 2 (Xor), thus creating the encrypted cyphertext.

Download the Cryptography Class now!

Features

  • Uses an encryption key. Without this key you will not be able to decrypt your data.
  • You can optionally set an application GUID variable and the encryption will add that to the complexity of the encryption.

Usage

Encrypt
cryptographyObject.Encrypt(yourString as String)
Encrypts your string

Decrypt
cryptographyObject.Decrypt(yourString as String)
Decrypts your string

Options

Key
cryptographyObject.Key = “yourEncrptionKey”
Sets an encription key of your choice.

GUID
cryptographyObject.GUID = “yourGUIDserial as GUID”
Set a GUID serial number. Careful! If you use this, ensure that your using it as an Application variable so that you can decrypt it server site, because GUIDs are generated randomly upon request, so if it doesn’t match, the decrypting won’t work.

Example:

	Dim Encrypt
	Dim regularString
	Dim encryptedString
	Dim encryptionKey

	Set Encrypt = New Cryptography

	Application("GUID")	= GetGuid

	regularString 		= """The world was my oyster, but I used the wrong fork."" -- Oscar Wilde"
	encryptionKey 		= "ClockWorkOrange"
	Encrypt.key 	= encryptionKey 'Required.
	Encrypt.GUID 	= Application("GUID") 'This is optional.
	encryptedString 	= Encrypt.Encrypt(regularString)

	Response.Write("<strong>This is the original string:</strong> " & regularString) & "<br /><br />"
	Response.Write("<strong>This is the string encrypted:</strong> " & encryptedString) & "<br /><br />"
	Response.Write("<strong>This is the string decrypted:</strong> " & Encrypt.Decrypt(encryptedString)) & "<br /><br />"
	Response.Write("<strong>This is the application GUID:</strong> " & Application("GUID"))

	Function GetGuid()
		Dim TypeLib
        Set TypeLib = CreateObject("Scriptlet.TypeLib")
        GetGuid = Left(CStr(TypeLib.Guid), 38)
        Set TypeLib = Nothing
    End Function 

	Set Encrypt = NOTHING

Download the Cryptography Class now!

Posted in VBScript | Leave a comment

VBScript Validate Class

I know that Classic ASP is now considered very old, but there are still some applications out there built on it. In the next few weeks, I’ll be uploading some classes that I created that may prove useful to some users supporting older applications.

As my first segment, I’m sharing the Validate Class. This class validates variables usually from querystrings or form posts. As a security measure, all developers should be checking their variables before sending their data to the database, and all data should be considered dangerous. It’s just a best practice and highly recommended.

Download the Validate Class now!

Features

The class validates:

  • data type
  • length
  • malicious keywords or groups of characters like:
    • script
    • ;–
    • /*
    • */
    • @@
    • nchar
    • varchar
    • nvarchar
    • delete
    • execute
    • sysobjects
    • syscolumns
    • information_schema
  • Detects and converts strings that are encoded hexadecimally.

Usage

Method: Validate(yourString, dataType, stringLength)

Requires:

  • yourString (any type of data): the string that you wish to validate
  • dataType (as string): the datatype that you are expecting. Supported types are:
    • number: a numeric expression
    • username: alphanumeric, foreign and some special characters
    • email: any email. Must contain “@” and a “.”
    • url: any URL
    • password: alphanumeric and special characters. Cannot contain any spaces;
    • name: alphanumeric and foreign characters and spaces
    • session: only validates hex characters and dashes. Anything else is rejected.
    • desc: alphanumeric, foreign and special characters, spaces
    • alphanum: alphanumeric characters only
    • date: any valid date (according to VBScript)
    • serial:  alphanumeric and some special characters
    • off: turns off character validation (but still validates length and for harmful words)
  • length (as integer): the length that you are expecting.

Example:

	Dim cleanerTool
	Dim dirtyString
	Dim cleanString

	dirtyString = Request.QueryString("id") 'Get your dirty data... I'm expecting an numerical id.

	Set cleanerTool = New Validate 'Create the validation instance.
	cleanString = cleanerTool.validate(dirtyString, "number", 6) 'Clean the mofo!
	Set cleanerTool = NOTHING 'Clean up some memory (always important in Classic)

	Response.Write cleanString

(BTW, just as a side note, I don’t write my code in the Hungarian Style. I just believe that a variable name should be written in a self explanatory way. It’s just my way.)

Download the Validate Class now!

Posted in VBScript | 1 Comment

Message Class 2.1 for Mootools 1.3

I’m releasing a copy of my Message Class for Mootools 1.3.  The dependencies are the same and they are:

  • Array.Extras
  • Chain.Wait
  • Element.Measure
  • Element.Position
  • Element.ShortCuts

This version is not likely to work with Mootools 1.2.5 and under. You can still get that version here. In the coming year, any other updates will only be compatible with 1.3 and above. I’ve tried to do what I could to make this version compatible with the upcoming Mootools 2.0, so I eliminated anything in the class that is deprecated.

As usual, please let me know if you find any problems.

Posted in Mootools | 4 Comments

Message Class 2.0 Update

I spent a good week or more perfecting the stacking option of the Message Class and I think I nailed it down, and stabilized the code as can be reasonably expected. The stacking of messages added a great deal of complexity to the code, and I’m not surprised. Getting a div tag to stack one on top of the other is not easy when you have all the options that I originally created this class. But!… it’s done, and it works. See my other blog post about the Message Class for details about how the class works and how to use it.

Some key things that you should know that have changed.

1. I’ve eliminated the use of “eval” to run a callback, so if you used the string method to send run a function using the message class, it will not work. Now you’ll have to create an event. Again, an example of this is in my previous blog post.

2. There is one more dependency to be aware of: Array.Extras from the Mootools More section. You’ll need to add that to your code for this class to work. It’s very small and every useful. I had to take advantage of it.

Posted in Mootools | 2 Comments

Message Class 2.0

Brought to you by popular demand, the Message Class has been upgraded with a nifty new feature: STACKING! (Thanks to Adam and Co. great suggestions.)

Now, as an option, you can have the messages stack one on TOP (or bottom) of the other rather than displaying them over the last message. You can download this latest version by simply downloading the class again in the right-hand menu, or by clicking here.

Click here to stack a message.

There is a known issue! The stacking does go a little wonky once the other messages start to fade out. The reason for this is because each message that is displayed is an independent, stand-alone instance of the Message Class, and once a message fades out, it is destroyed. Therefore, there is no way for me to reliably know where the last message existed once it is destroyed. I’m still working on making this perfect, but for now, the stacking works, and if any of you have any suggestions, I welcome some advice. I do have an idea that I will try out, but for now, check it out, and let me know what you think.

ALSO… another very important note: the callback feature that I used in my class also included the option to send a string as a way to launch a function. It does so by using the Eval function. It is a very bad programming practice to use Eval, and here I went and used it anyway! What is wrong with me?! My bad! It’s dangerous (because you could use this class to launch malicious code easily – and I won’t let all you baddies out there to use my class in a malicious way), and besides… it’s just inefficient too.

So, future updates of this class will eliminate the use of Eval. You have been warned!

Posted in Mootools | Leave a comment

Dreamweaver Code Colouring for Mootools

Syntax highlighting is so useful, isn’t it? I think so, and I think you do too. So, I’m uploading a file so that you can enjoy the wonderful world of syntax highlighting for Mootools in Dreamweaver. Click here to download the Zip file.

This is what it looks like:Syntax highlighting for Mootools in Dreamweaver

Syntax highlighting for Mootools in Dreamweaver

Of course you can change the colours to the what you’re used to.

To install the xml files in the download, follow these instructions:

Windows XP users

Dreamweaver CS4

  1. Close Dreamweaver
  2. Go to C:\Program Files\Adobe\Adobe Dreamweaver CS4\configuration\CodeColoring\
  3. Find and backup file all of the XML files
  4. Use the XML files from the download and overwrite the XML files

Dreamweaver CS3

  1. Close Dreamweaver
  2. Go to C:\Documents and Settings\%username%\Application Data\Adobe\Dreamweaver 9\Configuration\CodeColoring\
  3. Find and backup file all of the XML files
  4. Use the XML files from the download and overwrite the XML files

Windows 7 users

Dreamweaver CS4

  1. Close Dreamweaver
  2. Go to C:\Users\%username%\AppData\Roaming\Adobe\Dreamweaver CS4\en_US\Configuration\CodeColoring
  3. Find and backup file all of the XML files
  4. Use the XML files from the download and overwrite the XML files

MacOS users

Dreamweaver CS4

  1. Close Dreamweaver
  2. Go to /Users/%name%/Library/Application Support/Adobe/Dreamweaver CS4/%localization(en_US)%/Configuration/CodeColoring
  3. Find and backup file all of the XML files
  4. Use the XML files from the download and overwrite the XML files

Credits

Unfortunately, I can’t take all the credit for it’s wonderfulness. Portions of the file were taken from Nerd-core.org, which has been “under construction” for some time now and has left a void that I am now filling with this post. I’ve made my own updates, and added my Message Class plugin so that it highlights appropriately.

Also, I should thank Sramek Design for saving me from the tedious task of having to go research where the files should go. They did the work for me, and I simply copied those instructions. So thanks!

Posted in Dreamweaver, Mootools | 3 Comments

Mootools Message Class

This Message Class is a simple Mootools plugin that replaces the a standard dialog box like javascripts built in alert method. Now you’ll will be sending a message to the user in style! Read on! It’s quite useful.

Before we get started, this is open source code and, like Mootools itself, it is released under the Open Source MIT Licence. But, please give me credit by leaving the url to this site in the js files. Thanks!

Say Method

Click on this to see.

// Simplest way to use the class...
new Message({
	icon: "okMedium.png",
	title: "Success!",
	message: "You have successfully messaged your user."
}).say();

Tell Method

You can get bossy with the “tell” method of the class by forcing the user to respond. Click on this to see.

// Here I'm creating an instance of the Message Class and storing it the msg variable.
var msg = new Message({
	icon: "cautionMedium.png",
	title: "Watch Out!",
	message: "You just might be a redneck!"
});
// Execute the command!
msg.tell();

Ask Method

You can also ask a question by using the ask method. (See how clever I am? I named the methods after the what they do!) You can also send a callback function to complete a transaction when the user chooses “Yes”. Wow! Think of the power! Get the class to perform a task by sending either a function in the form of a string, or an element that has an assigned click event. When the user clicks “Yes”, the class will fire the function or the click event (which ever you passed in the callback option).

Click on this to see.

new Message({
	icon: "mediumQuestion.png",
	title: "Question!",
	message: "If a woman is yelling at a man and he's not there to hear it, is he still wrong?",
	callback: "saySimple()"
}).ask();

Waiter, Comment and Tip Methods

There are all kinds of things that this bad-boy can do. Click on the following links to marvel at the possibilities!

You can create a waiter using the waiter method.
Click here to dismiss the waiter.

You can create a comment box pop up.

How the heck did I do that? Here’s the code:

document.id('commentLink').addEvent('click', function(e){
	// Just creating an object here so that you can see that it's possible to send one.
	// Imagine the power in that!
	var obj = new Element('div', {
		'id': 'dummy',
		'events': {
			'click': function(){
				sendComment();
				this.destroy();
			}
		}
	});
	new Message({
		icon: "speakMedium.png",
		iconPath: "/2010/images/",
		width: 300,
		fontSize: 14,
		passEvent: e,
		autoDismiss: false,
		title: 'Have a Comment?' ,
		message: '<textarea id="commentText" cols="3" rows="5" class="msgEditable"></textarea>',
		callback: obj
	}).say();
});
var sendComment = function(){
	new Message({
		icon: "okMedium.png",
		iconPath: "/2010/images/",
		title: "Received!",
		message: "We've received your comments, and we'll ...uhhh... get back to you."
	}).say();
}

You can even create a tool tip. Yeah… I know it’s a built-in plugin in Mootools, but I think that this does it better. (I could never get the Mootools tooltip plugin to work the way I wanted.) Besides, I already created this class, so extending it to do tips was simple. Click on these to see the tip method in action:

I’m a tip
…and I’m a tip
…and I’m a tip too!

With the tip method, the HTML is important because we use the rel property in the a tag to pass a title and a message. This way, you can set your tips right in the HTML.

<a href="javascript:" class="tips" rel="Tip!::This is tip #1">I'm a tip</a>
<a href="javascript:" class="tips" rel="Tip!::This is tip #2">...and I'm a tip</a>
<a href="javascript:" class="tips" rel="Tip!::This is tip #3">...and I'm a tip too!</a>

The Javascript:

$$('.tips').addEvent('click', function(e){
	new Message({
		iconPath: '/2010/images/',
		icon: 'mediumQuestion.png',
		passEvent: e,
		callingElement: this
	}).tip();
});

Notice how the tips disappear on mouse rollout. This is achieved by passing the element that called the tip method. Pass this element using the callingElement option in the class’ constructor just like I did above.

Positioning

Just when you thought you’ve seen it all, you get a blast of another cool feature: positioning! That’s right, if you like it on top, you can position the message to align to the top by passing the “top: true” option. If you want it aligned to the left, simply pass the “left: true” option, and voilà… instant positioning! Just the way you like it. See the following:

Do it on the left.

Details

Ok… so the Message class is the bomb! So, what are the details? Here they are:

Constructor:

Message({options});

Options:

callingElement: (element: default to null). You use this option when you need the message to auto hide on the mouse out event. Essential when using the tip method.

callback: (string or element). The function that you want to fire when the user confirms the message by pressing “Yes”. i.e.: “myFunction()”, or just send an element with a click event attached to it.

top: (boolean: defaults to false) Set the message to come out from the top edge of the window. Defaults to the bottom.

left: (boolean: defaults to false) Set the message to the left. Defaults to right.

centered: (boolean: defaults to false) Set the message to the center of the window.

offset: (integer: defaults to 30) Determines the padding to give from the edge of the browser window frame.

width: (mixed: defaults to ‘auto’) The CSS value of your message. Pass a number to change it.

iconPath: (string: defaults to ‘image/icons/’) The path of the icons that you’d like to use.

icon: (string: defaults to null) The file name of your icon image. Note: your icon is expected to be 40 x 40! Can be changed in the CSS.

title: (string: defaults to null) The title of your message.

message: (string: defaults to null) Your message.

delay: (integer: defaults to 0) Delays the display of your message. Integer is interpreted in milliseconds.

autoDismiss: (boolean: defaults to true) The message will dismiss on it’s own. Note: this is shut off automatically when user input is needed.

dismissOnEvent: (boolean: defaults to false) The message will dismiss on the mouseout event. Note: this is used automatically when an event is passed.

isUrgent: (boolean: defaults to false) Use the “urgent” transitioning to get the user’s attention. Note: this is automatically used on the ask and tell methods.

callback: (string: defaults to null) Send a function in the form of a string to be fired on confirmation of an ask method.

passEvent: (event: defaults to null) Passing an event will make the message appear at the your cursor location (offset by 5 px).

tipMode: (boolean: defaults to false) Tip mode is a short-cut that sets the autoDismiss and dismissOnEvent to true.

stack: (boolean: defaults to true) This will stack messages one over (or below) the other message rather than on top of one another (as in a z-index value). **Note that if you over use messages, the stacking goes a little wonky. This is a known issue, and I spent many hours trying to perfect this, but doing so would make this plugin a LOT bigger. Not sure I want to do that. Still experimenting.

fxTransition: (Fx.Transition: defaults to null) Set your own transition. The default transition will simply fade in. * fxDuration: (mixed: defaults to ‘normal’) Set the transition duration. Intergers are interpreted in milliseconds.

fxUrgentTransition: (Fx.Transition object: defaults to Fx.Transitions.Bounce.easeOut) Set your own urgent transition

fxOutTransition: (Fx.Transition object: defaults to null) Set the out transition. The default will simply fade out.

fxOutDuration: (mixed: defaults to ‘normal’) Set the transition duration. Intergers are interpreted in milliseconds.

Methods

Note:

* All options can be passed in the constructor! Some can also be passed in the method.

* When isUrgent is on, a “Yes”, “No” or “Ok” confirmation link is added to dismiss the message.

Say

Syntax:
myMessage. say(title, message, icon, isUrgent, callback);

Options:
- title (string: required) The title of your message.
- message (string: required) Your message.
- icon (string: optional) The image icon that you’d like to use in the message. Note: your icon is expected to be 40 x 40! Can be changed in the CSS.
- isUrgent (boolean: optional) Setting it to true will make the message use the Fx.Transition.Bounce.easeOut effect and in the centered position. This is to get the user’s attention.
- callback (string: optional) Sent a function witten in the form of a string to use as a way to fire another function upon a “Yes” click.

Ask

Syntax:
myMessage.ask(title, message, callback, icon, isUrgent);

Options: they are the same as the say method except that the callback is required (or rather expected) and isUrgent is true by default. “Yes” and “No” links will be added to dismiss the message. A click on the “Yes” link will fire the callback function.

Tell

Syntax:
myMessage.tell(title, message, icon, isUrgent);

Options: they are the same as the say method except that isUrgent is boolean and is true by default. An “OK” link will be added to dismiss the message.

Waiter

Syntax:
myMessage.waiter(title, message, icon, isCentered);

Options: They are the same as the say method except that isCentered is boolean and is true by default.

Tip

Syntax:
myMessage.Tip(title, message, icon);

Options: they are the same as the say method.

Events:

onComplete: Fires when the hide message transition is complete.

onShow: Fires when the message shows. Specifically, it will fire when the show transition is fully complete.

Requirements and Other Notes

This class requires the Mootools Javascript Framework. I’m developed it on 1.2.4, and it’s dependent upon these plugins Element.Position, Element.Measure, Element.Shortcuts and Chain.Wait. (I hope I didn’t forget any… and if I did, please message me at beaudoin.jason@gmail.com!). I tested it on IE 7 +, Firefox, Safari and Google Chrome. I don’t support IE6 because nobody should be using that browser. (Friends don’t let friends use IE6. Remember that!) Also, I use CSS 3 in this example. If you’re viewing this in IE 8 or lower, you’re not going to see the CSS 3 support.

Speaking of CSS, you can find the one I used here. But, it’s also included in the package download file, also found at the top of this page on the right-hand menu.

Posted in Mootools | 49 Comments
  • Google Ads

  • Web Hosting