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

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

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

HTTP Transfer Component: Create a Server Component Using Internet Transfer Control
By S.S. Ahmed
Rating: 3.9 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction


    This article explains how to create a server component using Internet Transfer Control (ITC). This component can be used to download files from the Internet, especially image files. Some download components allow you to download text or HTML files, but this component allows you to download binary files. Created in Visual Basic (VB), it has been tested in both VB and ASP. Images can be downloaded from a local intranet as well as from remote sites. Today's applications are expected to extend their reach globally. An application should be able to download files from any computer connected to the Internet. Luckily, Microsoft has created an ActiveX control that makes accessing files on the Internet much easier.

    click here to download the sample code used in this article

    Internet Transfer Control

    Internet Transfer Control can be used to send and retrieve documents across the net. This control uses the File Transfer Protocol (FTP) and Hypertext Transfer Protocol (HTTP). Using FTP, the user can send and retrieve files from any system connected to the Internet. Users can perform actions such as rename and delete files, create and remove directories, etc. ITC is a very handy control for VB programmers. Basically, the Internet is used for transferring data, and ITC helps programmers to use the Internet in a better way. All of the functionality of ITC is implemented through its methods, and it requires no interface.

    ITC supports both synchronous and asynchronous transfers. In synchronous transfer, you can make the system wait until the transfer is complete, and in asynchronous transfer, the system can work as usual while the file is transferred in the background. ITC has many methods and properties that will not be discussed here in detail ( refer to MSDN http://support.microsoft.com/support/kb/articles/Q163/6/53.asp for complete documentation).

    This article shows how to create and test this component in steps that will make it easier to understand the functionality. The article discusses methods and properties used in the component.

    Step 1: Creating the project

    Start a new "ActiveX DLL" project. Assign a valid name to the project, such as "HTTP, " which is used here. Assign a name to the class module, such as "Dload."

    Step 2: Adding a form

    Add a form to the current ActiveX project. This step is necessary in order to place the Internet Transfer Control on a form. Through this form, we will access the control's methods and properties. I have done this to make programming simpler and to make it easier for beginners to understand and use the control. Remember, we could have accessed the control directly in the DLL project and accessed its methods, but for simplicity, I have included a form to place the ITC on.

    Step 3: Adding functionality

    First, we are going to add some properties to the class module. The class builder utility can be used to add the following properties to the class:

    
    Private mvarStatus As Variant 'local copy
    Private mvarProxyAddress As Variant 'local copy
    Private mvarRemotePort1 As Variant 'local copy
    Private mvarRemoteHost1 As Variant 'local copy
    Private mvarProtocol1 As Variant 'local copy
    
    

    Let's discuss these properties one by one.

    The first property will be used to display the status of the file transfer. The following messages are displayed:

    • URL not provided

      This message is displayed if the correct URL is not provided or is not provided at all.

    • Timed Out

      This message is displayed when the time out occurs.

    • Server not found

      If the computer from where the file is to be downloaded is not found, then this error message is displayed.

    • File not found

      If the file is not found on the remote computer, then this message will tell the user that the file could not be found.

    • File was downloaded successfully

      This message is displayed if the file is successfully retrieved and downloaded to the system.

    The second property is used to get proxy address from the user. ITC uses this property to set or get the name of the proxy server used to access the Internet.

    The third property will be used to connect to the remote port of the server. ITC uses this property to set or get the port number of the remote system to which the control connects.

    The fourth property is used to access the remote host. ITC uses this property to set or get the address of the remote system to which the control sends and/or receives data.

    The fifth property is used to set the protocol that we are going to use in this component. As already discussed, there are two protocols used in the ITC. We shall use the HTTP protocol in our component.

    Now let's move on to the main function. Declare the function as below:

    
    Public Function DLoad(ByVal strURL As String, Optional ByVal 
    sOutPutFile As String)
    
    

    Two parameters are passed to the function. The first one is the string containing the address of the file to be downloaded, and the second parameter is the string containing the name and path of the output file to be generated. A file-handling routine is not included in this component. This will have to be incorporated in the ASP script or the VB application, whichever is used as a test driver.

    Declare the variables that will be used throughout the class module, as follows:

    
    Dim bytes() As Byte
    Dim fn As Integer
    Dim msg As String
    Dim buf As String
    Dim fnf As Integer
    Dim snf As Integer
    Dim tout As Integer
    Dim OK As Integer
    Dim tempbuf As String
    Dim strResult As String
    
    

    Bytes() is the array of bytes that will contain the downloaded material.

    fn will contain the number of the file that will be opened to be written to.

    buf is a buffer that will contain the data.

    fnf is an acronym for "file not found" and will contain the number of files not found.

    snf stands for "server not found" and will contain the number of remote addresses not found.

    tout stands for "timed out" and will contain the number of timed out messages.

    "strResult" will contain the downloaded string.

    Set the properties to default values if no values are provided by the user.

    
    'Set the transfer protocol
    If Not Protocol1 = "" Then
         Form1.Inet1.Protocol = icHTTP 'CStr(Protocol1)
         ElseIf Protocol1 = "http" Or Protocol1 = "HTTP" Then
             Form1.Inet1.Protocol = icHTTP
    Else
            Form1.Inet1.Protocol = icHTTP
    End If
    
    'Set the Access Type to Default
    Form1.Inet1.AccessType = icUseDefault
    
    'Set the proxy address
    If Not ProxyAddress = "" Then
         Form1.Inet1.Proxy = ProxyAddress
    End If
    
    If Not RemotePort1 = "" Then
         Form1.Inet1.RemotePort = RemotePort1
    End If
    
    

    Notice the way we are accessing the control's properties. Set the protocol to HTTP. The HTTP protocol is a stateless protocol. Originally, HTTP was designed for the transmission of text, but it also can be used to transfer binary files. Set the AccessType property to default. AccessType specifies how the control will access the Internet. The three possible settings for this property follow:

    • icUseDefault

      The control uses the access settings that are specified in the Windows registry to access the Internet.

    • icDirect

      The control has a direct connection to the Internet.

    • icNamedProxy

      The control uses a proxy server. The proxy server must be specified in the control's Proxy property.

    Similarly, set the remotehost and remoteport properties that are supplied by the user.

    
    On Error Resume Next
    
    If strURL = "" Then
         Status = "URL not provided"
         Exit Function
    End If
    
    Form1.Inet1.URL = strURL
    bytes() = Form1.Inet1.OpenURL(, icByteArray)
    
    strResult = Form1.Inet1.OpenURL(strURL, icString)
    
    'Essential to avoid tying up the system
    Do Until Form1.Inet1.StillExecuting = False ' WAIT Downloading..
      DoEvents
    Loop
    
    

    We use the OpenURL method of the control to retrieve the content from the remote file. The easiest way to use the Internet Transfer Control is with the OpenURL method. Two parameters are passed to this method. The first parameter is the URL of the file to be downloaded, and the second parameter is the datatype, which tells the control about the datatype of the content to be downloaded from the remote server. This can be text or binary. If you want to download a file from an FTP server, then the URL parameter should contain something like this:

    ftp://ftp.server.com/test.htm

    In case of HTTP, provide the URL in the format shown below:

    http://www.server.com/image1.gif

    The values that can be provided to the datatype parameter follow:

    • icString

      Use this type if you want to download the data as a string.

    • IcByteArray

      Use this datatype if you want to download the data as a binary.

    The URL property of the control is used to assign the URL of the file to be downloaded to the control. The OpenURL method is used twice, first to retrieve the actual data and then to retrieve the data as a text string. This may be inefficient, but I did this for demonstration purposes only. The data is retrieved as a text string because the first 50 characters of the downloaded string contain the error messages, if any.

    
    Do Until Form1.Inet1.StillExecuting = False ' WAIT Downloading..
      DoEvents
    Loop
    
    

    The above statement checks the status of the control, which is important since we want the system to wait for the control to complete the transfer. If "StillExecuting" is true, then the control is still busy downloading the file.

    
    tempbuf = bytes()
    
    'If the URL returned anything, put the first
    '50 characters in a buffer, Error messages
    'will be found here.
    If Len(strResult) > 50 Then
         buf = Left(strResult, 100)
    Else
         buf = bytes()
    End If
    
    'Trap a time-out error
    If Err = 35761 Then
         tout = tout + 1
         Status = "Timed out: " & tout
         Err.Clear
         Exit Function
    
    'If nothing is returned, it means
    'the server was not found.
    ElseIf tempbuf = "" Then
         snf = snf + 1
         Status = "Server not found: " & snf
         Exit Function
    
    'If nothing is returned, it means
    'the server was found, but the requested file was
    'not present.
    
    ElseIf InStr(1, buf, "404") Then
         fnf = fnf + 1
         Status = "File not found: " & fnf
         Exit Function
    Else
    'Otherwise, everything is OK
         OK = OK + 1
         Status = "File was downloaded successfully: " & OK
    
    End If
    
    If the downloaded string is larger than 50 chars, then transfer the 
    first 100 characters to the buffer so that the error messages can be 
    searched for.  "35761" is the time-out error.
    
    'Get a file number
    fn = FreeFile
    
    'Open a binary file and load data into it!
    Open sOutPutFile For Binary Access Write As #fn
    Put #fn, , bytes()
    DoEvents
    'Close the open file
    Close #fn
    
    

    It's time to write the information retrieved from the remote server to the local file. We have used the FreeFile function here. FreeFile function returns an integer representing the next file number available for use by the open statement. One to 255 file numbers can be used to open files not accessible to other applications. Use file numbers in the range of 256 - 511 for files accessible from other applications. SOutPutFile is the name of the output file provided by the user. We have opened the file for binary access. Put the downloaded bytes into the newly opened file. After writing the content to the file, close the file. That's it. I use this component to download image files from remote computers, and it always works fine.

    
    Private Sub Class_Terminate()
    Set Form1 = Nothing
    End Sub
    
    

    In the class_terminate() event of the class, destroy the form on which we placed the control.

    Step 4: Compile the project

    To compile the project, from the file menu, select the "Make HTTP.dll." The component is automatically registered on the computer where it is compiled, but to register it on other computers, you will have to register it manually. Use regsvr32.exe to register the component manually.

    Step 5: Testing the component

    It's good practice to test the component in VB before taking it to the ASP. If you find an error while using the component in ASP, it is quite laborious to recompile the component with new changes added to it. If such a situation occurs, stop the IIS services and unregister the component before deleting it. To unregister the component, use the following command:

    Regsvr32.exe /u component.dll

    Recompile the component, and start the IIS services. To test the component in VB, add a standard EXE project to the current project. Add two command buttons on the form, change the caption of one button to "Test Dload Component," and change the caption of the other button to "Exit," as follows:

    
    Private Sub Test_Click()
    Dim objHTTP As New HTTP.DLoad
    Dim strURL As String
    objHTTP.Protocol1 = icHTTP
    objHTTP.ProxyAddress = ""
    objHTTP.RemotePort1 = 80
    strURL = "http://server/application/images/image1.gif"
    objHTTP.DLoad strURL, "c:\test.gif"
    MsgBox objHTTP.Status
    
    Set objHTTP = Nothing
    
    End Sub.
    
    

    The test code is rather simple. Set the property values and provide the name of the file to be downloaded.

    Use the code below to test the component in ASP.

    
    Dim objHTTP
    Set objHTTP = server.createobject("HTTP.Dload")
    Dim strURL
    objHTTP.Protocol1 = icHTTP
    objHTTP.ProxyAddress = ""
    objHTTP.RemotePort1 = 80
    strURL = "http://server/application/images/image1.gif"
    objHTTP.DLoad (strURL, "c:\test.gif")
    response.write objHTTP.Status
    
    Set objHTTP = Nothing
    
    

    The string (string containing the name of the file to be downloaded) parsing code is found in the ASP file provided with this article. VB code is also provided. ASP code contains two ASP pages. Form1.asp is the initial form and the results from form1.asp are passed to form2.asp. In form2.asp, an object is created and the values from form1.asp are passed to the object.

    The VB code contains a form, and values that are to be passed to the object are hard-coded in the form. You can change the values to test the functionality.

    About the Author

    S.S. Ahmed is a senior software engineer in a software development company that specializes in Web application development. To contact Ahmed with questions or comments, please email him at ss_ahmed1@hotmail.com.

  • 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

    internet.commediabistro.comJusttechjobs.comGraphics.com

    Search:

    WebMediaBrands Corporate Info

    Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
    Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs