VB.Net MasterPage Page.PreLoad Property not found - c#

I am trying to implement Cross-Site Request Forgery (CSRF) using Microsoft .Net ViewStateUserKey and Double Submit Cookie. For more please visit this link
The above code is in C# and i am converting this into VB.Net. Now The problem is that in this code there is a line
Page.PreLoad += master_Page_PreLoad;
When i try to convert the same line in VB.Net it does not find any such event Page.PreLoad
Please help how can i do this.
Thanks

The C# MasterPage template converted to VB looks like this:
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
Private _antiXsrfTokenValue As String
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
_antiXsrfTokenValue = requestCookie.Value
Page.ViewStateUserKey = _antiXsrfTokenValue
Else
_antiXsrfTokenValue = Guid.NewGuid().ToString("N")
Page.ViewStateUserKey = _antiXsrfTokenValue
Dim responseCookie = New HttpCookie(AntiXsrfTokenKey) With {
.HttpOnly = True,
.Value = _antiXsrfTokenValue
}
If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
responseCookie.Secure = True
End If
Response.Cookies.[Set](responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub
Protected Sub master_Page_PreLoad(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
Else
If CStr(ViewState(AntiXsrfTokenKey)) <> _antiXsrfTokenValue OrElse CStr(ViewState(AntiXsrfUserNameKey)) <> (If(Context.User.Identity.Name, String.Empty)) Then
Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
End If
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
End Class
I believe the specific line you're looking for is AddHandler Page.PreLoad, AddressOf master_Page_PreLoad.
For future reference, if you're looking to convert C# code to VB, or vice versa, there is a pretty great Telerik tool for that which can be found here: http://converter.telerik.com/. In order to get the code I posted above, I simply ran the C# template through there.

You can straight away create the method,
Private Sub Page_PreRender(ByVal sender As System.Object, ByVal e As System.EventArgs)
If Not IsPostBack Then
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
Else
If CStr(ViewState(AntiXsrfTokenKey)) <> _antiXsrfTokenValue OrElse CStr(ViewState(AntiXsrfUserNameKey)) <> (If(Context.User.Identity.Name, String.Empty)) Then
Throw New InvalidOperationException("Validation of " & "Anti-XSRF token failed.")
End If
End If
End Sub
No need to address this
Page.PreLoad += master_Page_PreLoad;

Related

Dispatcher.BeginInvoke Error in VB but not C#

Hey all I am using some UIAutomation code that was written in C#. So I converted it into VB.net so that I could integrate it into my own program I am making.
The code that has the error is this line:
Private Sub LogMessage(message As String)
Dispatcher.BeginInvoke(DispatcherPriority.Normal, New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
The error is on the Dispatcher.BeginInvoke stating Error 1 Reference to a non-shared member requires an object reference..
The code in C# looks like this:
private void LogMessage(string message)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new SetMessageCallback(DisplayLogMessage), message);
}
And has no errors and works just fine.
What am I missing from the VB.net version to make it work correctly?
The original C# code can be found HERE.
My converted C# to VB.net code looks like this:
Imports System.Threading
Imports Automation = System.Windows.Automation
Imports System.Windows.Automation
Imports System.Windows.Threading
Public Class Form1
Public Delegate Sub SetMessageCallback(ByVal [_Msg] As String)
Private Sub Automate()
LogMessage("Getting RootElement...")
Dim rootElement As AutomationElement = AutomationElement.RootElement
If rootElement IsNot Nothing Then
LogMessage("OK." + Environment.NewLine)
Dim condition As Automation.Condition = New PropertyCondition(AutomationElement.NameProperty, "UI Automation Test Window")
LogMessage("Searching for Test Window...")
Dim appElement As AutomationElement = rootElement.FindFirst(TreeScope.Children, condition)
If appElement IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Searching for TextBox A control...")
Dim txtElementA As AutomationElement = GetTextElement(appElement, "txtA")
If txtElementA IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Setting TextBox A value...")
Try
Dim valuePatternA As ValuePattern = TryCast(txtElementA.GetCurrentPattern(ValuePattern.Pattern), ValuePattern)
valuePatternA.SetValue("10")
LogMessage("OK " + Environment.NewLine)
Catch
WriteLogError()
End Try
Else
WriteLogError()
End If
LogMessage("Searching for TextBox B control...")
Dim txtElementB As AutomationElement = GetTextElement(appElement, "txtB")
If txtElementA IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Setting TextBox B value...")
Try
Dim valuePatternB As ValuePattern = TryCast(txtElementB.GetCurrentPattern(ValuePattern.Pattern), ValuePattern)
valuePatternB.SetValue("5")
LogMessage("OK " + Environment.NewLine)
Catch
WriteLogError()
End Try
Else
WriteLogError()
End If
Else
WriteLogError()
End If
End If
End Sub
Private Function GetTextElement(parentElement As AutomationElement, value As String) As AutomationElement
Dim condition As Automation.Condition = New PropertyCondition(AutomationElement.AutomationIdProperty, value)
Dim txtElement As AutomationElement = parentElement.FindFirst(TreeScope.Descendants, condition)
Return txtElement
End Function
Private Sub DisplayLogMessage(message As String)
TextBox1.Text += message
End Sub
Private Sub LogMessage(message As String)
Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
Private Sub WriteLogError()
LogMessage("ERROR." + Environment.NewLine)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim automateThread As New Thread(New ThreadStart(AddressOf Automate))
automateThread.Start()
End Sub
End Class
Found the correct way of doing it:
Private Sub LogMessage(message As String)
Me.BeginInvoke(New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
Thanks goes to #HansPassant for the help.
Dispatcher can be static. I think you need Me.Dispatcher.

convert c# to vb an event, and cannot be called directly

I'm trying to convert the following c# code to vb.net, but an error raised at the vb converted lines: Me.ZBAPI_MEDDOC_CREATE_LINKCompleted.
c#:
private void OnZBAPI_MEDDOC_CREATE_LINKOperationCompleted(object arg)
{
if ((this.ZBAPI_MEDDOC_CREATE_LINKCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.ZBAPI_MEDDOC_CREATE_LINKCompleted(this, new ZBAPI_MEDDOC_CREATE_LINKCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
vb:
Private Sub OnZBAPI_MEDDOC_CREATE_LINKOperationCompleted(ByVal arg As Object)
If (Me.ZBAPI_MEDDOC_CREATE_LINKCompleted IsNot Nothing) Then
Dim invokeArgs As System.Web.Services.Protocols.InvokeCompletedEventArgs = DirectCast(arg, System.Web.Services.Protocols.InvokeCompletedEventArgs)
Me.ZBAPI_MEDDOC_CREATE_LINKCompleted(Me, New ZBAPI_MEDDOC_CREATE_LINKCompletedEventArgs(invokeArgs.Results, invokeArgs.[Error], invokeArgs.Cancelled, invokeArgs.UserState))
End If
End Sub
How should I convert the c# line this.ZBAPI_MEDDOC_CREATE_LINKCompleted?
You need to use RaiseEvent in VB.NET, which also does not require the null check for if there are event listeners attached:
Private Sub OnZBAPI_MEDDOC_CREATE_LINKOperationCompleted(ByVal arg As Object)
Dim invokeArgs As System.Web.Services.Protocols.InvokeCompletedEventArgs = DirectCast(arg, System.Web.Services.Protocols.InvokeCompletedEventArgs)
RaiseEvent ZBAPI_MEDDOC_CREATE_LINKCompleted(Me, New ZBAPI_MEDDOC_CREATE_LINKCompletedEventArgs(invokeArgs.Results, invokeArgs.[Error], invokeArgs.Cancelled, invokeArgs.UserState))
End Sub

Cookie set and read not working in IE9 using asp.net code?

IE 9 is setting cookie values in browser even after changing privacy settings. What is the next option to save cookies in IE?
see below my code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.Cookies("RememberMe") Is Nothing Then
'this if condition is failing, it never executes and working in chrome.
End If
End If
Response.Cache.SetExpires(DateTime.Parse(DateTime.Now.ToString()))
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetNoStore()
Response.AppendHeader("Pragma", "no-cache")
End Sub
Protected Sub imgLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If Page.IsValid() Then
If Not user Is Nothing Then
FormsAuthentication.RedirectFromLoginPage(strUserID, False)
If (chkRememberMe.Checked) Then
Helper.StoreRememberMe(strUserID, ddlCompany.SelectedItem.Text)
ElseIf Not Request.Cookies("RememberMe") Is Nothing Then
Helper.DeleteCookie("RememberMe")
End If
Session("userInfo") = user
Response.Redirect("~/home.aspx")
End If
End If
End Sub
Public Shared Sub StoreRememberMe(ByVal username As String, ByVal company As String)
Dim rememberMe As New HttpCookie("RememberMe")
rememberMe.Values.Add("user", username)
rememberMe.Values.Add("company", company)
rememberMe.Expires = DateTime.Now.AddDays(30)
'cookie Expires ;
HttpContext.Current.Response.AppendCookie(rememberMe)
End Sub

pos for.net in windows 7 vb.net

I am using microsoft POS for .net dll and I am converting this part to vb.net from a HOL sample barcode reading tutorial written in c# found here.
EDIT:The device list shows and popup window shows (the activate button is pressed and scanner input is tested)but the txteventhistory is not update even when scanner emulator is used and i suspect the said part is the culprit. thank you for the response
{
Action<string> updateEventHistoryAction = new Action<string>(p => { txtEventHistory.Text = p; });
txtEventHistory.Invoke(updateEventHistoryAction, newEvent);
}
from this
void activeScanner_DataEvent(object sender, DataEventArgs e)
{
UpdateEventHistory("Data Event");
ASCIIEncoding encoder = new ASCIIEncoding();
try
{
// Display the ASCII encoded label text
string data = encoder.GetString(activeScanner.ScanDataLabel);
Action<string> updateScanDataLabelAction = new Action<string>(p => {txtScanDataLabel.Text = p;});
txtScanDataLabel.Invoke(updateScanDataLabelAction, data);
// Display the encoding type
string dataType = activeScanner.ScanDataType.ToString();
Action<string> updateScanDataTypeLabelAction = new Action<string>(p => { txtScanDataType.Text = p; });
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType);
// re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = true;
}
catch (PosControlException)
{
// Log any errors
UpdateEventHistory("DataEvent Operation Failed");
}
}
the conversion tool in #develop yielded the one below but i don't think it's correct
Dim updateScanDataLabelAction As New Action(Of String)(function (p)
txtScanDataLabel.Text = p
end function)
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
I tried converting it to but not quite there i think, though it
Private Sub activeScanner_DataEvent(sender As Object, e As DataEventArgs)
UpdateEventHistory("Data Event")
Dim encoder As New ASCIIEncoding()
Try
' Display the ASCII encoded label text
Dim data As String = encoder.GetString(activeScanner.ScanDataLabel)
Dim updateScanDataLabelAction append As New Action(Of String))
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType)
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("DataEvent Operation Failed")
End Try
End Sub
Private Sub p(ByVal text As String)
txtScanDataType.Text = text
End Sub
here is the whole code
Imports Microsoft.PointOfService
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Namespace POS
Partial Public Class ScannerLab
Inherits Form
Private explorer As PosExplorer
Private scannerList As DeviceCollection
Private scannerList1 As DeviceCollection
Private activeScanner As Scanner
Public Sub New()
InitializeComponent()
End Sub
Private Sub ScannerLab_Load(ByVal sender As Object, ByVal e As EventArgs)handles mybase.load
explorer = New PosExplorer()
scannerList1 = explorer.GetDevices()
bsdevices.DataSource = scannerList1
cboDevices.DisplayMember = scannerList1.ToString()
scannerList = explorer.GetDevices(DeviceType.Scanner)
devicesBindingSource.DataSource = scannerList
lstDevices.DisplayMember = scannerList.ToString()
End Sub
Private Sub btnActivateDevice_Click(ByVal sender As Object, ByVal e As EventArgs) handles btnActivateDevice.Click
If lstDevices.SelectedItem IsNot Nothing Then
ActivateScanner(DirectCast(lstDevices.SelectedItem, DeviceInfo))
End If
End Sub
Private Sub reportFailure()
Throw New Exception("The method or operation is not implemented.")
End Sub
Private Sub ActivateScanner(ByVal selectedScanner As DeviceInfo)
'Verifify that the selectedScanner is not null
' and that it is not the same scanner already selected
If selectedScanner IsNot Nothing AndAlso Not selectedScanner.IsDeviceInfoOf(activeScanner) Then
' Configure the new scanner
DeactivateScanner()
' Activate the new scanner
UpdateEventHistory(String.Format("Activate Scanner: {0}", selectedScanner.ServiceObjectName))
Try
activeScanner = DirectCast(explorer.CreateInstance(selectedScanner), Scanner)
activeScanner.Open()
activeScanner.Claim(1000)
activeScanner.DeviceEnabled = True
AddHandler activeScanner.DataEvent, AddressOf activeScanner_DataEvent
AddHandler activeScanner.ErrorEvent, AddressOf activeScanner_ErrorEvent
activeScanner.DecodeData = True
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log error and set the active scanner to none
UpdateEventHistory(String.Format("Activation Failed: {0}", selectedScanner.ServiceObjectName))
activeScanner = Nothing
End Try
End If
End Sub
Private Sub DeactivateScanner()
If activeScanner IsNot Nothing Then
' We have an active scanner, lets log that we are
' about to close it.
UpdateEventHistory("Deactivate Current Scanner")
Try
' Close the active scanner
activeScanner.Close()
Catch generatedExceptionName As PosControlException
' Log any error that happens
UpdateEventHistory("Close Failed")
Finally
' Don't forget to set activeScanner to null to
' indicate that we no longer have an active
' scanner configured.
activeScanner = Nothing
End Try
End If
End Sub
Private Sub activeScanner_DataEvent(ByVal sender As Object, ByVal e As DataEventArgs)
UpdateEventHistory("Data Event")
Dim encoder As New ASCIIEncoding()
Try
' Display the ASCII encoded label text
Dim data As String = encoder.GetString(activeScanner.ScanDataLabel)
Dim updateScanDataLabelAction As New Action(Of String)(AddressOf p)
txtScanDataLabel.Invoke(updateScanDataLabelAction, data)
' Display the encoding type
Dim dataType As String = activeScanner.ScanDataType.ToString()
Dim updateScanDataTypeLabelAction As New Action(Of String)(AddressOf p)
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType)
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("DataEvent Operation Failed")
End Try
End Sub
Private Sub p(ByVal text As String)
txtScanDataType.Text = text
End Sub
Private Sub q(ByVal text As String)
txtScanDataType.Text = text
End Sub
Private Sub UpdateEventHistory(ByVal newEvent As String)
If txtEventHistory.InvokeRequired Then
Dim updateEventHistoryAction As New Action(Of String)(AddressOf q)
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
Else
txtEventHistory.Text = (Convert.ToString(newEvent) & System.Environment.NewLine) + txtEventHistory.Text
End If
End Sub
Private Sub activeScanner_ErrorEvent(ByVal sender As Object, ByVal e As DeviceErrorEventArgs)
UpdateEventHistory("Error Event")
Try
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("ErrorEvent Operation Failed")
End Try
End Sub
EDIT: updated the code

How can I force web browser control to remember proxy credentials setting?

I'm using .net web browser control to open an url in new window through proxy with credentials. I use this code for that:
Public Function AppendHeader(ByRef OriginalHeader As String, ByVal Addition As String) As Boolean
If OriginalHeader <> "" Then
OriginalHeader = OriginalHeader + vbNewLine
End If
OriginalHeader = OriginalHeader + Addition
OriginalHeader.Trim(vbNewLine.ToCharArray)
End Function
Public Function Base64Enc(ByRef s As String) As String
Base64Enc = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(s))
End Function
Public Sub Navigate()
Dim webBrowser As WebBrowser = New WebBrowser()
Dim headers As String = ""
AppendHeader(headers, "Proxy-Authorization: Basic " & Base64Enc("user:pass"))
'AppendHeader(headers, "Authorization: Basic " & Base64Enc("user:pass"))
webBrowser.Navigate("http://stackoverflow.com", Guid.NewGuid().ToString(), Nothing, headers)
End Sub
This code helps to hide Windows Security window at the first time, but if loading web page sends requests to other urls this window shows again and again (you can see it on a screenshot below).
So what can I do to solve this problem?
(I'm using winforms and vb.net, but C# is suitable too)
Give this a try I am unable to test it :)
Private Sub webBrowser_Navigating(ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs)
Dim credentials As New System.Net.NetworkCredential("user", "pwd", "MyDomain")
Dim proxy As New System.Net.WebProxy("127.0.1.2", 80)
If proxy Is Nothing Then
e.Cancel = True
End If
End Sub

Categories