Visual Studio for Application 內幕之三
vsa的一個重要功能就是HostObject,這也是其上代vba sdk,包括Microsoft Script Control或是其他第三方vb語言實現(winwrap basic,basicscript,sbl等的重要功能)
hostObject是這樣的一個對象,在script中無需聲明就可以使用,比方說在excel中你可以使用application,在asp中你可以使用Server,Session等,包括在ActiveContent的模板中你可以使用Document,Site,Category等對象 :),都是類似的應用。
為了便於大家理解,我們建立一個Document類
Public Class Document
Private _title As String
Private _submitDate As Date
Private _url As String
Private _content As String
Public Sub New()
End Sub
Public Sub New(ByVal title As String, ByVal content As String, ByVal url As String, ByVal submitDate As Date)
Me.Title = title
Me.Content = content
Me.Url = url
Me.SubmitDate = submitDate
End Sub
Public Property Content() As String
Get
Return _content
End Get
Set(ByVal Value As String)
_content = Value
End Set
End Property
Public Property Title() As String
Get
Return _title
End Get
Set(ByVal Value As String)
_title = Value
End Set
End Property
Public Property SubmitDate() As Date
Get
Return _submitDate
End Get
Set(ByVal Value As Date)
_submitDate = Value
End Set
End Property
Public Property Url() As String
Get
Return _url
End Get
Set(ByVal Value As String)
_url = Value
End Set
End Property
End Class
編譯該類
vbc /out:bin\document.dll /t:library
在項目中引用該document.dll
我們依舊要藉助MyVsaSite 類
我們在其中聲明一個類級變數
private doc as Document
並在new 過程中對其進行初始化
Public Sub New()
doc = New Document("vsa 內幕三", "vsa 內幕三", "http://www.soho-works.net/blog/275.asp", Now)
End Sub
我們修改一下Script ,使其使用這個Document對象
class TestClass
public shared sub Hello(byval name as string)
System.Windows.Forms.MessageBox.Show(ThisDocument.Title)
end sub
End Class
如何調用?
1、建立一個IVsaReferenceItem執行個體
Dim ReferenceItem As Microsoft.Vsa.IVsaReferenceItem
ReferenceItem = m_VsaEngine.Items.CreateItem("Document", Microsoft.Vsa.VsaItemType.Reference, Microsoft.Vsa.VsaItemFlag.None)
ReferenceItem.AssemblyName = "C:\Documents and Settings\Administrator\My Documents\Visual Studio Projects\WindowsApplication2\WindowsApplication2\bin\Document.Dll"
2、建立一個IVsaGlobalItem執行個體
Dim GlobalItem As Microsoft.Vsa.IVsaGlobalItem
GlobalItem = m_VsaEngine.Items.CreateItem("ThisDocument", Microsoft.Vsa.VsaItemType.AppGlobal, Microsoft.Vsa.VsaItemFlag.None)
GlobalItem.TypeString = "Document"
注意:TypeString 為Document
2、實現MyVsaSite的GetGlobalInstance
Public Function GetGlobalInstance(ByVal name As String) As Object Implements Microsoft.Vsa.IVsaSite.GetGlobalInstance
Select Case name.ToLower
Case "thisdocument"
Return doc
End Select
End Function
3、調用方法沒有改變
Dim args() As Object = New Object() {"jjx"}
Invoke("TestClass.Hello", args)