vb.net CefSharp.Windows document.getElementById - cefsharp

We used webbrowser control to login website in VB.NET, now we are going to us CefSharp.
We have made a simple test form. Clicking on the button sets the "toegangscode". It works, but when I go to next field wachtwoord (password) and type 1 first character the "toegangscode" field will be made empty. What I am doing wrong ?
Public Class Form1
Public WithEvents browser As ChromiumWebBrowser
Public Sub New()
' This call is required by the designer.
InitializeComponent()
Dim settings As New CefSharp.WinForms.CefSettings()
CefSharp.Cef.Initialize(settings)
browser = New CefSharp.WinForms.ChromiumWebBrowser("https://diensten.kvk.nl/inloggen.html") With {
.Dock = DockStyle.Fill}
Panel1.Controls.Add(browser)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim jsScript1 = <js><![CDATA[document.getElementById("username").focus();]]></js>.Value
browser.ExecuteScriptAsync(jsScript1)
Dim jsScript2 As String = <js><![CDATA[document.getElementById("username").value = "xxxxxx";]]></js>.Value
browser.ExecuteScriptAsync(jsScript2)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim bCanExecuteJavascriptInMainFrame As Boolean = browser.CanExecuteJavascriptInMainFrame
Dim bIsBrowserInitialized As Boolean = browser.IsBrowserInitialized
If bIsBrowserInitialized Then
browser.ShowDevTools()
End If
End Sub
End Class

Related

Call a function from the Login Control in vb.net

