Add variables

Feb 25, 2014 at 9:59 AM
Imports System.Xml
Imports Microsoft.ClearScript

Public Class WebForm1
Inherits System.Web.UI.Page

Private xml As XmlDocument = New XmlDocument
Private documentid As Integer = New Integer
Private cs_engine As Windows.JScriptEngine = New Windows.JScriptEngine

Public Sub Initialize()
    cs_engine.AddHostObject("xml", xml)
    cs_engine.AddHostObject("me", Me)

    Try
        cs_engine.Execute("xml.LoadXml('<sales id=""123""/>');")
        cs_engine.Execute("me.documentid = me.documentid + 1;")

    Catch e As Microsoft.ClearScript.ScriptEngineException
        Response.Write(e.GetBaseException)
    End Try

    If xml.InnerXml.ToString <> "" Then
        Response.Write(xml.SelectSingleNode("//sales").Attributes.GetNamedItem("id").InnerText & "<BR><BR>")
    Else
        Response.Write("No XML Detected!<br><br>")
    End If

    Response.Write(documentid)
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub
End Class

Loading an XML object or database connection in clearscript with AddObject method is no problem. But how can I add a integer or string variable so when I manipulate it in script I can refer it outside script in VB or vice versa ?
Coordinator
Feb 25, 2014 at 4:35 PM
Hi shripaldalal,

In your code above the script can't access documentid because it's a private field. To fix the problem, either make it public or expose Me like this:
cs_engine.AddRestrictedHostObject("me", HostItemFlags.PrivateAccess, Me)
Cheers!
Marked as answer by shripaldalal on 2/25/2014 at 11:22 AM
Feb 25, 2014 at 7:25 PM
Hey,

Thanks a ton for the quick reply. Worked like a charm. Though I did this, so all the objects of the class get added in script global. Which is exactly what I need. As I mentioned in the other thread, I will be having one web class = 1 script engine! If you feel this is wrong please let me know or I will go ahead using this.

Imports System.Xml
Imports Microsoft.ClearScript

Public Class WebForm1
Inherits System.Web.UI.Page

Public xml As XmlDocument = New XmlDocument
Public documentid As Integer = New Integer
Public cs_engine As Windows.JScriptEngine = New Windows.JScriptEngine

Public Sub Initialize()
documentid = 1
cs_engine.AddRestrictedHostObject("me", HostItemFlags.GlobalMembers, Me)

Try
    cs_engine.Execute("xml.LoadXml('<sales id=""123""/>');")
    cs_engine.Execute("documentid = documentid + 1;")

Catch e As Microsoft.ClearScript.ScriptEngineException
    Response.Write(e.GetBaseException)
End Try

If xml.InnerXml.ToString <> "" Then
    Response.Write(xml.SelectSingleNode("//sales").Attributes.GetNamedItem("id").InnerText & "<BR><BR>")
Else
    Response.Write("No XML Detected!<br><br>")
End If

Response.Write(documentid)
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub
End Class