asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

In a Class of Its Own
By John Timney
Rating: 3.7 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    The newsgroups seem to be popping again with quizzical developers struggling to get a gripon the fundamentals of Visual Basic 6.0 and its new Internet Information Server (IIS) applications, more commonly known as Webclassing. This new technology should have been second nature VB developers who have dabbled with Active Server Pages (ASP) and ActiveX DLL files. However, it isn’t! So this article will use this new webclass technology in a practical document management example to breach the fine boundary between webclasses and ASP. This example is part of a planned "on-line" C.V.-resume-database-driven system designed for a company’s human resources department.

    Some of you will ask, "What is a webclass?" Well, the official line on a webclass is this:

    A webclass is a Visual Basic component that resides on a Web server and responds to input from the browser. When you create an IIS application, you create its webclass using the Webclass Designer. Webclasses typically contain webitems and the code that delivers those webitems to a client.
    I hear you saying, "What’s a WebItem?" Again, it’s a term borrowed (isn’t that another word for stolen!) from the VB6 documentation;
    A WebItem in an IIS application is an item that can be returned to the browser as part of a response to an HTTP request. A Web item is generally an HTML page, but it can be a MIME-type file, such as an image, a .wav file, and so on.
    So how does it all fit together?

    Well, a webclass typically contains Web items that it uses to provide content to the browser and to expose events. Primarily a Web item can be one of two things:

    • An HTML template file
    • A custom Web item

    Aren’t they really the same thing?

    HTML template files are HTML pages that you associate with your webclass. When the webclass receives a request, it can send the HTML page designated as the template file to the browser for display. With templates you have to connect your new webclass events to existing things, like form buttons and drop-down boxes. This allows you to customize what your response will be to a button press or a select box selection.

    Custom Web items do not have an associated HTML page they can return to the user. Instead, a custom Web item is a programmatic resource that consists of one or more event handlers that are logically grouped together to help organize your Web application. These event handlers are called from the browser, either when the page loads or when a user selects an HTML element.

    So how do I know which one is right for me?

    Regardless of whether you use templates or custom Web items, IIS triggers the event handlers for the custom item you have chosen either to generate a response to the browser or pass processing to another of the webclass's Web items. A strong characteristic of webclasses is that both templates and custom Web items expose events that the webclass can process when certain actions occur in the browser. Thus, with relative ease, the VB programmer can write event procedures for these events using standard Visual Basic code, creating a link between the actions that occur on a Web page and a common Visual Basic routine. This demonstrates how easy it is to remove business logic from presentation logic and create interface-independent code.

    Web button events can be custom driven. To make the code a little more interesting, the webclass example we use will demonstrate the following aspects:

    • Uploading files by reading from stdin and the HTML form-field type
    • Converting data using Unicode
    • Appending documents to a SQL Server 6.5 database field using Binary Large Objects (BLOBs)
    • Extracting BLOB data from a database
    • Writing binary data back to a client browser as a specific MetaType
    Basically it takes files from the client side (the Web browser) and puts them on the server (the Web server), and if it’s a document file, it sticks it in a database. But it doesn’t cover every aspect in detail, because primarily it’s an amalgamation of code to show how to perform these tasks in a VB6 webclass. (There are some excellent articles on the Web already about some of the things covered in this article, so it’s worth searching the Web for the areas you’re specifically interested in.)

    The solution I am demonstrating here was developed and tested on a Windows NT4 workstation (at service pack 3) with a local installation of Microsoft SQL Server 6.5 and the PUBS sample database also installed. The Web server of choice is naturally IIS4 from the Option Pack installed locally, along with a copy of VB6 Enterprise without the service pack, although the service pack should not matter. This is not the typical environment we tend to use. The first cut of the solution was done on a Compaq Proliant 6500 Raid 5 twin processor IIS4 Web server with 28 Gigabyte of disk space and 512 meg of RAM. This was a little excessive for this demo so we tuned it down to be a little more realistic to the development environment owned by the majority of people expected to read this article.

    The article does assume some experience with VB and expects certain knowledge of ASP, but not much. Also, please be aware that very little error handling is built into the example. You’ll have to sort that out yourself.

    1. Open ISQL/w, connect to your server, and choose the PUBS database device.
    2. Run the following query against the database.
      
      CREATE TABLE dbo.documents (
      	id int IDENTITY (1, 1) PRIMARY KEY CLUSTERED NOT NULL ,
      	doc image NULL ,
      	description varchar (255) NULL 
      )
      GO
      
      
      This creates the table called Documents that we will use as the target of uploaded doc files. The code will determine if an uploaded file is actually a doc file by using the Microsoft Word tag hidden within the binary data of every Word document rather than the file extension. After all, anyone can change the name of a file extension. (A changed file extension could cause problems to the HTML Meta Header used to display a binary file held within the database once it has been uploaded.) Once the table has been created, we can start with the VB6 webclass code.

      Figure 1

    3. Open a new IIS application in VB6. A new Webclass designer is created by default. As you can see, it contains event handlers for Custom WebItems and HTML Template WebItems. We are going to concentrate on Custom WebItems because there are samples for template Web items on the Microsoft site in the VB area.
    4. Open the Properties window for the webclass.

      Figure 2

    5. Rename the webclass to URLUploader and change the NameInURL field to match. For this example, we are not interested in StateManagement, so leave that as it is.

    6. Change the name of the project to Uploader and save the project.

    7. In the webclass designer window, right click the mouse and choose Add Custom WebItem. Rename the Custom WebItem Event to DoUpload.
    8. In the webclass designer window, right click the mouse and choose Add Custom WebItem. Rename the Custom WebItem Event to GetDoc.

      By creating a webclass designer, the designer automatically puts in some default code for you. We don’t need this code. It’s only there to show the novice what’s happening. If you were to press F5 at this point, the designer would attempt to invoke a page based upon the WebClass_Start event. If you accept the defaults, it will set a virtual directory up in the IIS Management console with execute permissions for an Out of Process Server. It will also set up the local IIS server to allow Out of Process Servers. It will remain as an Out of Process application until you decide to compile the webclass to an IIS-linked ActiveX.DLL.

    9. Double click on an event and the webclass designer code area will open with the following default code provided. Highlight it and strip it out
      
      Option Explicit
      Option Compare Text
      
      Private Sub WebClass_Start()
      'Write a reply to the user
          With Response
              .Write "<html>"
              .Write "<body>"
              .Write "<h1><font face=""Arial"">WebClass1's Starting Page</font></h1>"
              .Write "<p>This response was created in the Start event of WebClass1.</p>"
              .Write "</body>"
              .Write "</html>"
          End With
      End Sub
      
      Private Sub WebItem1_Respond()
      End Sub
      
      
    10. Now we have an empty designer with two customer events. We can now start adding the code to make the webclass function. Add the following to the general declaration section of the webclass designer:
      
      Option Explicit
      Option Compare Text
      
      
      The following fields are used to handle the stdin data:
      
      Private stdin As Variant
      Private HeaderMarker As Variant
      Private DataType As Variant
      Private ContentType As Variant
      Private FileContent As Variant
      Private FileNameUploaded As Variant
      Private FileName As Variant
      Private ToUniCode As Boolean
      Private mWebFieldName As String
      
      
    11. Define the Temp path for storing uploaded files. We will assume that you have a Temp directory on C.
      
      Const serverPath As String = "C:\TEMP\"
      Dim commdict1 As Object
      Dim commdict2 As Object
      
      
    12. Define the connection string to connect to the SQL database. We have assumed the default user of SA.
      
      Const ConnStr = "DRIVER={SQL Server};SERVER=YourServerName;UID=sa;PWD=;DATABASE=pubs"
      
      
      The most critical event for any webclass is the Start event. It is here that we define what our first step will be and what actions our webclass will perform. We will call a function called StartThingy when the class is initiated or when it is reloaded.

    13. Add the Webclass_Start event to the webclass.
      
      Private Sub WebClass_Start()
          
          Call StartThingy
          
      End Sub
      
      
      StartThingy is the custom function we will use to direct the initial output for the webclass. This will actually create our first page and serve it back to the user via the Web browser. For this project, it creates a page that allows the user to provide a file to upload to the server. The file the user chooses can be of any type, but any Microsoft Word files will automatically be converted to a Binary Large Object and inserted into the SQL Server database.
    14. Add the StartThingy function to the designer.
      
      Private Function StartThingy()
      
      With Response
          .Write "<html>"
          .Write "<head><title>File Upload</title></head>"
          .Write "<h1>John Timney’s Webclass Driven Binary Database Device<h1>"
          .Write "<body>"
          .Write "<h1>This interface was generated from a VB6 Webclass</h1><br>"
          .Write "<form ENCTYPE=" & """multipart/form-data""" & " action=" 
          .Write """URLUploader.ASP?WCI=DoUpload""" & " Method=" & """post""" & ">"
          .Write "File Name<BR>"
          .Write "<INPUT NAME=" & """UploadField""" & " SIZE= " & """50""" & " TYPE=" & """file""" & ">"
          .Write "<BR>File Description"
          .Write "<BR><input type=" & """text""" & "size=" & """50""" & "name=" & """FieldName1""" & ">"
          .Write "<BR><input type=" & """submit""" & "value=" & """Upload""" & " name=" & """btnUpload""" & ">"
              '# if this button is pushed in the Web page, it will process the action of the DoUpload function
              '# as outlined in the above form method
          .Write "</form>"
          .Write "</body>"
          .Write "</html>"
      End With
      
      Response.End
      
      End Function
      
      
      If we disseminate the code a little, for anyone familiar with ASP, your attention should be drawn to the line containing the following string;
      
      .Write "<form ENCTYPE=" & """multipart/form-data""" & " action=" 
      .Write """URLUploader.ASP?WCI=DoUpload""" & " Method=" & """post""" & ">"
      
      
      specifically the """URLUploader.ASP?WCI=DoUpload""".

      In simple terms, webclasses respond to a particular tag on the query string called a tag prefix. You can set this in Custom WebItem properties but it’s better left alone. The WCI= tells the webclass what to do with the form submit event and what function or subroutine to activate. So the first parameter in the query string is the function we wish to have activated if the user presses the submit button and posts the form. In this example it’s the DoUpload function, and it not only uploads the data, but disseminates it very nicely from its binary. I cannot claim all the credit for this function. I struggled with some of the binary positioning of the unicode data conversion, specifically the true end of the multipart/form data tag. It’s never easy working with binary data in VB, so a pat on the back goes to David for an example he made available to the news community that helped me complete the example given here.

      Add the DoUpload function to the webclass.

      
      
      Private Sub DoUpload_respond()
      
      Dim fs As Object
      Dim target As Variant
      Dim bytecount As Variant
      Dim sFileName As String
      Dim sFile As Object
      Dim name As Variant
      Dim tVal As Variant
      Dim sExtraFieldContents As Variant
      Dim dbconnection As Object
      Dim rs As Object
      Dim SQLquery As String
      Dim counter As Integer
      Dim a As Variant
      
      
      With Response
      
      Set fs = CreateObject("Scripting.FileSystemObject")
      
      '# convert the data to a safe array
      '# how many bytes were passed as the post request
      
      bytecount = Request.TotalBytes
      '# set the prDataToUniCode property with the bytes from the post request
      '# so we can search through it all
      prDataToUniCode = Request.BinaryRead(bytecount)
      '# extract the name of the file from the posted data
      sFileName = fnConvertField("UploadField")
      '.Write "<BR>Your Remote Filename was received as = " & sFileName
      If sFileName = "Field Exists but no file contents were sent." Then
      .Write "No File"
      Else
      
      '# write the file to the upload area
      '# we could take the binary data and dump it straight into the database
      
      Set sFile = fs.CreateTextFile(serverPath & sFileName, True)
      sFile.Write (FileContents)
      sFile.Close
      
      '# we need to write the file to the DB dependent on it being a
      '# doc file, no other files will be put in the DB, they will simply be
      '# stored in the server directory
      
      '# to do this, check stdin for the word identifier in the file data
      If InStr(1, stdin, "Microsoft Word") Then
      
      '# is there anything in the extra text fields
      '# we can’t use the response object once the binary read function has been initialized
      '# so we must use the actual binary field contents from the safe array
      
      sExtraFieldContents = fnConvertField("FieldName1")
      tVal = CreateIDRecord(CStr(sExtraFieldContents))
      insertBLOB tVal, serverPath & sFileName
      
      fs.DeleteFile serverPath & sFileName, True
      Set fs = Nothing
      
      '# the file is in the database, list all the descriptions
      
          .Write "<html>"
          .Write "<head><title>Database Contents</title></head>"
          .Write "<h1>John Timney’s Webclass Driven Binary Database Device<h1>"
          .Write "<body>"
          .Write "<form action=" & """URLUploader.ASP?WCI=GetDoc""" & " Method=" & """post""" & ">"
          .Write "<BR>Document Description"
          
          Set dbconnection = Server.CreateObject("ADODB.Connection")
          dbconnection.Open ConnStr
          SQLquery = "Select id, description FROM documents order by ID ASC"
          Set rs = dbconnection.Execute(SQLquery)
      
      '# pass the rs values into some dictionary objects, this means we can retain
      '# the values away from the recordset, better for performance.
      '# one as a session var as WebClass needs it elsewhere
          
          Set Session("commdict1") = CreateObject("Scripting.Dictionary")
          Set commdict2 = CreateObject("Scripting.Dictionary")
          counter = 1
          Do While Not rs.EOF
              Session("commdict1").Add CStr(counter), CStr(rs.fields("ID"))
              commdict2.Add CStr(counter), CStr(rs.fields("Description"))
          counter = counter + 1
          rs.MoveNext
          Loop
          rs.Close
          Set rs = Nothing
          dbconnection.Close
          Set dbconnection = Nothing
              
          .Write ("<select name =" & """FieldName1""" & ">")
              
          For Each a In Session("commdict1")
              .Write "<option value=" & a & ">" & commdict2.Item(a)
          Next
          
          Set commdict2 = Nothing
          
          .Write ("</select>")
          
          .Write "<BR><input type=" & """submit""" & "value="
          .Write """Fetch Document""" & " name=" & """GetDoc""" & ">"
              '# If this button is pushed in the Web page, it will process the action of the DoUpload function
              '# as outlined in the above form method
          .Write "</form>"
          .Write "</body>"
          .Write "</html>"
      
      Else
      
      .Write "<H2>Your upload of file " & sFileName & " is complete</H2>"
      
      End If '# end the word file type check
      
      End If
      
      End With
      
      End Sub
      
      
    Read this section carefully because it attempts to cover in a simplistic view some of the intricacies of the very scary BinaryRead method. The BinaryRead method is used to read the raw data sent by the client as part of a POST request. This method is used for low-level access to this data, as opposed to, for example, using the Request.Form collection to view form data sent in a POST request. Once you have called BinaryRead, referring to any variable in the Request.Form collection will cause an error. Conversely, once you have referred to a variable in the Request.Form collection, calling BinaryWrite will cause a trappable error. In this case, trapping the error is really a pointless venture and only useable at design time, we have to work around it via the safe array to be able to query the forms collection.

    Remember, if you access a variable in the Request collection without specifying which subcollection it belongs to, the Request.Form collection may be searched, bringing this rule into force. BinaryRead is used to retrieve the data from the request object and store it in a safe array. A SafeArray is an array that contains information about the number of dimensions and the bounds of its dimensions. This causes problems for Web developers. Normally we access the forms collection by simply asking for Request.Form("FieldName1"), but this will cause an error. The fnConvertField function will handle the data in the safe array and thus allow us to call the contents of the form collection with the new syntax of fnConvertField("FieldName1").

    Moving On…

    We now have the code for disseminating the binary data and actually importing the data in the PUBS table. We need some other properties to enable the above functions to work correctly.

    Add the following to the webclass designer.

    
    Public Property Get WebFileNameTitle()
    
    '# this has to be padded, filename= is actually " and ; filename=
        WebFileNameTitle = Chr(34) & "; filename="
    
    End Property
    
    
    Public Property Get WebFieldNameTitle()
    
        WebFieldNameTitle = "name="
    
    End Property
    
    Public Property Get UniMe(strIn)
    '# convert the string to a unicode byte value to represent the length of the string
    '# with the quotes
    UniMe = Len(StrConv(strIn, vbUnicode))
    
    End Property
    
    
    Public Property Let prDataToUniCode(ByVal vNewValue As Variant)
        If Not IsEmpty(vNewValue) Then
            ToUniCode = True
            stdin = StrConv(vNewValue, vbUnicode)
            HeaderMarker = LeftB(stdin, 84)
            ' result should look something like this
            ' -----------------------------7cf18f135e011
        Else
            ToUniCode = False
        End If
    End Property
    
    Public Property Get FileContents() As Variant
        If DataType = "file" Then
            FileContents = FileContent
        Else
            FileContents = Null
        End If
    End Property
    
    Private Sub Class_Initialize()
        ToUniCode = False
    End Sub
    
    Public Property Get ToUniCodeData() As Variant
        ToUniCodeData = stdin
    End Property
    
    
    The DoUpload function also calls a number of required functions to handle the database insert. The InsertBLOB function relies on the premise that a record already exists in the database. This would be a good place to hook in Microsoft Transaction Server functionality. Paste the following functions into the designer.
    
    Public Function CreateIDRecord(strIn As String) As Integer
    
    Dim dbconnection As Object
    Dim myQuery As Object
    Dim rs As Object
    Dim SQLquery As String
    
    '# create a record for the new file
        SQLquery = "Insert into documents(description) values (" & "'" & strIn & "'" & ")"
        Set dbconnection = Server.CreateObject("ADODB.Connection")
        dbconnection.Open ConnStr
        dbconnection.Execute (SQLquery)
        
    '# What ID was assigned to it
        SQLquery = "select max(id) as ID from documents"
        
        Set rs = dbconnection.Execute(SQLquery)
        
        Do While Not rs.EOF
            rs.movefirst
            CreateIDRecord = rs("ID")
        rs.MoveNext
        Loop
        
        rs.Close
        Set rs = Nothing
        dbconnection.Close
        Set dbconnection = Nothing
    
    End Function
    
    
    Public Function insertBLOB(id As Variant, fName As Variant, Optional inBin As Variant)
        
        ' This routine relies on an existing record.  You must insert the record
        ' into the DB first and then call this routine to add the image/BLOB data.
        
        Const BLOCKSIZE = 100
    
        Dim MyParameter As Object
        Dim myQuery As Object
        Dim strSQL As String
        Dim lngColumnSize As Long
        Dim intNumBlocks As Integer, intLeftOver As Integer
        Dim bytData() As Byte
        Dim i As Integer
        Dim intcomplete
            
        strSQL = "UPDATE documents SET doc = ? WHERE id = " & id
        Set myQuery = CreateObject("ADODB.Command")
        myQuery.activeconnection = ConnStr
        myQuery.CommandText = strSQL
        myQuery.Parameters.Refresh
        Set MyParameter = myQuery.Parameters(0)
    
        Open fName For Binary Access Read As #1
        lngColumnSize = LOF(1)
           
        intNumBlocks = lngColumnSize \ BLOCKSIZE
        intLeftOver = lngColumnSize Mod BLOCKSIZE
    
        ReDim bytData(BLOCKSIZE)
        For i = 0 To intNumBlocks - 1
            Get #1, , bytData()
               
            MyParameter.AppendChunk bytData()
            If Int((CLng(i) * 100) / CLng(intNumBlocks)) > intcomplete Then
                intcomplete = Int((CLng(i) * 100) / CLng(intNumBlocks))
                Debug.Print "Appending to database... (" & intcomplete & "% Complete)"
            End If
        Next i
        ReDim bytData(intLeftOver)
        Get #1, , bytData()
        MyParameter.AppendChunk bytData()
    
        myQuery.Execute
    
        Close #1
    
        myQuery.activeconnection.Close
        Debug.Print "Append completed successfully"
    
        Set myQuery = Nothing
        
    End Function
    
    
    This is the key function used to extract the data from stdin using the unicode converted data.
    
    Public Function fnConvertField(Fieldname)
    
    On Error GoTo local_error_handler
    
    Dim lbinFieldName As Long
    Dim formNameEndTag As Long
    Dim fieldNameEndTag As Long
    Dim fileNameField As Long
    Dim MimeType As Long
    Dim lineFeed As Long
    Dim lHeader As Long
    
        On Error Resume Next
        If Not ToUniCode Then
           fnConvertField = "No HTTP Post Data Found"
           Exit Function
        End If
    
        ' search for the form field requested, look for name=
        ' rather than filename=
        ' we want the byte position of the first occurrence of this string
        lbinFieldName = InStrB(1, stdin, WebFieldNameTitle & Chr(34) & Fieldname & Chr(34))
    
        ' search for the last quote (") at the end of the form field name
        ' Chr(34) is the character code for a quotation mark (").
        ' this indicates where the form field name value ends
        ' it does not end with the field separator value ; and occurs
        ' before the filename field quotation starts
        ' Add the length of name= and a quotation mark as a unicode byte value
        ' now remember we are working with unicode lengths, thus the size is not the same as usual
        formNameEndTag = InStrB(lbinFieldName + UniMe(WebFieldNameTitle & Chr(34)), stdin, Chr(34))
        
        ' now search the data
        ' look for ; after the " at the end of the form field name this
        ' indicated it is the file upload field, if it’s not there then it’s a standard field
        If MidB(stdin, formNameEndTag + 2, 2) = ";" Then
                      
            ' found ; so it should be a file
            ' find the last " after the filename
            ' Chr(34) is the character code for a quotation mark (").
            
            fieldNameEndTag = InStrB(formNameEndTag + UniMe(WebFileNameTitle & Chr(34)), stdin, Chr(34))
            
            ' get the name of the file that was uploaded includes the full
            ' path from client’s side
            FileNameUploaded = MidB(stdin, formNameEndTag + UniMe(WebFileNameTitle & Chr(34)), _
    		fieldNameEndTag - formNameEndTag - UniMe(WebFileNameTitle & Chr(34)))
            
            ' parse just the file name out of above using InstrRev
            ' This Returns the position of an occurrence of one string
            ' within another, from the end of string.
            ' look for the backslash char
            fileNameField = InStrRev(FileNameUploaded, Chr(92))
            FileName = Mid(FileNameUploaded, fileNameField + 1, Len(FileNameUploaded) - fileNameField)
            ' make sure a file did get uploaded
            
            If FileName <> "" Then
                DataType = "file"
                fnConvertField = FileName
                ' what’s the MIME content type or type of file
                ' it starts following the actual field name end tag
                ' not the field name title end tag
                ' To get the Mimetype position, we must extract everything left of the first :
    	    ' (the end of the content-type string
                MimeType = InStrB(fieldNameEndTag, stdin, Chr(58))
                ' Return the byte position of the first occurrence of the
                ' character 13 value, the carriage return linefeed combination
                '# following the identification of the MimeType position
                lineFeed = InStrB(MMimeType, stdin, Chr(13))
                ' ID the content type of the file being sent
                ' following the ID of the MIME type text location
                ContentType = MidB(stdin, MimeType + UniMe(": "), lineFeed - MimeType - UniMe(": "))
                ' get the header marker that tells us that we have reached the end of the file contents
                lHeader = InStrB(lineFeed, stdin, HeaderMarker)
                ' Save the actual file content in a variant
                ' start 4 unicode chars from the linefeed, this is where the file data begins
                ' end 6 unicode chars from the end of the linefeed, this is where the file data ends
                FileContent = MidB(stdin, lineFeed + UniMe(Space(4)), lHeader - lineFeed - UniMe(Space(6)))
            Else
                ' file field exists but no file was uploaded
                fnConvertField = "Field Exists but no file contents were sent."
            End If
        Else
            ' did not find ; so it is not a file
            DataType = "notfile"
            ' find the end of the value of the field by finding the next header marker
           lHeader = InStrB(formNameEndTag + UniMe(Space(2)), stdin, HeaderMarker)
           ' get the value of the field
            fnConvertField = MidB(stdin, formNameEndTag + UniMe(Space(5)), lHeader - formNameEndTag - UniMe(Space(7)))
            
        End If
    
    Exit Function
    
    local_error_handler:
    
    fnConvertField = "An error " & Err.Number & " occurred during Field Conversion"
    
    End Function
    
    
    At first glance, this example is rather complicated. It is designed to show the webclass in action, so you will need to do a little work to make it a fully operational and a scalable solution. It does, however, work quite admirably, and we can prove it with the following function. The GetDoc Respond function takes a single ID argument extracted from the Web page created from the DoUpload event. The DoUpload event is the one that tagged the GetDoc button to the following custom event ("""URLUploader.ASP?WCI=GetDoc""")

    Add the GetDOC Respond event to the designer.

    
    Private Sub GetDoc_Respond()
    
    '# extract the desired doc from the db based on the doc id
    GetBLOBFile CInt(Session("commdict1").Item(CStr(Request.Form("FieldName1"))))
    
    '# don’t forget to release your objects
    Set Session("commdict1") = Nothing
    
    End Sub
    
    
    The GetDoc_Respond event calls the GetBLOBFile function to extract the requested DOC file from the database and feed it out to the browser as a recognized and specific browser content type.
    
    Public Function GetBLOBFile(Optional id As Integer)
    
    ' This ASP expects an input parameter DOCID that represents the
    ' key of the table holding the BLOBs.
    ' We set the content type to a Word document, and the client browser
    ' reacts accordingly to the MIME type.
    
    Dim dbconnection As Object
    Dim rs As Object
    Dim SQLquery As String
    
    Response.Buffer = True
    Response.Clear
    
    '# need some code to determine what the content type would be
    
    Response.ContentType = "application/MSWord"
    
    Set dbconnection = Server.CreateObject("ADODB.Connection")
    dbconnection.Open ConnStr
    
    If IsEmpty(id) Then
        id = 0
    End If
    
    SQLquery = "SELECT doc FROM documents WHERE id = " & id
    Set rs = dbconnection.Execute(SQLquery)
    If Not rs.EOF Then
    Response.BinaryWrite rs(0)
    End If
    rs.Close
    
    Set rs = Nothing
    dbconnection.Close
    Set dbconnection = Nothing
    
    Response.End
    
    End Function
    
    
    And that’s it.
    
    
    If you have added all the functions successfully, you should have a functional webclass driven by custom events that can upload files to a server. Doc files will be inserted into the database with a description; other files will be stored in the Temp directory. Following an upload, a page will display the current file descriptions of the DOC files and allow the user to view the DOC file in the browser.

    You can compile the webclass if you wish. On compilation a new DLL and a series of associated files, including an ASP file, will be created. The files can be moved to a directory with relevant permissions and registered using Regsvr32.EXE as if it was just another ActiveX.DLL.

    Now wasn’t that easy after all?

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Apr 27, 2004 - Develop and Customize Web Parts with Custom Tool Parts
    Tool Parts provide an interface for Web Part properties well beyond the capabilities of the default property pane. In this article Gayan Peiris shows how to customize Web Parts with custom Tool Parts.
    [Read This Article]  [Top]
    Apr 7, 2004 - Reusable Components in ASP.NET 2.0, Object Binding and Precompilation
    This article demonstrates how to create a reusable component in ASP.NET 2.0 and then consume it from an ASP.NET page. Also learn how the ObjectDataSource control can be used to directly bind the output of an object to the controls in an ASP.NET page and how precompilation can be used to increase the performance of the Web application and catch compilation errors.
    [Read This Article]  [Top]
    Mar 31, 2004 - Build a Managed BHO and Plug into the Browser
    Browser Helper Objects (BHOs) are COM components that communicate with Internet Explorer to enrich the browsing experience. Michele Leroux Bustamante returns to the world of COM to show you how to build a managed BHO with the help of the .NET Framework's COM interoperability features.
    [Read This Article]  [Top]
    Feb 18, 2004 - Customizing SharePoint Web Parts with Custom Properties
    In addition to creating custom Web Parts for SharePoint Portal Server, developers can actually create their own custom properties to further enhance Web Part appearance and behavior. Gayan Peiris explains the process and provides all the necessary code.
    [Read This Article]  [Top]
    Sep 26, 2003 - Accessing Shared Resources Using ASP.NET
    Accessing shared resources is a challenge for many ASP.NET developers. Tony Arslan explains how a simple serviced component can solve this infamous problem.
    [Read This Article]  [Top]
    Oct 2, 2002 - Function Pointers and COM
    Using callbacks and function pointers in VB can be risky and complicated. Ben Garcia explains his work-around for the function pointer issue he encountered while creating the VB version of his SNMP component.
    [Read This Article]  [Top]
    Sep 4, 2002 - Creating an SNMP Component - Part 2
    In part two of this intriguing article series, Ben Garcia shows how to build an updated and improved SNMP component in VC++ AND VB, and he briefly explains why limitations in VB make VC++ a better language for developing this type of application.
    [Read This Article]  [Top]
    Jul 23, 2002 - Creating an SNMP Component
    Ben Garcia sheds some light on the Simple Network Management Protocol (SNMP). First he provides a history of SNMP, then he dives right into its architecture. Finally, he shows how to build a COM component that communicates with SNMP-enabled devices.
    [Read This Article]  [Top]
    Jun 26, 2002 - Accessing Caller ID from the Web - Part 1
    Paul Apostolos begins his series on using Web services and the MSComm32.OCX component to access caller id information from a Web page. In part 1, learn how to write the Visual Basic program that runs on the server and updates a database with incoming callers.
    [Read This Article]  [Top]
    Nov 20, 2001 - Creating a Server Component with VB - Redesigned - Part 2
    Doug Dean explains different methods of retrieving and manipulating data from a database in a VB DLL so that it is ready to be rendered in a browser.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers