Create customized web output using VB web classes

Submitted on: 1/6/2015 4:33:00 AM
By: Ian Ippolito (PSC)  
Level: Intermediate
User Rating: By 8 Users
Compatibility: VB 5.0, VB 6.0
Views: 2435
author picture
     You CAN create web apps without losing the sophistication of such Visual Basic niceties as sophisticated error handling, API calls, class modules, etc...using Visual Basic Web Classes! This article shows you how.

This article has accompanying files

				From Active
Server Developer Magazine, March 2000
Reposted with Permission of ZD Net Journals

As you probably know, Visual Basic contains many useful features that VBScript lacks, like sophisticated error trapping, class modules, API calls, and user-defined types. If you've come to ASP programming from Visual Basic, then you probably found yourself yearning for something as simple as runtime debugging. Sure, Microsoft InterDev provides debugging, but let's face it, it can't hold a candle to Visual Basic's IDE. If you're like us, you probably wished for a way to have your cake and eat it too--that is, to program ASP pages with the full power of Visual Basic directly from Visual Basic's IDE. In that case, you'll be happy to know that Visual Basic 6.0 gives you the ability to do just that. The WebClass object and Designer lets you create COM DLL's that act exactly like regular ASP pages.

In this article, we'll take you step by step through the process of building a WebClass. When we've finished, we'll have a simple Web portal that will let you register a name and password with the site, and then display a customized home page based on the initial information.

What's in a WebClass?

As we mentioned, a WebClass is a COM DLL that serves as a type of proxy on your Web server, serving out the appropriate HTML content to client requests. Each WebClass consists of WebItems (HTML pages), which in turn consist of elements. These elements represent the items capable of receiving events. To get a better grasp of exactly what you can do with a WebClass, let's dive right in and create the example.

Create the Portal project

To begin, launch Visual Basic and create a new IIS Application. (Note: you'll need Internet Information Server (IIS) and one of the following operating systems: Windows NT, Windows NT Workstation, Windows 2000, Windows 2000 Server or Windows 2000 Advanced Server). Then, in the Project Explorer right-click on the default Project1 item and choose Project1 Properties from the shortcut menu. In the Project Name text box, enter Portal as the project's name and click OK.

Get to know the WebClass Designer

At this point, we want to open the WebClass Designer and import the HTML page templates that make up the site. To launch the designer, in the Project Explorer window expand the Designers folder. When you do, Visual Basic displays the project's default WebClass object. Double-click on it to open the WebClass Designer, as shown in Figure A. As you create your WebClass, you'll use this window extensively throughout this article.

Figure A: Visual Basic 6.0's WebClass designer displays the WebItems contained in the current project.
[ Figure A ]

Next, in the Properties window, name the WebClass wbcPortal, and then change the Name In URL property to Portal. This property determines the name used by VB as the WebClass's URL page, and will display to the end user through the address bar in his browser. As a result, it's important to keep the URL name meaningful. Now, save the project in its own folder.

Import the HTML pages

Next, let's import the site's base Web pages. Microsoft designed WebClasses with the assumption that programmers would work with Web pages only after a graphic designer initially created them. As a result, VB doesn't contain an HTML authoring tool to assist you with Web page creation. However, if you click the Edit The HTML button, Visual Basic opens the page in Notepad. To save time, you can use the three Web pages included in this month's download: NewUser.htm, Portal.htm, and Welcome.htm. To import these files, first copy them into the current project's directory. Then, in the Designer right-click on the HTML Template WebItems folder located beneath wbcPortal. Choose Add HTML Template from the shortcut menu, and then select the files one at a time. After VB imports each file, it lets you rename them. Use the names tplNewUser, tplPortal, and tplWelcome respectively. At this point, the designer window should look similar to Figure B.

Figure B: To add HTML template pages to the project, you import them into the WebClass Designer.
[ Figure B ]

Indicate the start-up page

As our last setup task, we need to tell the WebClass which WebItem is our start-up page. To do so, double-click on wbcPortal in the Designer. When you do, Visual Basic displays the WebClass' Start() event. This event is equivalent to a form's Load() event, and fires whenever you first visit the Web site. You'll notice that VB has already inserted some default code. Microsoft probably thought this was a great feature, because it allows WebClass newbies to get their bearings. However, 99.99 percent of the time you'll want to get rid of it. Replace the existing code with
'show default class
Now, let's see what the Web site looks like. Click the Visual Basic Run button. When Windows displays the Debugging dialog box, make sure the Start Component is selected and click OK. If Visual Basic asks if you want to create a virtual root on the Web server in which to run the WebClass, choose Yes. After a few seconds, your Internet browser should greet you with the screen shown in Figure C. You'll notice that while the page displays just fine, the Submit button doesn't actually do anything--it just takes you to an empty page. Let's fix that problem, next.

Figure C: The Portal WebClass serves the necessary HTML for this welcome page.
[ Figure C ]

Create forms that work

In a nutshell, we want our Web application to react two different ways in response to the user data. For new members, we want to send them to a welcome page that gathers additional registration information. On the other hand, the Web application can simply pass existing members directly to the portal page. To add this functionality, we need to connect events to the Web pages' various elements. To begin, let's add the code that sends the user's information to a database, and then redirects them to the appropriate Web page. To do so, stop the program and return to the WebClass Designer. Next, click on the tplWelcome item. Visual Basic fills the right pane with a list of the page's elements. Double-click on the Form1 element to open the code window for this item. In the actual Web page, IIS executes the code in this event whenever you click Form1's Submit button.

Next, set a Reference to the Microsoft Active X Data Objects 2.1 Library. We'll use this DLL to perform the data access tasks. Now, insert the code in Listing A, which queries the database for the user's name and password. Notice that if the code doesn't find the member's name, it uses the WebClass' .WriteTemplate method to send him to the welcome page. If it does find the member's name, then it redirects him to the portal page.

Listing A: The welcome form's event code

Private mconConnection As ADODB.Connection
Private mrsUser As ADODB.Recordset
Private Sub tplWelcome_Form1()
Set mconConnection = New ADODB.Connection
Set mrsUser = New ADODB.Recordset
mconConnection.Open "Provider=Microsoft.Jet.OLEDB" _
	& ".3.51;Data Source=" & App.Path _
	& "\portalMems.mdb"
mrsUser.Open "SELECT * from tblUsers where " _
	& "txtName='" & Request("txtName") & "' " _
	& "AND txtPass='" & Request("txtPassword") _
	& "'", mconConnection, , , adCmdText
If mrsUser.EOF Then
	'user not registered--show new user screen
	'user registered--show portal screen
End If
Set mconConnection = Nothing
Set mrsUser = Nothing
End Sub
As you can see, Visual Basic WebClasses have access to the same object model as Active Server Pages. The code uses the Request.Form object to retrieve the user name and password from tplWelcome.

Let's see what happens when we run the program now. Click Visual Basic's Run button, enter a user name and password in the Web page, and then click the Submit button. When you do, the program recognizes a new user and takes you to the new user page, as seen in Figure D.

Figure D: Our WebClass checks a database of current members for the data entered in the welcome page, and then transfers you to the appropriate Web page.
[ Figure D ]

Insert the data of your choice into WebClass tags

Notice that the Name field on the new user screen defaulted to a generic name entry (the password field did the same, but you can't tell because...well, it's a password field). It would be nice if the page remembered the info we just entered on the previous page, and showed it instead. To solve this problem, we'll gather the data exactly like we did in the tplWelcome's Form() event. This time, however, we also need to actually display it to the user. You may wonder how to customize what Visual Basic displays in the HTML template. In a regular ASP page, you'd simply use something like
<% = Request("txtName") %>
as the text field's value. In a WebItem, you accomplish this substitution in a similar manner--you insert custom HTML tags in the HTML template. Then, in the WebItem's ProcessTag() event, you provide code that instructs the WebClass to insert data into each tag. To see how this works, in Visual Basic click the End button, and then in the WebClass Designer, right-click on tplNewUser. Choose Edit HTML Template from the shortcut menu. Visual Basic displays the HTML page in Notepad. In addition to the many tags with which you're familiar, you'll probably notice a few unusual tags as well, such as
These tags are the custom tags that we mentioned previously. Just like the ASP tag, when IIS parses the page it takes note of the WC@ elements. Unlike the ASP tags, these custom WebClass tags are actually XML tokens, which act more like bookmarks than code block indicators. To replace the custom tag's default values with text from our portal's welcome page, return to the Designer and double-click on tplNewUser. In the code window, select the ProcessTag() event. Now, enter the following code:
Select Case (TagName)
	Case "WC@txtName"
		TagContents = Request("txtName")
	Case "WC@txtPassword"
		TagContents = _
	End Select
End Sub
As we mentioned, this event fires each time the WebClass encounters a custom tag in the template that begins with WC@. The TagName input parameter holds the name of the custom tag being processed. The TagContents output parameter contains the value that the WebClass will insert into the tag. Now, run the program once more, and enter a new user name and password. This time, when you click the Submit button, the new user page displays the correct data!

Save entry data to the database

At this point, we're really making progress. Of course, as for the next step we need to add the code to save the user info into a database and transfer them to the Portal page. To do so, return to the WebClass Designer and click on tplNewUser. Double-click on the Form1 element in the right pane. First, add the following three variables to the General Declarations section:
Private mstrUser As String
Private mstrFavoriteURL As String
Private mdteDate As Date
Next, add the code shown in Listing B to tplNewUser's Form1() event.

Listing B: The tblNewUser WebItem's Form1() event

Private Sub tplNewUser_Form1()
Set mconConnection = New ADODB.Connection
Set mrsUser = New ADODB.Recordset
mconConnection.Open "Provider=Microsoft.Jet.OLEDB" _
	& ".3.51;Data Source=" & App.Path _
	& "\portalMems.mdb"
With mrsUser
	.Open "tblUsers", mconConnection, _
		adOpenForwardOnly, adLockPessimistic, adCmdTable
	.Fields("txtName") = Request("txtName")
	.Fields("txtPass") = Request("txtPassword")
	.Fields("txtFavURL") = Request("txtFavoriteURL")
End With
Set mconConnection = Nothing
Set mrsUser = Nothing
End Sub

Now, when you run the program and submit the information on the new user screen, the code stores the data in the database. Then, it transfers you to the final Portal page, which, of course, doesn't display any custom information...yet.

Wrap it up

Now we just have to spruce up the portal page, and we'll have a complete site. Again, we need to insert the appropriate information into the custom tags on this WebItem just like we did on the new user page, so that the user's name and favorite URL link appear, instead of the default text. To start, double-click on the tplPortal WebItem in the Designer. In code window's General Declarations section enter the following three variable declarations:
Private mstrUser As String
Private mstrFavoriteURL As String
Private mdteDate As Date
Next, select tplPortal's ProcessTag() event and enter the code shown in Listing C.

Listing C: The tplPortal item's ProcessTag() event

Private Sub tplPortal_ProcessTag(ByVal TagName As _
	String, TagContents As String, _
	SendTags As Boolean)
Select Case (TagName)
	Case "WC@Init"
		Set mconConnection = New ADODB.Connection
		Set mrsUser = New ADODB.Recordset
		mconConnection.Open "Provider=Microsoft.Jet" _
			& ".OLEDB.3.51;Data Source=" & App.Path _
			& "\portalMems.mdb"
		mrsUser.Open "SELECT * from tblUsers where " _
			& 	"txtName='" & Request("txtName") & "' " _
			& "AND txtPass='" & Request("txtPassword") _
			& "'", mconConnection, , , adCmdText
		mstrUser = mrsUser("txtName")
		mstrFavoriteURL = mrsUser("txtFavURL")
		mdteDate = mrsUser("dtSignUp")
		TagContents = ""
	Case "WC@txtName"
		TagContents = mstrUser
	Case "WC@dteDate"
		TagContents = mdteDate
	Case "WC@txtFavoriteURL"
		TagContents = "<a href=" & Chr(34) _
			& mstrFavoriteURL & Chr(34) & ">" _
			& mstrFavoriteURL & "</a>"
End Select
End Sub
Now run the app, enter in a user name and password, click Submit, and enter your favorite URL. When you click Submit, the portal page displays your information, as shown in Figure E.

Figure E: The code for our portal page reads the appropriate data from the database, and then inserts it into the appropriate XML tokens.
[ Figure E ]

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
  3. Scan the source code with Minnow's Project Scanner

If you don't have a virus scanner, you can get one at many places on the net

Other 13 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.