Dynamic arrays and array techniques with vbscript classic asp

The standard vbscript array is created as so…

Dim degrees(4)
degrees(0) = “Associate in Applied Science Transfer”
degrees(1) = “Associate in Arts, University and College Transfer”
degrees(2) = “Associate in Arts, General Studies”
degrees(3) = “Associate in Science”
degrees(4) = “Associate in Technical Arts”

 

These arrays are not dynamic and need some work to add data to them. You can also create arrays by splitting strings as seen in my post about asp string manipulation techniques.

 

count = 23 ‘ set from database pull

Dim myarray()
ReDim Preserve myarray(count)

For x = 1 to count
myarray(x) =  mydynamicitemhere

Next

 

 

Dump the contents of an array to the screen for debug:

For Each item In myFixedArray
	Response.Write(item & "<br />")
Next

A two dimensional array would be achieved as so…

Dim listofslides()

ReDim preserve listofslides(4,4) ‘ sequence, filename, description, enabled
listofslides(0,0)=1
listofslides(0,1)=”image1.jpg”
listofslides(0,2)=”Description of image 1″
listofslides(0,3)=1

 

 

But if you are getting the array from an information storage system, then its super easy.

sub grabdata
        SQL_query = "SELECT * FROM MSAccess_table"
        Set rsData = conn.Execute(SQL_query)
        If Not rsData.EOF Then aData = rsData.GetRows()         
    end sub

and you use the array like this


If IsArray(aData) Then
    For x = lBound(aData,2) to uBound(aData,2) 'loops through the rows
        Col1 = aData(0,x)
        Col2 = aData(1,x)
        Col3 = aData(2,x)
        Response.Write "Row #" & x+1 & "
" Response.Write "This is the data in Column1: " & Col1 & "
" Response.Write "This is the data in Column2: " & Col2 & "
" Response.Write "This is the data in Column3: " & Col3 & "
" Next End If

Formatting currency fields using javascript

This actually uses jquery, but yo could replace the jquery with doc.getelem….

Here is a sick way to get rid of $ signs, commas and anything after decimal point.

for example: $45,000.45 becomes a clean number 45000 ready for calculations.

No, it doesnt round. just removes the change.

// strip out any $$ .00 and anything else
function stripper(who){
dirtynumber = $( who ).val();
cleannumber = parseInt(dirtynumber.replace(/[^d.]/g, “”));
$( who ).val(cleannumber);
}

Handling Events With J Query

jQuery event.target always refers to the element that triggered the event, where 'event' is the parameter passes to the function. http://docs.jquery.com/Events_(Guide)

$(document).ready(function() {     $("a").click(function(event) {         alert(event.target.id);     }); });
If the  <a> that is clicked were a game element, such as an ace card, the card could tell you "I am an ace of spades" for your code to do what ever.
$( "p" )
.html( newText )
.find( "span" )
.hover(function() {
$( this ).addClass( "hilite" );
}, function() {
$( this ).removeClass( "hilite" );
})
.end()
.find( ":contains('t')" )
.css({
"font-style": "italic",
"font-weight": "bolder"
});

Setting an event handler is not too difficult, but what about removing the event. I don’t want the user to be able to hit the button more than once and still fire the function. the only way that was working was to disable the button or hide it.  I finally found the technique that really works for me. The prop() is a powerful function with untold uses. Dealing with checkboxes seems to be something that would merit its own post. http://api.jquery.com/prop/

Here is a great way to remove a click event that you put inline:

<A href=”#” onclick=”mycoolfunk()” id=”thisbut”>my button or link</a>

