Using VB to generate DLL encapsulation ASP code An example: Connect Access database, etc.

Source: Internet
Author: User
Tags define command line file system functions iis connect variables zip
access| Encapsulation | data | Database encapsulation as a DLL can bring many benefits, including only property rights protection, as well as efficiency and security performance improvements. The encapsulated DLL file in this example hides the actual path to the Access database.

VB-generated DLLs encapsulate ASP code to connect to the database (Access).

This article uses one of the simplest examples of connecting an Access database to illustrate how to encapsulate ASP code as a DLL file.

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

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=;p wd=123;dbq=" & Server.MapPath ("db.asp")

We will encapsulate the following parts
"Driver={microsoft Access Driver (*.mdb)};uid=;p wd=123;dbq=" & Server.MapPath ("db.asp")

To analyze the contents of this section to be encapsulated,
The first half of it is a string:
"Driver={microsoft Access Driver (*.mdb)};uid=;p wd=123;dbq="
Another string that connects the second half of the upper part with &.
Another string in the second part is the return value of the Server.MapPath object function.

Here's how to start the encapsulation process.
First of all
Create a new VB under the ActiveX DLL project, the project name Project1 changed into Condbdll
The name of the method Class1 is changed to CS
The project name and method name will be used when calling this DLL, you can define your own naming rules, but please be careful to use them well.
The code section of this DLL 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 necessary to simplify the original object and handle it in two basic functions.

Public Function Connectdb () as Variant
Connectdb = "Driver={microsoft Access driver (*.mdb)};uid=;p wd=123;dbq="
End Function
' The above function is to handle the first half of the string, and directly return the contents of the string

' also define the following function to handle the second half of the content
Public Function DBPath () as Variant
DBPath = Sr. MapPath ("db.asp")
End Function
' Note that the SR is used and do not use it as a server

To the critical step, add the Microsoft Active Server Pages ObjectContext Object Library to this project Reference
Add a method, select "Project"-> "Reference" in the menu, and select it in the Open dialog box.
By the way, also select the "Microsoft ActiveX Data Objects 2.6 Library"

Once we've done that, we can compile the build DLL, (don't forget the name of the previous project and method)

Prepare database file Db.asp (by db.mdb change suffix, password 123)

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

Since you created the DLL yourself, you must register to use it when you copy it to the appropriate directory.
Registered method, executing in run:
Regsvr32.exe Dllname.dll

The method for canceling the registration of this DLL is: regsvr32.exe/u Dllname.dll

After registering, our work is basically done, now we can use this encapsulation method to connect with the targeted database.

But one thing that needs special attention is:
Because
Dim condb
Set Condb=server.createobject ("Condbdll.conn")
' Condb is the DLL object created
This is the object created in ASP, including Proconn, so we remember to release the two objects in any other ASP file that uses the (referenced) proconn.asp!
Proconn.close
Set proconn=nothing
Set condb=nothing
Otherwise the system becomes more and more overwhelmed by the fact that the object is not released.

For a method that encapsulates ASP code to connect to an Access database, I want to fully apply the connection method for other databases.


For example, the following examples of encapsulation are:

First you 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

In order to use an ASP's built-in object in the Wenconnection class, you must write a onstartpage child function in this class. That's because whenever a user accesses an ASP file with this component, IIS sends the ScriptingContext to our object and invites us to use it. This scriptingcontext includes all ASP methods and attributes, which gives us the ability 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

Now that we use the OnStartPage function to create the object, we use the OnEndPage function to release the object:

Public Sub OnEndPage ()
Set Wenscriptingcontext = Nothing
Set wenapplication = Nothing
Set wenrequest = Nothing
Set Wenresponse = Nothing
Set Wenserver = Nothing
Set wensession = Nothing
End Sub

Next, define two functions 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 datasourceconnection () as Variant
Datasourceconnection = "Driver={sql server};server=servername;uid=sa;pwd=;d atabase=databasename"
End Function

Third, save the project name is Wenadodb.vbp and save class name is Wenconnection.cls, then click "File"-> "Generate WenADODB.DLL" compile into Dynamic Connection library file. VB in the compilation of dynamic connection library files are also registered in the registration table, if you want to register the component on another machine, please use the following instructions to register or reverse registration:

Regsvr32 x:\ path \wenadodb.dll x:\ path \ disk character and path for WenADODB.dll file

regsvr32/u x:\ Path \wenadodb.dll parameter U for anti-registration

The example of invoking the WenADODB.dll component in the ASP file.

<%

Set conn=server.createobject ("wenadodb.wenconnection") ' invokes the component to create an object instance
Objconn=conn.datasourceconnection ()
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 "There is no data for the moment. "
Else
Do as not rs.eof
%>
<tr width=100%>
&LT;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

We have only written a simple link database to connect the library file, the use of the powerful components of VB writing function can also write more powerful and complete components, to complete more practical tasks