Trying to call a function in code behind but not working - one suggestion was to use the OnAuthenticate instead of the OnClick however this requires a rewrite of the entire authentication process.
<asp:Login ID="Login1" runat="server" OnClick="MyButton" DestinationPageUrl="~/Receipt.aspx"
UserNameLabelText="User Name (From: mysite.com):"
PasswordRecoveryText="Forgot User Name or Password?"
PasswordRecoveryUrl="~/GetPassword.aspx">
</asp:Login>
vb code:
Protected Sub MyButton(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username As String = Login1.UserName
Dim currentDateTime As DateTime = DateTime.Now.AddHours(3)
Dim filepath As String = Server.MapPath("~") + "\debug.txt"
Using writer As StreamWriter = File.AppendText(filepath)
writer.WriteLine(username)
writer.WriteLine(currentDateTime)
writer.WriteLine("")
End Using
End Sub
Revised Code:
Imports System.IO
Imports System.Data
Partial Class Login
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xUserName As String = User.Identity.Name()
'UpdateLastLoginDate(xUserName)
End Sub
Protected Sub MyButton(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username As String = Login1.UserName
Dim pw As String = Login1.Password
Dim currentDateTime As DateTime = DateTime.Now.AddHours(3)
Dim filepath As String = Server.MapPath("~") + "\debug.txt"
Using writer As StreamWriter = File.AppendText(filepath)
writer.WriteLine(username)
writer.WriteLine(pw)
writer.WriteLine(currentDateTime)
writer.WriteLine("REMOTE_ADDR: " + Request.Servervariables("REMOTE_ADDR"))
writer.WriteLine("USER_AGENT: " + Request.Servervariables("HTTP_USER_AGENT"))
writer.WriteLine("LOCAL_ADDR: " + Request.Servervariables("LOCAL_ADDR"))
writer.WriteLine("LOGON_USER: " + Request.Servervariables("LOGON_USER"))
'writer.WriteLine(Request.Servervariables("ALL_HTTP"))
writer.WriteLine("")
End Using
End Sub
Protected Sub Page_PreInit(sender As Object, e As EventArgs)
WireLoginControlButtonClickEvent(Login1)
End Sub
Private Sub WireLoginControlButtonClickEvent(parent As Control)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is Button Then
AddHandler DirectCast(ctrl, Button).Click, Function() (MyFunction())
ElseIf ctrl.HasControls() Then
WireLoginControlButtonClickEvent(ctrl)
End If
Next
End Sub
Private Function MyFunction() As String
Response.Write("Function Called")
Return Nothing
End Function
End Class
Give this a try:
Protected Sub Page_PreInit(sender As Object, e As EventArgs)
WireLoginControlButtonClickEvent(Login1)
End Sub
Private Sub WireLoginControlButtonClickEvent(parent As Control)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is Button Then
AddHandler DirectCast(ctrl, Button).Click, AddressOf MyFunction
ElseIf ctrl.HasControls() Then
WireLoginControlButtonClickEvent(ctrl)
End If
Next
End Sub
Private Sub MyFunction(sender As Object, e As EventArgs)
Response.Write("Function Called")
End Sub

asp.net server control not saving state properly

I am trying to create an ASP.net server control that uses controls from the AjaxControlToolkit. Essentially, the control is a dropdownlist and a button. When the user clicks the button, a modal dialog (modalPopupExtender) opens. The dialog has a checkboxlist with a list of options to chose from. When the user selects their choice(s) and hits the Ok button, in the dialog, the dialog closes and the selected choices should get added to the dropdownlist. What is happening, though, is that when the user makes their selection and hits OK only the last item in the Checkboxlist gets added. I think it may have something to do with the inherited functions I override. Can anyone tell me what I may be doing wrong? Here is the relevant code:
<DefaultProperty("Text"), ToolboxData("<{0}:myServerControl runat=server>
</{0}:myServerControl >")> _
Public Class myServerControl
Inherits CompositeControl
Implements INamingContainer, IPostBackEventHandler
Private myDropDownListAs New DropDownList
Private addPlant As New Button
Private _updatePanel As UpdatePanel
Private _modalExtenderOne As AjaxControlToolkit.ModalPopupExtender
Private lblWarning As Label
Private cb1 As New CheckBoxList
Private btnSavePlants As New Button
Private btnCancel As New Button
Protected Overrides Function SaveViewState() As Object
Return New Pair(MyBase.SaveViewState(), Nothing)
End Function
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(CType(savedState, Pair).First)
EnsureChildControls()
End Sub
Protected Overrides Sub CreateChildControls()
createDynamicControls()
MyBase.CreateChildControls()
End Sub
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
End Sub
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
End Sub
Private Sub createDynamicControls()
Controls.Clear()
AddHandler btnSavePlants.Click, AddressOf saveItems_Click
_updatePanel = New UpdatePanel
Dim myTable As New Table
myTable = buildControl() ' a funciton that returns a built table
Dim myPanel As New Panel
myPanel = buildDialog() 'a function taht returns a build modal dialog
_updatePanel.ContentTemplateContainer.Controls.Add(myTable)
_updatePanel.ContentTemplateContainer.Controls.Add(myPanel)
Me.Controls.Add(_updatePanel)
End Sub
Protected Sub saveItems_Click(ByVal sender As Object, ByVal e As EventArgs)
Me.myDropDownList.Items.Clear()
Try
For Each i As ListItem In Me.cb1.Items
If (i.Selected = True) Then
Dim newLi As New ListItem
With newLi
.Selected = False
.Text = i.Text
.Value = i.Value
End With
Me.myDropDownList.Items.Add(newLi)
Else
End If
Next
Catch ex As Exception
End Try
End Sub
Public Sub bindSelections(ByVal myList As List(Of myObject))
For Each p As myObjectIn myList
Dim newLI As New ListItem
newLI.Value = p.EquipmentPK
newLI.Text = p.EquipmentID
Me.cb1.Items.Add(newLI)
Next
End Sub
Public Sub RaisePostBackEvent(ByVal eventArgument As String) Implements System.Web.UI.IPostBackEventHandler.RaisePostBackEvent
End Sub
End Class

Getting an ASP.NET error System.NullReferenceException: Object reference not set to an instance of an object?

I am completely new to ASP.NET and VB as well as C#. I am trying to add customers to a contact list out of a DB. Then the list can be referenced to call them up.
But when I try to run it I get System.NullReferenceException: Object reference not set to an instance of an object. In line 19.
Here is my code:
Page 1 is default page...it connects to the database and grabs the contact information and allows me to select the current contact and add them to a listbox on a separate page:
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private SelectedCustomer As Customer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
If Not IsPostBack Then
ddlCustomers.DataBind()
End If
SelectedCustomer = Me.GetSelectedCustomer
Me.DisplayCustomer()
End Sub
Private Function GetSelectedCustomer() As Customer
Dim dvTable As dataview = CType(AccessDataSource1.Select( _
DataSourceSelectArguments.Empty), dataview)
dvTable.RowFilter = "CustomerID = " & ddlCustomers.SelectedValue
Dim drvRow As DataRowView = dvTable(0)
Dim customer As New Customer
customer.CustomerID = CInt(drvRow("CustomerID"))
customer.Name = drvRow("Name").ToString
customer.Address = drvRow("Address").ToString
customer.City = drvRow("City").ToString
customer.State = drvRow("State").ToString
customer.ZipCode = drvRow("ZipCode").ToString
customer.Phone = drvRow("Phone").ToString
customer.Email = drvRow("Email").ToString
Return customer
End Function
Private Sub DisplayCustomer()
lblAddress.Text = SelectedCustomer.Address
lblCityStateZip.Text = SelectedCustomer.City & ", " _
& SelectedCustomer.State & " " _
& SelectedCustomer.ZipCode
lblPhone.Text = SelectedCustomer.Phone
lblEmail.Text = SelectedCustomer.Email
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If Page.IsValid Then
Dim customerItem As New Customer
customerItem.Name = SelectedCustomer.ToString
Me.AddToCustomer(customerItem)
Response.Redirect("CustomerList.aspx")
End If
End Sub
Private Sub AddToCustomer(ByVal customerItem As Customer)
Dim customer As SortedList = Me.GetCustomer
Dim customerID As String = SelectedCustomer.CustomerID
If customer.ContainsKey(customerID) Then
customerItem = CType(customer(customerID), Customer)
Else
customer.Add(customerID, customerItem)
End If
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
End Class
The next bit of code allows me to add the contact to a list box:
Partial Class Default2
Inherits System.Web.UI.Page
Private Customer As SortedList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Customer = Me.GetCustomer
If Not IsPostBack Then Me.DisplayCustomer()
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
Private Sub DisplayCustomer()
lstCustomer.Items.Clear()
Dim customerItem As Customer
For Each customerEntry As DictionaryEntry In Customer
customerItem = CType(customerEntry.Value, Customer)
lstCustomer.Items.Add(customerItem.Name)
Next
End Sub
Protected Sub lstCustomer_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstCustomer.SelectedIndexChanged
End Sub
End Class
The error occurs on line 19 (For Each customerEntry As DictionaryEntry In Customer) in the second set of code from the default2 class. Any ideas? I am completely new to ASP.NET just trying to learn. I more at home on PHP, Java, and Actionscript unfortunately.
I think the problem is in this function
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
You initialise Customer here but then pull out of Session("Cart")
I think what you meant to do is
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
Now customer should always be initialised whereas before it might not have been which would cause the NullReferenceException that you are getting.

ASP NET Stop other sub proc from executing after error

I am having a problem with my try catch block runs in the error:
database is not available
My problem is the try catch runs and catches the error, but it will not redirect to my error page. The code continues to execute the other subs. I have tried adding: exit, return, response.end. None of them worked. Thank you for your help.
Imports System.Data
Imports EUC
Imports System.Threading
Imports System.Data.SqlClient
Partial Class mpMain
Inherits System.Web.UI.MasterPage
Dim strSQL As String
Dim objData As clsDataAccess = New clsDataAccess()
Dim ds As New D
ataSet
Dim t1 As DataTable
Dim intSecurityLevel As String = 0
Dim strUser As String = UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4))
Protected Sub ExpandNode(ByVal NodeName As String, ByVal PageName As String)
'More Code
End Sub
Protected Sub ExpandNode2(ByVal NodeNameMain As String, ByVal NodeName As String, ByVal PageName As String)
'More Code
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (IsPostBack) Then
Try
strSQL = "Select SecurityLevel from tblSecurity where SFID = #SFID order by SecurityLevel"
Dim MyParameters1 As SqlParameter() = { _
New SqlParameter("#SFID", SqlDbType.VarChar) _
}
MyParameters1(0).Value = UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4))
ds = objData.SQLExecuteDataset(strSQL, CommandType.Text, MyParameters1)
t1 = ds.Tables(0)
Catch ex As Exception
Dim sendError As New clsExceptionMessage
sendError.sendMessage(ex.Message, Request.Path, strSQL)
Response.Redirect("ErrorMessage.aspx", False)
End Try
End If
End Sub
Protected Sub TreeView1_TreeNodeDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles TreeView1.TreeNodeDataBound
'More Code
End Sub
Protected Sub TreeView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.DataBound
'More Code
End Sub
End Class
Firstly I would catch SQLException, you rarely want to catch a general exception.
In the catch block, set a boolean parameter such as
hasError = True
and once outside the try..catch block check for this to be true and redirect from there.

