DLL example of ASP encapsulation developed using VB

Source: Internet
Author: User

Encapsulation brings many benefits to DLL, including only protection of property rights and improvement of efficiency and security performance. In this example, the encapsulated DLL file can hide the actual path of the Access database.

DLL generated by VB encapsulates ASP code to connect to the database (ACCESS ).

This document describes how to encapsulate ASP code as a DLL file by using the simplest example of connecting to the access database.

We use VB to encapsulate ASP code in the most common way.

We need to encapsulate the following objects:

'Proconn. asp
Dim proconn
Set proconn = server. Createobject ("ADODB. Connection ")
Proconn. Open "driver = {Microsoft Access Driver (*. mdb)}; uid =; Pwd = 123; DBQ =" & server. mappath ("DB. asp ")

We encapsulate the following parts
"Driver = {Microsoft Access Driver (*. mdb)}; uid =; Pwd = 123; DBQ =" & server. mappath ("DB. asp ")

Analyze the content to be encapsulated,
The first half is a string:
"Driver = {Microsoft Access Driver (*. mdb)}; uid =; Pwd = 123; DBQ ="
Connect the second half of the string.
Another string in the second half is the return value of the server. mappath object function.

Next we will start the encapsulation operation process.
First
Create an ActiveX dll project under VB, and change project name project1 to condbdll
Method class1 name changed to CS
The project name and method name will be used when calling this DLL. You can define them according to your naming rules, but please be careful when using them.
The DLL code is written as follows:

Dim RP as response
Dim RQ as request
Dim AP as application
Dim SR as server
Dim sn as session

Public sub onstartpage (myscriptingcontext as scriptingcontext)
Set Rp = myscriptingcontext. Response
Set RQ = myscriptingcontext. Request
Set sr = myscriptingcontext. Server
Set ap = myscriptingcontext. Application
Set Sn = myscriptingcontext. Session
End sub

Public sub onendpage ()
Set Rp = nothing
Set RQ = nothing
Set sr = nothing
Set ap = nothing
Set Sn = nothing
End sub
'The above statement is required. The original object is simplified and processed in two basic functions.

Public Function connectdb () as Variant
Connectdb = "driver = {Microsoft Access Driver (*. mdb)}; uid =; Pwd = 123; DBQ ="
End Function
'The above function processes the First Half of the string and returns the content of the string directly.

'Define the following function to process the second half of the content.
Public Function dbpath () as Variant
Dbpath = Sr. mappath ("DB. asp ")
End Function
'Note that the SR is used above. Do not use server.

To the key step, add the reference "Microsoft Active Server Pages objectcontext Object Library" to this project
Add method, select "project"-> "Reference" from the menu, and select in the displayed dialog box.
By the way, select "Microsoft ActiveX Data Objects 2.6 library"

After completing the above operations, we can compile and generate the DLL. (do not forget to change the project name and method name)

Prepare the database file dB. asp (changed by DB. mdb suffix, password 123)

The following is the ASP file code that calls the encapsulated database connection:

Because it is a self-created DLL, after copying it to the corresponding directory, it must be registered before it can be used.
The registration method is executed in "run:
Regsvr32.exe dllname. dll

The method to cancel the registration of this DLL is: regsvr32.exe/u dllname. dll

After registration, we basically finished our work. Now we can use this encapsulation method to connect to a targeted database.

However, note the following:
Because
Dim condb
Set condb = server. Createobject ("condbdll. Conn ")
'Condb is the created DLL object.
This is the object created in ASP, including proconn, So we remember to release these two objects in any other ASP files that use (reference) proconn. asp!
Proconn. Close
Set proconn = nothing
Set condb = nothing
Otherwise, the system will become increasingly overwhelmed because the objects are not released.

For how to encapsulate the ASP code to connect to the Access database, I would like to apply the connection method of other databases.

For example, the following encapsulation example:

First, declare the variable:

Private wenscriptingcontext as scriptingcontext
Private wenapplication as application
Private wenrequest as request
Private wenresponse as response
Private wenserver as server
Private wensession as session

To use ASP built-in objects in the wenconnection class, you must write an onstartpage subfunction in this class. That's because no matter when the user accesses an ASP file with this component, IIS will send scriptingcontext to our object for use. This scriptingcontext includes all ASP methods and attributes, which enables us to access all ASP objects.

Public sub onstartpage (passedscriptingcontext as scriptingcontext)
Set wenscriptingcontext = passedscriptingcontext
Set wenapplication = wenscriptingcontext. Application
Set wenrequest = wenscriptingcontext. Request
Set wenresponse = wenscriptingcontext. Response
Set wenserver = wenscriptingcontext. Server
Set wensession = wenscriptingcontext. Session
End sub