Keywords how to write an ASP as a DLL

This article is mainly the ASP code into components, the developer is not only to speed up the ASP, but also to protect their own code.
Next, we'll write a very simple component, focusing on knowing how to develop DLL components, not their complex code! It all depends on your own efforts in the future.

Server-side components

First, server-side components are different from the client's components. The client's components are transmitted over the network, depending on the HTML. And can only be useful on IE. but the server-side component is run on the server side, and it performs various operations on the server. So, all browsers are available, It relies on the server rather than the browser.

When IIS is requested to execute an ASP program, it first finds the code between the 〈%%> tags in the ASP file, and executes it (or it can be code between 〈scriptrunat=server>〈/script>). If the ASP program was previously invoked, it would use an in-memory compiled program to return the HTML code to the user, and if not, it would recompile. Here ASP has a little more speed advantage than CGI, Because CGI is a thread used for every request. This greatly consumes the resources of the server.

If you don't want to write the program yourself, you can run it in IIS!?! You can do it now! With VB5 (now VB6, of course) you'll be able to build dynamiclinkedlibraries (DLL file), which can be run directly on IIS (if an ASP file is requested).

Requirements for systems and software

You need a 32-bit operating system to run the ASP. Of course you also have to install IIS or PWS. Our following program is developed under the WINDOWS95+PWS+VB5 environment.

Here we go

Start your VB, select the ActiveX icon. This icon can be found in the new project! VB will provide a default project name (Project1) and class name (Class1). We'll get rid of all two names. Before renaming, please confirm that we have microsoftactiveserverpagesobjectlibrary, It's very useful in our program. Select project from the menu, and then select References in which the References window appears
Select Microsoftactiveserverpagesobjectlibrary from.

Naming Projects and classes

Now we come to the name of Project1 and Class1 according to their hobbies! It is also important to name them, and we will use this project name and class name to create an instance of this component!

How to change my name, I don't want to say more!
Our project name is changed to Exmaple, class name is Helloword

How to use Engineering and class

Now we have our own engineering (EXAMPLE1) and class name (HelloWorld). We'll use their names in the ASP code to refer to this component in the future. In the ASP we are quoting as follows:

Setobjreference=server.createobject ("Projectname.classname")

The reference to our project is:
Setobjreference=server.createobject ("Example1.helloworld")
Now we can use Objreference to invoke the function we created in the component, subroutine. Below we will write a SayHello subroutine, we execute it with the following code:


〈%
Setobjreference=server.createobject ("Example1.helloworld")
Objreference.sayhello
%>


In order to use the ASP method in the Helloword class, you must write a onstartpage in this class
Child functions, as follows:


Publicsubonstartpage (Passedscriptingcontextasscriptingcontext)
Setmyscriptingcontext=passedscriptingcontext
Endsub



Now, whenever a user accesses an ASP file with this component, IIS sends ScriptingContext to our object for us to use. This scriptingcontext includes all ASP methods and properties. Implementation, This gives us the ability to access all of the ASP's objects. Look at the following code:


Publicsubonstartpage (Passedscriptingcontextasscriptingcontext)
Setmyscriptingcontext=passedscriptingcontext
Setmyapplication=myscriptingcontext.application
Setmyrequest=myscriptingcontext.request
Setmyresponse=myscriptingcontext.response
Setmyserver=myscriptingcontext.server
Setmysession=myscriptingcontext.session
Endsub


We can use MyApplication in VB to replace the application in ASP, the same can replace request,server ... but we are here to declare these variables before OnStartPage:


Privatemyscriptingcontextasscriptingcontext
Privatemyapplicationasapplication
Privatemyrequestasrequest
Privatemyresponseasresponse
Privatemyserverasserver
Privatemysessionassession



Using ASP's Objects

Our variables can now be used like standard ASP objects! For example, we often use Request.Form () in ASP to collect 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 are able to use all response methods, and of course, Myresponse is a name that can be easily fetched and you can even take response.
Another thing we should be aware of is that we have to write the OnEndPage child function in our established class, and this onstartpage is the opposite! OnStartPage is the object of creation, OnEndPage is the object of extinction.



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



SayHello method

Let's create a child function to display "Holleworld". This SayHello method is just helloworld a child function in this class, and we'll use the following display in the ASP


〈%
Setobjreference=server.createobject ("Example1.helloworld")
Objreference.sayhello
%>



SayHello's program, very simple!

Publicsubsayhello ()
Myresponse.write ("HelloWorld")
Endsub



Now a small component to write, the rest of the work is to compile this component, in the "Project" menu to save it, take whatever name can be, we use EXMAPLE1.VBP Bar! Then use the menu to select "Makeexmaple1.dll", Compile it into a DLL file. A component is really done!


Note that this component is compiled so you have to turn off your PWS before compiling this component. Otherwise VB will tell you some components in use.

Use our own components in the ASP.

When you have corrected the error in the compilation, successfully compiled the EXAMPLE1 project, now you have to take out your favorite HTML editor to write down the following statement, save as an ASP file.


〈html>
〈head>
〈title>example1〈/title>
〈/head>

〈body>

〈%
Setobjreference=server.createobject ("Example1.helloworld")
Objreference.sayhello
%>

〈/body>
〈/html>

You can see the results after running:

HelloWorld

Registering components

If you want to share your components with your friends and neighbors, then you have to register your components on your system. We typically use Regsvr32.exe to register components. Your component will appear in Win95/win98 after registration windows/ System directory. Here is an example of a registration:

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


In your system, VB will automatically register you, so you rarely use the Regsvr32.exe

Here just write a very small component, you can write your own larger components, but also can use a lot of VB control.


Appendix: A shortcut to establish a registration DLL and a reverse registration DLL file
Some programmers often want to register or reverse their own written DLL file, add 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 we need to register or reverse the registration DLL, just press the right mouse button on the DLL file!



Appendix registers and cancels the DLL file method:
A fast registration DLL and OCX method
Sometimes we in VB to reference a DLL or OCX, there will be unregistered messages, then, we can use the manual registration method, that is, directly in the command line using Regsvr32.exe to do, the practice 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 written directly into the program, using the Shell to execute, but what I want to say now is not the method mentioned above!



1, find C:\Windows\System\Regsvr32.exe in the Explorer and "copy" (Press the right mouse button selected copy)
2, after the directory moved to the C:\Windows\SendTo, the implementation of the "Paste Shortcut" (Click the right mouse button selected to paste the shortcut)
3. Change the name of the shortcut to "REGISTER"
4, OK

Now, if you want to register for a file, for example: C:\Windows\System\Test.ocx, you just open the Explorer, find C:\Windows\System\Test.ocx, right-click the "Transfer to" register Can complete the registration action!

Note: There is a place to note that Regsvr32.exe can only register 32-bit files! If you want to use it to register 16-bit files, there will be an error message generated.


Appendix the features of some DLL files:
First, easy to repair IE browser

Many friends who often surf the internet have had such an encounter: IE can't open a new window, click the hyperlink with the mouse and there is no response. At this point the reload IE can generally solve the problem. In fact, do not have such trouble, using the Regsvr32 command can be easily handled.

Type the "regsvr32 actxprxy.dll" command in "Start → run" and click "OK" to pop up a message dialog box "DllRegisterServer in Actxprxy.dll succeeded" and click "OK" , and then type the regsvr32 shdocvw.dll command in start → run, and click OK. IE has been easily repaired after reboot.

Solve the problem that Windows cannot be upgraded online

Windows Update has a lot of vulnerabilities and needs to be upgraded online every once in a while, but "Windows Updates" is often unusable, so we can use Regsvr32 to solve the problem.

Type "regsvr32 wupdinfo.dll" in Start → run and click OK to re-register the Windows Update component in the system, and the problem has been resolved after reboot.

III. Prevention of network scripting virus

The network script virus is embedded in the Web page, when the Internet unknowingly in the machine will infect the virus. The author thinks that only using anti-virus software can not effectively prevent these script viruses, we must start from the mechanism of virus transmission. Network script virus replication, transmission are inseparable from the FSO object (File system object, filesystem objects), so disabling the FSO object can effectively control the spread of script viruses. The method of operation is simple:

You can disable the FSO object by typing "regsvr32/u scrrun.dll" in Start → run, and if you need to use the FSO object, type the regsvr32 scrrun.dll command.

Four, uninstall the win XP from the "Chicken" function

Win XP is famous for its powerful features, but some features are often "chicken" sense, such as the Win XP with the zip function and picture preview function, not only occupy the system resources, function is far less powerful than Third-party software. In fact, using the Regsvr32 command makes it easy to uninstall these features.

Type "regsvr32/u Zipfldr.dll" in "Start → run", click "OK" button, eject the Uninstall Success message box to complete the zip function uninstall; To restore the zip function, type "regsvr32 zipfldr.dll". Also, uninstalling the picture preview function is simple, type "regsvr32/u Thumbvw.dll" in "Start → run", and if you want to restore the feature, just type "regsvr32 thumbvw.dll".

V. Let WMP player support RM format

Many friends like to use Windows Media Player (hereinafter referred to as WMP) player, but it does not support RM format, do I have to install other playback software? I have a way.

Take win XP for example, first download an RM format plug-in, extract two folders: Release (for Windows 9x) and release Unicode (for Windows 2000/XP); Copy the Realmediasplitter.ax file under the Unicode folder to the system drive \windows\system32\ directory, type "regsvr32 realmediasplitter.ax" in Start → run, and click Ok. Then download the decoder, such as real alternative, after installation can play the RM format of the audio and video files WMP.

Appendix: Batch processing of registration and anti-registration DLL files



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.