$(‘#thisbut’).prop(“onclick”, null);

 

Update: I have been fighting with finding the best way to remove a click event from the button so the user cant hammer on it repeatedly. None of my solutions were working effectively in all situations: like actions on  a submit button are harder to remove than ones on a link.I couldn’t get the submit to submit to my will. I wanted to hide it onclick, not happenin. remove click event, not workin either. What the hell should I do?

Well, enter the .one()  — thats right. http://api.jquery.com/one/ The jquery docs have a function to only put one click event onto an object. This is perfect for a submit where we don’t want the user to be able to repeatedly press the figgin button cause they think everything should be so instantaneous. LOL.

 

But what about handling multiple events.  I have been looking for this for years… We have the  $( document ).on( "click", "#demo-page", function( e ) {alert(e.type)}); alerts(‘click’)

Well here’s how to handle multiple events with one on call:

 $( document ).on( "click press swipeleft swiperight", "#demo-page", function( e ){
alert(e.type); 
if ( e.type === "swipeleft"  ) {// do something only on swipeleft}
});// end doc.on funk

 

I will write up a demo page with this script so I can test it out and do stuff with events.

 

Using delegated events to allow dynamic elements to have the event handler.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

Lets take for example the diploma application I am working on. I have some buttons that have styles and actions that need to be called, but the buttons are not in the dom until and unless the user accesses that particular step of the application. How do I assign the events and styles to non-existing buttons. I had tried a few various solutions before I read about this. Now lets go for this approach. I will delegate the event to the form element. That way, any dynamically added elements will still get the mouseover and mouseout effects.

$(“#diplomappform”).on(“mouseover mouseout”, “[name=’stepUpButton’]”, function(e){
if(e.type==”mouseover”){
$(this).removeClass(“blackouterstrokesmall”).addClass(“boldfont blackouterstrokemedium insetborder whitetextglowtight”);
}
if(e.type==”mouseout”){
$(this).removeClass(“boldfont blackouterstrokemedium insetborder whitetextglowtight”).addClass(“blackouterstrokesmall”);
}
});

 

Sometimes if  you have a mouse over event, the mouse out event will trigger accidently too early. Peter has worked out a fix for this: make a function to call the mouse over function instead of putting an anonymous function directly into the event.
var qlinkTrigger = function() {
$(“#qlink-box”).slideDown(“slow”, function() {
$(this).clearQueue();
});
}

$(“a#qlink-trigger”).hover(qlinkTrigger).click(qlinkTrigger);

$(“#qlink-box”).mouseleave(function() {
$(this).slideUp(“slow”);
});