Can I add buttons with events to a custom treeNode?

I extended treeview, treenode, and nodetype so I could have custom nodes. Certain nodes have image buttons on them allowing them to add a child node or delete the node. I can't handle any of the events from my buttons.
Public Class ContentTreeView
Inherits TreeView
Public Event OnAddChild(ByVal sender As Object, ByVal e As EventArgs)
Public Event OnDelete(ByVal sender As Object, ByVal e As EventArgs)
Private _AddImageURL As String = String.Empty
Private _DeleteImageURL As String = String.Empty
Public Property AddImageURL() As String
Get
Return _AddImageURL
End Get
Set(ByVal value As String)
_AddImageURL = value
End Set
End Property
Public Property DeleteImageURL() As String
Get
Return _DeleteImageURL
End Get
Set(ByVal value As String)
_DeleteImageURL = value
End Set
End Property
Protected Overrides Function CreateNode() As TreeNode
Dim retval As ContentTreeNode = New ContentTreeNode(AddImageURL, DeleteImageURL)
AddHandler retval.OnAddChild, AddressOf ContentNode_AddChild
AddHandler retval.OnDelete, AddressOf ContentNode_Delete
Return retval
End Function
Protected Sub ContentNode_AddChild(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent OnAddChild(Nothing, Nothing)
End Sub
Protected Sub ContentNode_Delete(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent OnDelete(Nothing, Nothing)
End Sub
Public Class ContentTreeNode
Inherits TreeNode
Public Event OnAddChild(ByVal sender As Object, ByVal e As EventArgs)
Public Event OnDelete(ByVal sender As Object, ByVal e As EventArgs)
Private _AddImageURL As String = String.Empty
Private _DeleteImageURL As String = String.Empty
Private btnAddChild As ImageButton
Private btnDelete As ImageButton
Public Sub New(ByVal AddImageURL_ As String, ByVal DeleteImageURL_ As String)
_AddImageURL = AddImageURL_
_DeleteImageURL = DeleteImageURL_
End Sub
Public Property AddImageURL() As String
Get
Return _AddImageURL
End Get
Set(ByVal value As String)
_AddImageURL = value
End Set
End Property
Public Property DeleteImageURL() As String
Get
Return _DeleteImageURL
End Get
Set(ByVal value As String)
_DeleteImageURL = value
End Set
End Property
Protected Overrides Sub RenderPreText(ByVal writer As HtmlTextWriter)
End Sub
Protected Overrides Sub RenderPostText(ByVal writer As HtmlTextWriter)
CreateChildControls()
If GetTreeNodeType() <> ContentTreeNodeTypes.Root Then
btnAddChild.RenderControl(writer)
If GetTreeNodeType() <> ContentTreeNodeTypes.Category Then
btnDelete.RenderControl(writer)
End If
End If
End Sub
Private Function GetTreeNodeType() As TreeNodeTypes
Dim leaf As TreeNodeTypes = TreeNodeTypes.Leaf
If ((Me.Depth = 0) AndAlso (Me.ChildNodes.Count > 0)) Then
Return ContentTreeNodeTypes.Root
End If
If Me.Depth = 1 Then
Return ContentTreeNodeTypes.Category
End If
If ((Me.ChildNodes.Count <= 0) AndAlso Not Me.PopulateOnDemand) Then
Return leaf
End If
Return ContentTreeNodeTypes.Parent
End Function
Protected Sub CreateChildControls()
'Controls.Clear()
'***Creat Add Button***
btnAddChild = New ImageButton()
btnAddChild.ID = "btnAddChild"
btnAddChild.ImageUrl = AddImageURL
btnAddChild.ToolTip = "Add Child"
AddHandler btnAddChild.Click, AddressOf btnAddChild_Click
'***Create DeleteButton***
btnDelete = New ImageButton()
btnDelete.ID = "btnDelete"
btnDelete.ImageUrl = DeleteImageURL()
btnDelete.ToolTip = "Delete Page"
AddHandler btnDelete.Click, AddressOf btnDelete_Click
''***Add Controls***
'Me.Controls.Add(btnAddChild)
'Me.Controls.Add(btnDelete)
End Sub
Protected Sub btnAddChild_Click(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent OnAddChild(Nothing, Nothing)
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent OnDelete(Nothing, Nothing)
End Sub
Public Enum ContentTreeNodeTypes
All = 7
Leaf = 4
None = 0
Parent = 2
Root = 1
Category = 3
End Enum
End Class
End Class
1) Can I implement something like IPostBackEventHandler?
2) Is this possible since treeNode isn't a control/webcontrol?
Any help is appreciated... Thanks!!!
I think the problem is timing related, meaning the child controls are added to late in the ASP.Net page lifecycle for the event to be executed.
This might solve the issue:
Compose the whole tree structure as early as possible, e.g. in the Init event of the page.
Append the child ImageButton in the constructor of the ContentTreeNode.
Alternatively you could use a javascript context-menu so you wouldn't need to append any child-controls to the TreeNode...
After reading this post. I decided to use the following solution. First I changed my CreateChildControls method to:
Protected Sub CreateChildControls()
Dim page As Page = HttpContext.Current.CurrentHandler
Dim csm As ClientScriptManager = page.ClientScript
Dim control As WebControl = page.Master.FindControl(_ContainerID).FindControl(_ContentTreeViewID)
'***Creat Add Button***
btnAddChild = New ImageButton()
btnAddChild.ID = "btnAddChild"
btnAddChild.ImageUrl = AddImageURL
btnAddChild.ToolTip = "Add Child"
btnAddChild.Attributes.Add("onClick", csm.GetPostBackEventReference(control, String.Format("{0}:{1}", Me.Value, "Add")))
'***Create DeleteButton***
btnDelete = New ImageButton()
btnDelete.ID = "btnDelete"
btnDelete.ImageUrl = DeleteImageURL()
btnDelete.ToolTip = "Delete Page"
btnDelete.Attributes.Add("onClick", csm.GetPostBackEventReference(control, String.Format("{0}:{1}", Me.Value, "Delete")))
End Sub
Then I had to implement IPostBackEventHandler in the custom treeview to handle the postback events. Maybe not the best solution but it works well with custom event args.

Resources