Since we use the onstartpage function to create an object, we will use the onendpage subfunction to release the object here:

Public sub onendpage ()
Set wenscriptingcontext = nothing
Set wenapplication = nothing
Set wenrequest = nothing
Set wenresponse = nothing
Set wenserver = nothing
Set wensession = nothing
End sub

The following two functions are defined: rsresult () and datasource ():

Public Function RS (strsql as string) as recordset
Dim oconn as connection
Dim ors as recordset
Dim strconnstring as string
Strconnstring = "driver = {SQL Server}; server = servername; uid = sa; Pwd = ;"&_
"Database = databasename"
Oconn. Open strconnstring
ORS. activeconnection = oconn
Strsql = "select * From tablename"
ORS. Open strsql, oconn, 1, 3
Set rs = ors
End Function

Public Function performanceconnection () as Variant
Performanceconnection = "driver = {SQL Server}; server = servername; uid = sa; Pwd =; database = databasename"
End Function

3. Save the project name as wenadodb. VBP and the Save class name as wenconnection. CLs, and then click "file"-> "generate wenadodb. dll" to compile it into a dynamic connection library file. While compiling the dynamic connection library file, VB also registers the component to the Registry. If you want to register the component on another machine, use the following command to register or anti-register:

Regsvr32 X:/path/wenadodb. dll X:/path/the drive letter and path for storing the wenadodb. dll file

Regsvr32/u x:/path/wenadodb. dll parameter U is not registered

4. Example of calling the wenadodb. dll component in the ASP file.

<%

Set conn = server. Createobject ("wenadodb. wenconnection") 'Call the component to create an object instance
Objconn = conn. performanceconnection ()
Application ("strconn") = objconn

Set rs = server. Createobject ("ADODB. recordset ")
SQL = "select * From tablename order by ID DESC"
Rs. Open SQL, application ("strconn"), 1, 3
%>
<Table align = "center" border = "1">
<%
If Rs. bof and Rs. EOF then
Response. Write "no data yet. "
Else
Do while not Rs. EOF
%>
<Tr width = 100%>
<TD width = 50%> <% = RS ("field1") %> </TD> <TD width = 50%> <% = RS ("field2 ") %> </TD>
</Tr>
<%
Rs. movenext
Loop
End if
Rs. Close; Set rs = nothing
%>
</Table>

V. Summary

Here we just compiled a simple dynamic connection library file to connect to the database. Using the powerful component writing function of VB, we can also write more powerful and complete components to complete more practical tasks.

Keyword: how to compile ASP into DLL

This article mainly turns ASP code into a component. Developers not only speed up ASP, but also protect their own code.
Next, we will compile a very simple component, focusing on how to develop the DLL component, rather than its complex code! All of this depends on your future efforts.

Server Components

First, the server components should be different from the client components. the client components are transmitted over the network and work with HTML. and can only be used on IE. however, the server component runs on the server, and it performs various operations on the server. therefore, all browsers can enjoy it, relying on servers rather than browsers.

When IIS is requested to execute an ASP program, it first finds the code between the <%> labels in the ASP file, and execute it (it can also be code between <scriptrunat = Server> </SCRIPT> ). if this ASP program was previously called, it will return HTML code to the user using the compiled program in the memory. If not, it will re-compile. here, ASP is a little more speed advantage than CGI, Because CGI uses a thread for every request. in this way, the server resources are greatly consumed.

I don't want the program you write to run on IIS !?! Now you can do it! When using vb5 (of course it is VB6 now), you can create a dynamic1_libraries (DLL file), which can be run directly on IIS (if there is an ASP file for request ).

System and software requirements

You need a 32-bit operating system to run ASP. Of course, you also need to install IIS or PWS. Our program is developed in the Windows 95 + PWS + vb5 environment.

Let's get started.

Start your VB and select the ActiveX icon. This icon can be found in the new project! VB provides a default project name (project1) and Class Name (class1 ). we will change both names. before renaming, make sure that we have the microsoftactiveserverpagesobjectlibrary, which is very useful in our program. select "project" from the menu, and then select "Reference". The "Reference" window appears.
Select microsoftactiveserverpagesobjectlibrary.

Name projects and Classes

Now let's name project1 and class1 based on our hobbies! Naming them is also very important. We will use this project name and class name to create an instance for this component in the future! The following is a detailed description.

How can I change my name!
Change the project name to exmaple, and the class name is helloword.

How to use projects and Classes

Now we have our own project (example1) and Class Name (helloworld ). in the future, we will use their names in ASP code to reference this component. in ASP, We reference it as follows:

Setobjreference = server. Createobject ("projectname. classname ")

References to our project are:
Setobjreference = server. Createobject ("example1.helloworld ")
Now we can use objreference to call the function we created in the component. We will write a sayhello subroutine. The code we run is as follows:

<%
Setobjreference = server. Createobject ("example1.helloworld ")
Objreference. sayhello
%>

To use ASP in the helloword class, you must write an onstartpage
The sub-function is as follows:

Publicsubonstartpage (passedscriptingcontextasscriptingcontext)
Setmyscriptingcontext = passedscriptingcontext
Endsub

Now, no matter when the user accesses an ASP file with this component, IIS will send scriptingcontext to our object for use. this scriptingcontext includes all ASP methods and attributes. this allows us to access all ASP objects. see the following code:

Publicsubonstartpage (passedscriptingcontextasscriptingcontext)
Setmyscriptingcontext = passedscriptingcontext
Setmyapplication = myscriptingcontext. Application
Setmyrequest = myscriptingcontext. Request
Setmyresponse = myscriptingcontext. Response
Setmyserver = myscriptingcontext. Server
Setmysession = myscriptingcontext. Session
Endsub

In the future, we can use myapplication in VB to replace the application in ASP. Likewise, we can replace the request, server..., but we want to declare these variables before onstartpage:

Privatemyscriptingcontextasscriptingcontext
Privatemyapplicationasapplication
Privatemyrequestasrequest
Privatemyresponseasresponse
Privatemyserverasserver
Privatemysessionassession

Use ASP objects

Our variables can now be used like standard ASP objects! For example, we often use request. Form () in ASP to collect the data for submitting forms. Now we implement this function in our VB. The Code is as follows:

Implemented in ASP:
<%
Mytempvariable = request. Form ("username ")
Response. Write ("youentered" & mytempvariable & "asyourusername ")
%>

Implemented in VB:

Mytempvariable = myrequest. Form ("username ")
Myresponse. Write ("youentered" & mytempvariable & "asyourusername ")

By using myresponse instead of response, we can use all response methods. Of course, the name of myresponse can be obtained at will, and you can even get response.
Another thing we should note is that we have to write the onendpage subfunction in the class we created. This onstartpage is the opposite! Onstartpage is the object to be created, and onendpage is the object to be destroyed.

Publicsubonendpage ()
Setmyscriptingcontext = nothing
Setmyapplication = nothing
Setmyrequest = nothing
Setmyresponse = nothing
Setmyserver = nothing
Setmysession = nothing
Endsub

Sayhello Method

Let's create a sub-function to display "holleworld". This sayhello method is only a sub-function in the helloworld class. We will use the following method in ASP later.

<%
Setobjreference = server. Createobject ("example1.helloworld ")
Objreference. sayhello
%>

The sayhello program is very simple!

Publicsubsayhello ()
Myresponse. Write ("helloworld ")
Endsub

Now the compilation of a small component is complete, and the rest of the work is to compile this component. Save it in the "project" menu and get any name. Let's use exmaple1.vbp! Then select "makeexmaple1.dll" in the menu and compile it into a DLL file. A component is actually complete!

Note: after this component is compiled, you must first turn off your PWS and then compile this component. Otherwise, VB will tell you that some components are in use.

Use our own components in ASP.

When you have corrected the compilation error and successfully compiled the example1 project, now you have to come up with your favorite HTML editor to write down the following statement and save it as an ASP file.

<HTML>
<Head>
<Title> example1 </title>
</Head>

<Body>

<%
Setobjreference = server. Createobject ("example1.helloworld ")
Objreference. sayhello
%>

</Body>
</Html>

The result is displayed after running:

Helloworld

Register Components

Register to register the component. After registration, your component will appear in the Windows/system directory of Win95/Win98. The following is an example of registration:

Regsvr32.exec:/wwwroot/example1/example1.dll

In your system, vbwill automatically give you registration, so you rarely use regsvr32.exe

Here, we only wrote a very small component. You can write your own larger component, and you can also use many widgets in VB.

Appendix: Create a shortcut for registering DLL files and reregistering DLL files
Some programmers often need to register or unregister their own DLL files. Adding a shortcut will reduce their workload:

Windows Registry Editor Version 5.00

[Hkey_classes_root/dllfile/Shell]

[Hkey_classes_root/dllfile/Shell/register]

[Hkey_classes_root/dllfile/Shell/register/command]

@ = "Regsvr32% 1"

[Hkey_classes_root/dllfile/Shell/unregister]

"Command" = "regsvr32% 1/u"

[Hkey_classes_root/dllfile/Shell/unregister/command]

@ = "Regsvr32% 1/u"

When you need to register or unregister a DLL, you just need to right-click the DLL file!

How to register and deregister DLL files in the appendix:
A quick method for registering DLL and OCX
Sometimes when we want to reference a DLL or ocx in VB, the file is not registered. In this case, we can use the manual registration method, that is, use regsvr32.exe directly in the Command column. The procedure is as follows:

File registration: C:/Windows/system/regsvr32.exe C:/Windows/system/test. ocx
Cancel registration: C:/Windows/system/regsvr32.exe/u c:/Windows/system/test. ocx

These actions can also be directly written to the program and executed using shell, but what I want to say is not the method mentioned above!

1. Find C:/Windows/system/regsvr32.exe in resource manager and [copy] (right-click to select copy)
2. Move the directory to C:/Windows/sendto, and then click paste shortcut (right-click and choose paste shortcut)
3. Change the shortcut name to "register]
4. OK

Now, if you want to register an object, for example, C:/Windows/system/test. OCX, you just need to open the resource manager and find C:/Windows/system/test. OCX, right-click and select [transfer to] [register] to complete registration!

Note: regsvr32.exe can only register 32-bit files! If you use it to register a 16-bit file, an error message is generated.

Functions of some DLL files in the appendix:
1. easily fix ie browsers

Many Internet users often encounter this problem: IE cannot open a new window, and clicking a hyperlink with the mouse does not respond. At this time, reinstalling Ie can solve the problem. In fact, you don't have to worry about this. You can easily use the regsvr32 command.

In "Start> Run", type "regsvr32 actxprxy. DLL command and click "OK". A dialog box "dllregisterserver in actxprxy" appears. DLL succeeded, click "OK", and then type "regsvr32 shdocvw" in "Start> Run. DLL command, click OK. After the restart, ie has been easily fixed.

Ii. Solve the problem that Windows cannot be upgraded online

Windows has many vulnerabilities. You need to use the "Windows Update" Upgrade Program to perform online upgrades at intervals. However, "Windows Update" is often unavailable, we can use regsvr32 to solve this problem.

In "Start> Run", type "regsvr32 wupdinfo. DLL, click "OK", and then re-register the "Windows Update" component in the system. The problem has been resolved after the restart.

3. New methods to prevent web script viruses

The web script virus is embedded in the webpage, and the machine will be infected with this virus when surfing the Internet without knowing it. I believe that using anti-virus software alone cannot effectively prevent these script viruses. We must start with the virus transmission mechanism. The replication and propagation of the network script virus are inseparable from the FSO object (File System Object). Therefore, disabling the FSO object can effectively control the spread of the script virus. The procedure is simple:

In "Start> Run", type "regsvr32/u scrrun. dll" to disable the FSO object. If you need to use the FSO object, type the "regsvr32 scrrun. dll" command.

4. Uninstall the "chicken ribs" feature provided by Win XP

Windows XP is famous for its powerful functions, but some features are often "chicken ribs". For example, the zip and image preview features provided by Windows XP not only occupy system resources, features are far less powerful than third-party software. In fact, the regsvr32 command can easily uninstall these functions.

In "Start> Run", type "regsvr32/u zipfldr. DLL, click OK. The zip function is uninstalled after the successful uninstallation dialog box is displayed. To restore the zip function, type "regsvr32 zipfldr. DLL. Similarly, the image preview function is easy to uninstall. In "Start> Run", type "regsvr32/u thumbvw. DLL. To restore the function, you only need to type "regsvr32 thumbvw. DLL ".

5. Enable WMP player to support RM format

Many friends like to use Windows Media Player (WMP), but it does not support the RM format. Do you have to install other playing software? I have a solution.

Take Win XP as an example. First download a plug-in RM format and decompress the plug-in to obtain two folders: release (for Windows 9x) and release Unicode (for Windows 2000/XP ); set realmediasplitter under the release Unicode folder. copy the ax file to the "system drive letter/Windows/system32/" directory. In "Start> Run", type "regsvr32 realmediasplitter. ax. Click OK. Download the decoder, such as real alternative. After installation, you can use WMP to play the RM format audio and video files.

Appendix: Batch Processing of DLL file registration and anti-registration

DLL. bat
------------------------------
@ Regsvr32.exe admindll. dll

Un. bat
-------------------------------------
@ Regsvr32.exe/u admindll. dll

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.