$(“a.close-qlinkbox”).click(function() {
$(“#qlink-box”).slideUp(“slow”);
return false;
});

ASP and VBSCRIPT string manipulation techniques

To compare two strings that should be identical match:

mystringa=”deedubs”
mystringb=”Dee Dubs”

TestComp = StrComp(mystringa, mystringb)

If TestComp <> 0 Then
Response.Write("The strings don't match")
End If

 

ASP Classic and VBScript tips, tuts links and snips  This seems to be a sick way to code arrays in asp from a string
Here is a vbscript reference pdf.

Are you trying to break a string up into smaller pieces? ASP provides an easy to use split function which lets you dice and slice a string.

Let’s say you take in a sentence and want to put each word into a different variable. So you take in

NameStr = “Mr. John Smith”

Set up the array to hold the results with

Dim WordArray

then do the split, using a space as the split indicator

WordArray = Split(NameStr, ” “)

Now WordArray(0) is equal to “Mr.”, WordArray(1) is equal to “John” and WordArray(2) is equal to “Smith”! You can use various array functions and other string functions to work with these results.

ASP String Functions

 

Best practices  Redirect a user to a location.

While I could response.write a javascript relocation, this is not best practice for security and performance, we would want to execute this code on the server side, so that it can’t be manipulated in any way by a malicious user.

<script>document.location=”myfile.asp”</script> — this is handled on the client machine after they have recieved the page. This could be messed with by a hacker, and I am not even going to give you any reasons why or how.

newUri = “http://www.mysite.com/myspecialpage.html”

 Response.Redirect(newUri) 

The only drawback is that this can’t be used after any content has been written to the page. Here is a great article from microsoft about the variables and how to use them.

 

Check if a string has letters in it.

A basic validation to see if a string doesnt have letters in it:

Set re =New RegExp
re.Pattern ="[a-z]"
re.IgnoreCase =True
re.Global =True
hasMatches = re.Test("12345abc")
If hasMatches =True
'it has letters in it.
End If

 

basic Javascript email validation

This function will check for very basic user mistakes such as @ sign and .com and stuff.

// function to validate email address
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
// end email address validator

Use it like this in your code where ever you need it….

if (validateEmail(student_class_instructor_email) == false) {alert(“Error, please check the instructor email address for proper syntax.”); return false;}

 

a really bad ass way to display the error alert , especially in foundation, is to change the alert() to a prepend of the form or even the element that had the error…

alert(“Error…)
$(‘#foundationform’).prepend(“Error, please check the  email address for proper syntax.”);

if you have foundation you can use the error box built in with a close button .. just wrap it around the error message

<div class=’alert-box alert’>Error, please check the  email address for proper syntax.<a href=” class=’close’>&times;</a></div>

Loop through form elements with Javascript using modern form validation techniques.

Here are some techniques that I use to loop through a form , access the elements and validate the field.

Here is one that will look for any field with an id, and require it. Then it will display the error message using the label of the field. sick!

function checkForm() {
        // begin basic form validation
        // check for empty fields name. adress etc.
        var str = '';
        var elem = document.getElementById('golf_reg_form').elements;
        for(var i = 0; i < elem.length; i++)
        {
           if(elem[i].value=="" && elem[i].id!==""){
            var myelem = elem[i];
            dalabel = $( elem[i] ).prev().html();
            alert("Please fill in  " + dalabel);
            //$( elem[i] ).val("error");-- note "A"
            return false;
            } 

        } 

    } // end form validation funk

note “A”: — here is where you could set some responsive disclosure ui features to help user know where the error is.

<script type="text/javascript">
    function DisplayFormValues()
    {
        var str = '';
        var elem = document.getElementById('frmMain').elements;
        for(var i = 0; i < elem.length; i++)
        {
            str += "<b>Type:</b>" + elem[i].type + "&nbsp&nbsp";
            str += "<b>Name:</b>" + elem[i].name + "&nbsp;&nbsp;";
            str += "<b>Value:</b><i>" + elem[i].value + "</i>&nbsp;&nbsp;";
            str += "<BR>";
        } 
        document.getElementById('lblValues').innerHTML = str;
    }
</script>

Update: I have figured out how to access this elem[i] using jquery.

$( elem[i] ).val(“error”);

Here is how to remove the error display when the user begins to correct it.
// this is to remove an error message after the user corrects it.
function typeIn(i, a)  {

if (document.sports_recruitment_form.elements[i].className==”error”) {

document.sports_recruitment_form.elements[i].className = ” “;

}

Then I can use selectors and apply the event handler to required fields: onclick=”typeIn(this.name, this.value)”

I could use jquery to loop through the form if I wanted to have more precision selectors like choosing only checkboxes, or even only checked checkboxes.

 

Here is a great example of how to select inputs from a large form, all elements have been named in groups, and setting each one with a unique id would be a waste of time.Instead, just give the container a unique id, and then access the child elements using jquery’s powerful selectors.

<div class=”six columns disclose” id=”golfer1″>

<label>First</label><input name=”team” type=”text” size=”24″/>

<label>Last</label><input name=”team” type=”text” size=”24″  />

<label>Email</label><input name=”team” type=”text” size=”40″ />

<label>Phone</label><input name=”team” type=”text” size=”16″ />

</div>

for(var allfields=0; allfields<=$(“#golfer1 :input”).length-1;allfields++){
alert($(“#golfer2 input:eq(“+allfields+”)”).val());
}

 

This code will loop through and detect the value of any input elements within the parent container. From there we could create some validation or whatever we want to do with the data.

UPDATE: after years of practice, I have concluded that the name and id should be set as so: <label>Phone</label><input name=”Phone Number” type=”text” id=”phone” size=”16″ /> then the labels and/or placeholders could be created dynamically from the name.

// set the placeholder of every text input to equal its name attribute
$(“form :input[type=’text’]”).each(function(){
$( this ).attr(“placeholder”, $( this).attr(“name”));
});

Application Development Documentation

These  documents are necessary to properly plan and document a website, application or production project, and they are critical to successful development, launch and maintenance/updates.  Here are some examples of my work creating documentation, and my notes on what should be included in these documents.

 

 

Creative Brief

The Creative Brief is also called a site plan, depending on the project. This is the first document to be created, usually from the initial information obtained from the client or project director.

Your Creative Brief should include:

  • The Site Purpose
    What is the point of this website? And how is it going to fulfill that purpose better than any other site on the Web?
  • The Site Goals
    SMART goals can help you take a mediocre site and make it great. Once you know the goals of the site, you can plan around them.
  • The Customers
    Who is going to read this website? Try to be as specific as you can regarding your target audience. Include details like: age, hobbies, income, job title(s), and so on. You might envision different people coming to different parts of your site – that’s fine. But know who the audience is that you want to attract. And if your site is already live, you should include data on the audience that you currently have.
  • The Content
    What will be on the site? Will the content change regularly? Will you focus on selling products with product pages or focus on providing information through articles? Is your content going to be mostly text or images or multimedia? Do you have the content already created or do you still need to get it?
  • The Design
    What colors will your site be? Remember that design aesthetic varies across different demographics. So if you’re planning a website for cutting edge designers, it will have a different look than one designed for stay-at-home dads (except maybe those stay-at-home dads that are also cutting edge designers…). The design includes things like graphic elements, colors, fonts, and typography. The more you plan ahead of time, the easier the design phase will be.
  • The Timeline
    Once you have the rest of the pieces of the plan together, you should decide on a schedule. Don’t forget to include time for testing, revision, and user feedback.

Flowcharts

So far I have found that this is a good way to visualize the MVC design flow.

Use case diagram

Here is how to write an effective use case and user story.

 

What is UML use case diagram

 

 

Site Map

I’m not sure if this is the same as what I need. This Sitemap is a google search meta code for html pages.

Here is a little info about the site map, it really is just a simple diagram showing the pages and how they link together.

 

WireFrame

Sequence Diagrams

Component Diagrams

Deployment Diagram

Database Diagrams

Using custom attributes in jquery

You can use your own custom atributes to attach more information to a tag.

make a note to look into using your own tags in jquery.check out lukes hall of fame code for inspiration.

Heres a great example. I needed to mark tasks as completed or not, and using a custom attribute works well. I add the attribute “taskstatus” to be “new”, open, or “completed” based on results from a call to the database. Then I can select any task that has the attribute as so….

thetasks=$(‘#maintasklist  div[taskstatus=completed]’);

This looks for divs with my custom taskstatus set to completed, inside a container with id of maintasklist.

Managing Persistent Data In Your Web Applications Using DOM Storage

The 90’s saw many inovations in the web, but not much changed in the way of client side storage. Javascript and cookies were the way to keep user data saved in the browser.

Recently various techniques for storing and retrieving data have emerged. There are so many different ways in fact that we need to answer some questions to determine the best solution for persisting data between requests.

We have to ask who needs the data ? How long does the data need to be persisted?  And how large is the set of data?

Persistence Method Who Needs the Data? For How Long? How Much Data?
Application All users Until the next application restart Can be almost any size—it will only be stored once
Cookie One user As short as desired, or for months or even years if the user doesn’t delete their cookies Minimal, simple data
Form Post One user For the next request (can be reused across many requests) Virtually any size—the data is sent back and forth with every page
QueryString One user or one group of users For the next request (can be reused across many requests) Minimal, simple data
Session One user As long as the user is active, plus a timeout period (typically 20 minutes) Can be almost any size, but should be minimized since every user has their own separate session store
Cache All users or a subset of users As long or as short as needed Can be used for large or small, simple or complex data
Context One user This request only Can hold large objects, but typically does not since it is often used for every request
ViewState One user One Web form Minimal; as with Form Post, this data is sent back and forth with every page
Config file All users Until the configuration file is updated Can hold a lot of data; usually organized as many small strings or XML structures

Application

Let’s set the object use criteria by answering the state questions I asked earlier. Who needs this data? All users need access to it. How long does this data need to be persisted? It has to live forever, or for the life of the application. How large is this data? It can be almost any size—only one copy of the data will exist at any given time.
In classic ASP, the Application object provided a great place to store frequently used pieces of data that changed infrequently, such as the contents of menus or other reference data. While the Application object is still available as a data container in ASP.NET, other objects are generally better suited for the kinds of data that would have been stored in the Application collection of a classic ASP application.
Cookies

Cookies are handy when a particular user needs a specific piece of data, and it needs to be persisted for a variable period of time. It can be as brief as the life of the browser window, or as long as months or even years. As far as size goes, cookies are very small. Cookies can be as small as only a few bytes of data, and since they are passed with every browser request, their contents should be kept as small as possible.
Security NOTE : The best way to secure sensitive state that should not be viewed or modified by a hostile user is to store that state on the server. If sensitive data must be sent to the client, it should be encrypted beforehand, regardless of the storage mechanism employed.
Form Post / Hidden Form Field

Form data is needed by a particular user, and it must be persisted for any period from a single request to the life of the application. The data can be virtually any size; it’s sent back and forth over the network with each form post. This requires the data to be sent back and for to each other using Submit buttons, or saved on the client machine with cookies.  This was a classic technique that is not recommended anymore.
QueryString

The data stored in the QueryString object is used by the individual user. Its lifetime can be as brief as a single request, or as long as the user continues to use the application (if architected appropriately). This data is typically less than 1KB. Data in a QueryString is passed in the URL and is visible to the user, so as you might guess, sensitive data or data that can be used to control the application should be encrypted when using this technique.
That said, the QueryString is a great way to send information between Web forms in ASP.NET. For example, if you have a DataGrid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the QueryString to include the product ID in the QueryString of the link to the product details page (for example, productdetails.aspx?id=4). Another advantage of using QueryStrings is that the state of the page is contained in the URL. This means that a user can put a page in their Favorites folder in its generated form when it’s created with a QueryString. When they return to it as a favorite, it will be the same as when they actually made it a favorite. Obviously, this only works if the page doesn’t rely on any state outside the QueryString and nothing else changes.
Along with sensitive data, any variable that you don’t want the user to be able to manipulate should be avoided here (unless encryption is used to remove human-readability). Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode, as Figure 7 shows. When dealing with a single ASP.NET page, ViewState is a better choice than QueryString for maintaining state. For long-term data storage, Cookie, Session, or Cache are more appropriate data containers than QueryStrings.

Session

Session data is specific to a particular user. It lives for as long as the user continues to makes requests plus some period of time afterward (typically 20 minutes). The Session object can hold large or small amounts of data, but total storage should be kept minimal if the application is intended to scale to hundreds of users or more.
Using the Session object is easy and its syntax is identical to classic ASP. However, the Session object is one of the less efficient ways of storing user data, since it is held in memory for some time even after the user has stopped using the application. This can have serious effects on scalability for a very busy site.
For small amounts of data, the Session object can be a perfectly valid place to store user-specific data that needs to persist only for the duration of the user’s current session.
This sounds like the way to go for my progress reporting application. So, lets dive into a demo and see how we can save some data in session object.

Here is some sample session variable code: Methods

Create session variable and set it:

Session(“varName”) = varValue

 

Get on page:

newVar = Sesssion(“varName”)

 

Clear session variable:

Session(“varName”) = “” OR

Session.Contents.Remove(“varName”)

Clear out session when done:

Session.Contents.RemoveAll()    OR

Session.Abandon

I would combine the two to ensure that pesky session data is gone.My logout script is :

Session.Contents.RemoveAll()
Session.Abandon
Response.Redirect(“default.asp”)

The session object has the onStart and OnEnd events and the SessionID and Timeout properties

 

A session ends if a user has not requested or refreshed a page in the application for a specified period. By default, this is 20 minutes. They could need longer for filling out these forms.

If you want to set a timeout interval that is shorter or longer than the default, use the Timeoutproperty.

Session.Timeout=5 gives the session 5 minutes of inactivity. I think you would want a few hours at least.

 

 

Here is the best resources for asp dev http://www.w3schools.com/asp/asp_sessions.asp

http://www.tizag.com/aspTutorial/aspSession.php

This is a summary of a microsoft developer network article. that was updated in 2005.

 

 

Now lets get into the new technology

Here is my personal test file http://itwebdev.mv.skagit.edu/don/stuff/dom%20storage/domstorage.html

DOM storage, also called Web Storage is comprable to cookies. However, web storage offers more control of  how the information is stored and accesed by each window.

This technique also offers a lot more storage space, and quite different functionality than cookies.

 

The web storage scripting objects have been drafted into the HTML 5 working draft specifications, and have gathered major vendor support.

window.sessionStorage
Session storage is designed for scenarios where the user is carrying out a single transaction. The sessionStorage attribute of the window object maintains key/value pairs for all pages loaded during the lifetime of a single tab (for the duration of the top-level browsing context). For example, a page might have a check box that the user selects to indicate that he wants insurance. A later page could then check, from script, whether the user had selected the check box.

The Storage object supports expando properties (‘insurance’ in the preceding example). If the property name does not exist, a key/value pair is automatically created to hold it. Note that key/value pairs are always stored as strings. Different data types such as numbers, Boolean values, and structured data must be converted to strings before persisting to a storage area.

After a value has been saved to sessionStorage, it can be retrieved by script running in another page in the same context. When another document is loaded,sessionStorage is initialized from memory for same-origin URLs

Note  Although it is allowed by the HTML5 (Working Draft), Internet Explorer 8 does not resume sessionStorage after browser crash recovery.

 

window.localStorage

The local storage mechanism spans multiple windows and persists beyond the current session. The localStorage attribute provides persistent storage areas for domains. It allows Web applications to store nearly 10 MB of user data, such as entire documents or a user’s mailbox, on the client for performance reasons.

here is the msdn article that this blog post sumarrizes http://msdn.microsoft.com/en-us/library/cc197062(v=vs.85).aspx