DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/)
-   ASP Tutorials (http://www.daniweb.com/forums/forum35.html)
-   -   Understanding ASP classes (http://www.daniweb.com/forums/thread19997.html)

hollystyles Mar 11th, 2005 12:06 pm
Understanding ASP classes
 
The aim of this tutorial is to save burgeoning self taught developers some of the early pitfalls that lurk on the road to programming enlightenment. It will attempt to do this by distilling the last 50 years of software engineering philosophy into a relatively short single tutorial, applying the concepts along the way in the medium that is in most need of its principals: web development.

Several assumptions have been made about your level of knowledge, such as having an understanding of the Visual Basic Scripting syntax for Active Server Pages (ASP) and the ability to create and ADO connection and recordset objects for example. If you don’t have a clue what is meant by looping through your recordset to make an HTML Table or List Control then, to be honest, you are probably not quite ready for this tutorial.

If you are still reading then you are probably wondering why ASP when it has been superseded by ASP.NET? The truth is that ASP is far from dead and anyway, the stuff covered here will make the move to ASP.NET from ASP that much easier anyway, if and when you should find yourself in that position.

Building a web application from the snippets garnered from a ‘learn ASP in 24 hours’ tutorial is all well and good, and can be done. But be warned that further down the road you may face headaches maintaining that system. So let’s look at how you should be thinking of applying the syntax you have already learnt in order to avoid those headaches.

Let us start by introducing Object Oriented Programming (OOP), the natural step onward from structured programming. Computing hardware was become cheaper and more powerful, the problems that needed to be solved and therefore the software requirements were becoming ever more complex. What was needed was a better way to model the real world problems that were to be solved with our software. In order to do it quicker; to make the software easily maintainable; to make it more future proof required new languages and syntax to enable the programmer to group his or her variables, subroutines and functions into abstract items called classes. Classes are a blue print for an object, you use that blueprint to create an instance of your class, an object, in your program and then you can set its variables and call its methods. This can be demonstrated by way of using the most famous example in programming: the hello world program.

Create a new asp file, call it Greeting.asp, if you’re using an IDE like Interdev, get rid of any code or HTML the template bungs into your new page e.g. the <%@ Language = VBScript %> and any HTML tags. Put the following code in exactly as shown:

  1. <%
  2. Public Class Greeting
  3.  
  4.         ‘Private member variable accessible only
  5.         ‘to the class
  6.         Private m_sGreeting       
  7.  
  8.         ‘Accessor method, controlled aliased
  9.         ‘READ access to your class variable
  10.         Public Property Get Message()       
  11.                 Message = m_sGreeting
  12.         End Property
  13.  
  14.         ‘Accessor method, controlled aliased
  15.         ‘WRITE access to your class variable
  16.         Public Property Set Message(sMsg)       
  17.                 m_sGreeting = sMsg
  18.         End Property
  19.  
  20.         ‘The constructor, initialization for
  21.         ‘your object
  22.         Private Sub Class_Initialize()               
  23.                 m_sGreeting = “Hello world!�?
  24.         End Sub
  25.  
  26.         ‘Public class method, something this
  27.         ‘class can do for you.
  28.         Public Sub Greet()                       
  29.                 Response.Write m_sGreeting
  30.         End Sub
  31.  
  32.         ‘Cleaning up.
  33.         ‘Unhand that RAM you hog !
  34.         ‘There’s nothing to clean up in this
  35.         ‘small class, so this is here for
  36.         ‘demonstration only
  37. Private Sub Class_Terminate()       
  38.  
  39. End Sub
  40.  
  41. End Class
  42. %>

Now you should create another ASP page, call it index.asp and place the following code within it:

  1. <%@ Language=VBScript %>
  2. <%Option Explicit
  3. ‘This next bit is an SSI (server Side Include) It means put here
  4. ‘the contents of  Greeting.asp as if it were part of the code
  5. in this page.%>
  6. <!-- #include file="Greeting.asp" -->
  7. <%
  8.         Dim oGreeting
  9.  
  10.         'Instantiate an object of type Greeting
  11.         Set oGreeting = New Greeting
  12. %>
  13. <HTML>
  14. <HEAD>
  15. <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
  16. </HEAD>
  17. <BODY>
  18.  
  19. <P>
  20.         <%
  21.                 'Call the Greet method
  22.                 oGreeting.Greet
  23.  
  24.                 'Destroy our object
  25.                 Set oGreeting = nothing
  26.         %>
  27. </P>
  28.  
  29. </BODY>
  30. </HTML>

Now this may seem an excessive amount of code just to display the string “HelloWorld!" and you would be right, but ignore that for a minute and look at what you have actually achieved. Firstly you have hidden the nitty gritty of making a dynamic greeting on your ASP page using the response object, and replaced it with something much more intuitive. You needed a greeting, so you created an instance of a greeting and asked it to greet by calling the greet method. This is called encapsulation or data hiding, should a new and better way of writing strings be released for ASP you could change the greet method in your class without effecting any of the code in your index.asp page, which will still work just as before.

Secondly, that extra effort spent now has saved you effort in the future because you have separated out the responsibility of providing a greeting on an ASP page: it has become a black box. You don’t need to know how it works, you just need to know how to use it. It is also in a separate file, next time you need a greeting in another project, there it is ready and waiting. This is known as code reuse.

Thirdly you have avoided duplication. Imagine a project where you had to have a greeting on several pages within it, deadlines were tight so you used single line Response.Write statements throughout and went home early for tea. Suddenly the following morning you need any greeting to now include the users name. If you have been developing for any amount of time you will know there are three certainties in life, not two. Death, Taxes, and changes to the requirements. As you had used single line Response.Write statements everywhere, you now have to hunt them down and recode them. With the greeting class implementation you merely open Greeting.asp and amend the Greet method accordingly in one place. Any pages making use of the class will display the new behavior with no change to their code what-so-ever. Imagine applying these principals to those repetitive tasks such as connecting to your database, filling a recordset, concatenating the HTML string and so on. Using classes you can: do it once and do it well.

Now it is time to go into the class syntax in more detail, explaining member variables and accessor methods and how it all works as well as attempting to create a more useful class that makes an HTML list box control. If you were lucky enough to study computing at a good college you will have learnt about things like Orthogonal systems, the DRY principal (Don’t Repeat Yourself), encapsulation, code reuse, and possibly even newer terms such as Unit testing and Iterative development. If however, you came into programming from nothing and have taught yourself pretty much everything by reading getting started type books then they will be new terms for you, or terms you have heard but don’t understand. But these terms are very important and you are going to learn them one at a time and then repeat each time you find yourself facing a new challenge requiring a solution.

The first concept you are going to tackle is best described as 'damn the details.' If you are lucky as a developer you find yourself facing lots of problems that require your software solutions. How you go about designing and creating that software is much more important than the actual code you will end up implementing. If your early encounters with programming were VBScript and ASP, your immediate response when faced with a problem that needs a software solution may be to start writing down some pseudocode .

Your thought process might go along the lines of something like: “Hmmm, I’ll need to store customer details, so I’ll need a form with some text boxes…" But it’s actually far too early to be thinking at that low level in your solution, leave the details out for as long as possible. The trick is to force yourself to stay high level, to look down from a birds eye view. You should be aiming to glide into your deadline from on high, not nose dive to ground level and get lost in the terrain. By start high you should be thinking of something like:

INPUT ? PROCESS ? OUTPUT

High enough? Well it does no harm to make this a mantra, making things habit embeds them in your mind and also sets it in the right frame. Every sprinter knows 99% of the race is how you exit the starting blocks. Before you get to the code for a listbox control making class, you should look back at the class we created earlier and examine its parts to understand what it really means. Only then can you apply that knowledge and make a new one. Firstly a class in VBScript is declared simply with the keyword Class; then a valid identifier to name it; some valid syntax; and finally the keyword End Class.

  1. Class MyClass
  2.         ‘Properties and methods here
  3. End Class

Implementing classes varies widely amongst languages, but the concept of classes is universal. There are many analogies for describing classes. Most often a book or article will talk about real world objects like a car or bike, and go on to describe the difference between the idea of a bike and the physical bike itself, but this does not quite capture fully what they are, or how they can empower you as a developer. Think of them instead as super variables with ‘supervariable’ powers. They not only store data like variables can, but they store LOTS of data; they have responsibility; and they have knowledge; finally they have an interface.

The essential components of a class are as follows:
  • Private and or public member variables (your current state)
    A Constructor (we are all born)
    Accessor methods (your eyes and ears)
    Private and or Public functions or subroutines (your ability and knowledge)
    A Destructor (we all die one day)

Our Greeting class had all of these. Next there is a single member variable:

  1.         ‘Private member variable accessible only
  2.         ‘to the class
  3.         Private m_sGreeting

This variables’ scope is the bounds of the class, you can not affect it from any code outside of the class. If you had declared it as Public:

  1.         ‘Private member variable accessible only
  2.         ‘to the class
  3.         Public m_sGreeting

you could access it from code outside the class like this:

  1. Dim oGreeting
  2. Set oGreeting = New Greeting
  3.  
  4. oGreeting.m_sGreeting = “Hi!�?

But this is seldom advisable as class variables should ideally be accessed via an accessor method or methods, depending whether you want the value to be read only, or updateable.

  1.         ‘Accessor method, controlled aliased
  2.         ‘READ access to your class variable
  3.         Public Property Get Message()       
  4.                 Message = m_sGreeting
  5.         End Property
  6.  
  7.         ‘Accessor method, controlled aliased
  8.         ‘WRITE access to your class variable
  9.         Public Property Set Message(sMsg)       
  10.                 m_sGreeting = sMsg
  11.         End Property
  12.  

You use the same dot notation to use these methods:

  1. Dim oGreeting
  2. Set oGreeting = New Greeting
  3.  
  4. Set the message value
  5. oGreeting.Message = “Hi!�?
  6.  
  7. ‘Read the message value
  8. Response.Write oGreeting.Message

The important issue here is that because they are methods you get additional opportunity. You can validate the value trying to be set, and should you need to change the implementation of your class the interface stays the same. So any ‘User’ of your class doesn’t need to know about it. They call the same method and pass the same data, what the class does with it once received is up to the class. The constructor is where we initialize things, if necessary. If you omit the constructor a blank one is inserted by the compiler automatically. In VBScript this is a special subroutine Class_Initialize() (careful of the spelling of initialize with a z if you spell it with an s you wont get a syntax error, just a hard to locate bug!) In your Greeting example you set the class variable m_sGreeting to the string value “Hello World!" so that if the user of your class does not set a message with the Message accessor method, you have a default value already set.

  1.         ‘The constructor, initialization for
  2.         ‘your object
  3.         Private Sub Class_Initialize()               
  4.                 m_sGreeting = “Hello world!�?
  5.         End Sub

Next comes the meat of the class, it doesn’t look so much in your example, but in the real world these are likely to be the most sophisticated elements of your classes:

  1.         ‘Public class method, something this
  2.         ‘class can do for you.
  3.         Public Sub Greet()                       
  4.                 Response.Write m_sGreeting
  5.         End Sub

In this case you have a subroutine, but it could be a function. The difference being a function returns a value, where as a subroutine just does some work. Actually a subroutine is a function that returns void or nothing. Finally all good things come to an end at some point; this is the responsibility of the destructor. In VBScript (like the constructor) a special subroutine Class_Terminate() is called, when you set your object to nothing explicitly, or when VB’s garbage collector kills it off. So this is where you put any code needed to tidy up.

So that’s classes, for now at least. It is time now to put what you have learnt so far to good use. Create a new asp file ‘Controls.asp’ and place the following code into it, remembering again to remove anything the template puts in for you if you are using an IDE such as Interdev.

  1. <%
  2.  
  3. Class Combo
  4.  
  5.         'Member Variables
  6.         Private m_bIsData
  7.         Private m_aOptionElements
  8.         Private m_sName
  9.         Private m_iRowIndex
  10.         Private m_iRowCount
  11.         Private m_sSelectItem
  12.  
  13.         'Accessor methods       
  14.         Private Sub Class_Initialize()
  15.                 m_bIsData = False
  16.                 m_sName = "combo1"
  17.                 m_sSelectItem = ""
  18.         End Sub
  19.  
  20.         Public Property Let Name(sName)
  21.                 m_sName = sName
  22.         End Property
  23.  
  24.         Public Property Let SelectItem(sItem)
  25.                 m_sSelectItem = sItem
  26.         End Property
  27.  
  28.         Public Property Get SelectItem()
  29.                 SelectItem = m_sSelectItem
  30.         End Property
  31.  
  32.         'Public methods
  33.         Public Sub FillCombo(ByRef rs)
  34.                 'Takes reference to  recordset
  35.                 'and puts data into a 2 dimensional
  36.                 'array
  37.                 If rs.EOF and rs.BOF Then
  38.                         m_bIsData = False
  39.                 Else
  40.                         m_bIsData = True
  41.                         m_aOptionElements = rs.GetRows
  42.                         m_iRowCount = Ubound(m_aOptionElements,2)
  43.                 End If
  44.         End Sub
  45.  
  46.         Public Sub WriteCombo()
  47.         'loops through an array to
  48.         'create dynamic HTML
  49.                 Response.Write "<select name='" & m_sName & "'>" & vbCrLf
  50.                 If m_bIsData Then
  51.                         For m_iRowIndex = 0 to m_iRowCount
  52.                                 Response.Write "<option "
  53.                                 If m_aOptionElements(0,m_iRowIndex) = m_sSelectItem Then Response.Write "selected "
  54.                                 Response.Write "value=""" & m_aOptionElements(0,m_iRowIndex)""">" & m_aOptionElements(1,m_iRowIndex) & "</option>" & vbCrLf
  55.                         Next
  56.                 Else
  57.                         Response.Write "<option value=''></option>" & vbCrLf
  58.                 End If
  59.                 Response.Write "</select>" & vbCrLf
  60.         End Sub
  61. End Class
  62.  
  63. %>

Now to implement your class, put the following code in another file called UserForm1.asp. This example assumes you have SQL Server developer edition installed. You can download it from Microsoft http://msdn2.microsoft.com/en-us/sql/default.aspx if you don’t have it.

  1. <%@ Language=VBScript %>
  2. <%Option Explicit%>
  3. <!-- #include file="Controls.asp" -->
  4. <%
  5. 'Declare our variables
  6. Dim oCon, oRst, oCombo1
  7. Dim sCon, sSQL
  8.  
  9. 'Initialise our variables and objects
  10. sCon = "Provider=SQLOLEDB;Integrated Security=SSPI;Data Source=localhost;Initial Catalog=Pubs"
  11. sSQL = "Select au_id, au_fname+' '+au_lname from authors"
  12.  
  13. Set oCon = Server.CreateObject("ADODB.Connection")
  14. Set oRst = Server.CreateObject("ADODB.Recordset")
  15. Set oCombo1 = New Combo
  16.  
  17. 'Set some properties
  18. oRst.CursorLocation = adUseClient
  19.  
  20. 'Connect to database and fill the recordset
  21. oCon.Open sCon
  22. oRst.Open sSQL, oCon
  23. Set oRst.ActiveConnection = Nothing
  24. oCon.Close
  25. Set oCon = Nothing
  26.  
  27. 'Pass the data to our combo class
  28. oCombo1.FillCombo oRst
  29.  
  30. 'Ditch the recordset no longer required
  31. Set oRst = Nothing
  32. %>
  33. <HTML>
  34. <HEAD>
  35. <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
  36. </HEAD>
  37. <BODY>
  38.  
  39. <%
  40. 'Display our Combo as HTML Listbox control
  41. oCombo1.WriteCombo
  42. Set oCombo1 = Nothing
  43. %>
  44.  
  45. </BODY>
  46. </HTML>

If you have typed the code correctly, and have SQL server set up correctly (you may have to add the local account IUSR_<machine_name> to SQL Server logins) you should get a Listbox of author names when you browse UserForm1.asp. So next time you need a Listbox in a form, you won’t have to write all that loop code ever again.

  1. <%
  2. While Not Rst.EOF
  3.         Response.Write “<select blah …..
  4. Wend
  5. %>

You’ve done it once, and you’ve done it well in your Controls.asp page, so that you can now use in any project with an SSI <!-- #include file=“Controls.asp" -->


All times are GMT -4. The time now is 5:48 am.

Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC