如何制作无状态的ASP组件
如何制作无状态的ASP组件,如何制作无状态的ASP组件
很幸运有个好消息。我们都知道可持续性的整个前提是能够将变量恢复到这样的状态,以至于组件知道在上次的例示中它在哪。这有助于组件现在去做它假定要做的。这个方案的一个典型例子是网页上资料的翻页。当用户点击Page Down时,我们需要知道我们在前一页的位置。 不把变量保存在内存中(如会话变量),如果我们能将它们保存在文件中,等以后需要时检索不是会很好吗?用基础的数据形式(字符串与数字)保存数据很容易。用对象和数组会怎样呢?对象和数组本质上是存储器中的二进制数据流。如果我们能读这个数据我们就能将它写进文件以便以后的检索。关于对象有个好注意。尽管数组的情况不同。首先你不能用数组做组件的属性(VB6.0)。你可以用他们做变量,但以后你会碰到路障。幸运地是我们为这种情况发现了一个工作区。
你可以将所有或部分属性保存在一个PropertyBag对象中。PropertyBag对象控制在一个对象调用过程中可以保存和恢复的信息。PropertyBag对象的内容(Content)属性提供你任何存在组中的二进制数据流。由你来将这些二进制数据流写进文件中以便日后的检索。
实例:
比如你有一个类MyComp.clsMyDept,它有两个属性MyDepartment$ 和 MyEmployees (一个ADO记录集对象)。
以下是这个类模块的代码:
Option Explicit
Option Compare Text
Public MyDepartment As String
Public MyEmployees As ADODB.Recordset
Dim objBag As New PropertyBag
Private Sub Class_InitProperties()
Set MyEmployees = New ADODB.Recordset
MyEmployees.Fields.Append "EmpName", adVarChar, 30
MyEmployees.Fields.Append "EmpSal", adCurrency
MyEmployees.Open
End Sub
Public Sub SaveMyProperties()
Dim intFile%, bytRec() As Byte
objBag.WriteProperty "MyDepartment", MyDepartment
objBag.WriteProperty "MyEmployees", MyEmployees
' Save this data in a file for later retrieval
intFile = FreeFile
If Dir("C:MyData.txt", vbNormal) = "" Then
Else
Kill "C:MyData.txt"
End If
Open "C:MyData.txt" For Binary Access Write As #intFile
bytRec = objBag.Contents
Put #intFile, , bytRec
Close #intFile
End Sub
Public Sub RestoreMyProperties()
Dim intFile%, bytRec() As Byte
' Read the saved data from the file.
ReDim bytRec(FileLen("C:MyData.txt"))
intFile = FreeFile
Open "C:MyData.txt" For Binary Access Read As #intFile
Get #intFile, , bytRec
objBag.Contents = bytRec
Close #intFile
' PropertBag restored. Lets restore the properties now.
MyDepartment = objBag.ReadProperty("MyDepartment")
Set MyEmployees = objBag.ReadProperty("MyEmployees")
End Sub
在客户应用中保存属性
Private Sub Command1_Click()
Dim objDept As New MyComp.clsMyDept
objDept.MyDepartment = "Research"
' Add one employee
objDept.MyEmployees.AddNew
objDept.MyEmployees!EmpName = "Harry"
objDept.MyEmployees!EmpSal = 2500
objDept.MyEmployees.Update
' Add second employee
objDept.MyEmployees.AddNew
objDept.MyEmployees!EmpName = "Potter"
objDept.MyEmployees!EmpSal = 3000
objDept.MyEmployees.Update
' Save the properties by calling the method from our component
objDept.SaveMyProperties
Set objDept = Nothing
End Sub
取回保存的属性
Private Sub Command2_Click()
Dim objDept As New MyComp.clsMyDept
' Restore properties by calling the method from our component
objDept.RestoreMyProperties
' Lets see what is restored
Debug.Print objDept.MyDepartment 'Will print Research
objDept.MyEmployees.MoveFirst
Debug.Print "" & objDept.MyEmployees!EmpName 'Will print Harry
objDept.MyEmployees.MoveNext
Debug.Print "" & objDept.MyEmployees!EmpName 'Will print Potter
Set objDept = Nothing
End Sub