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

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

Related

How to get event when word process stopped in vb.net

I am using ManagementEventWatcher to get message when process start and stop.
I am successfully getting message when word process start it displays me File name and datetime.
I have an issue in stopping process.
Public Class Form1
Dim list As New List(Of String)
Dim list1 As New List(Of String)
Private processStartEvent As ManagementEventWatcher = New ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace")
Private processStopEvent As ManagementEventWatcher = New ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace")
Public Sub New()
InitializeComponent()
AddHandler processStartEvent.EventArrived, New EventArrivedEventHandler(AddressOf processStartEvent_EventArrived)
processStartEvent.Start()
AddHandler processStopEvent.EventArrived, New EventArrivedEventHandler(AddressOf processStopEvent_EventArrived)
processStopEvent.Start()
End Sub
Private Sub processStartEvent_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
Dim allProcesses = Process.GetProcesses().Where(Function(p) p.ProcessName.Contains("WINWORD"))
Dim windowTitles = ChildWindowManager.GetChildWindowTitles(allProcesses.First().Id)
For Each title In windowTitles
If (title.Contains("- Word")) Then
If Not (title.Contains("Opening - Word")) Then
If Not list.Contains(title) Then
list.Add(title)
MessageBox.Show("+ Process Started. File Name: " & String.Join(",", list.Item(list.Count - 1)) & " | Date & Time: " & System.DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") & vbNewLine & vbNewLine)
End If
End If
End If
Next
End Sub
Private Sub processStopEvent_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
End Sub
End Class
Class ChildWindowManager
Delegate Function EnumThreadDelegate(ByVal hWnd As IntPtr, ByVal lParam As IntPtr) As Boolean
<DllImport("user32.dll")>
Private Shared Function EnumThreadWindows(ByVal dwThreadId As Integer, ByVal lpfn As EnumThreadDelegate, ByVal lParam As IntPtr) As Boolean
End Function
<DllImport("user32.dll")>
Public Shared Function GetWindowText(ByVal hwnd As Integer, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
End Function
<DllImport("user32.dll")>
Private Shared Function GetWindowTextLength(ByVal hwnd As IntPtr) As Integer
End Function
Private Shared Function EnumerateProcessWindowHandles(ByVal processId As Integer) As List(Of IntPtr)
Dim windowHandles = New List(Of IntPtr)()
For Each thread As ProcessThread In Process.GetProcessById(processId).Threads
EnumThreadWindows(thread.Id, Function(hWnd, lParam)
windowHandles.Add(hWnd)
Return True
End Function, IntPtr.Zero)
Next
Return windowHandles
End Function
Private Shared Function GetWindowTitle(ByVal hWnd As IntPtr) As String
Dim length As Integer = GetWindowTextLength(hWnd)
If length = 0 Then Return Nothing
Dim titleStringBuilder As New System.Text.StringBuilder("", length)
GetWindowText(hWnd, titleStringBuilder, titleStringBuilder.Capacity + 1)
Return titleStringBuilder.ToString()
End Function
Public Shared Function GetChildWindowTitles(processId As Integer) As List(Of String)
Dim windowTitles As New List(Of String)
For Each Handle In EnumerateProcessWindowHandles(processId)
Dim windowText = GetWindowTitle(Handle)
If windowText <> Nothing Then
windowTitles.Add(windowText)
End If
Next
Return windowTitles
End Function
End Class

VB.Net MasterPage Page.PreLoad Property not found

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;

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.

Proper syntax for parameters in VB function call

I have developed in the past in VB.net and I simply can't figure out how to properly call this function and how to get the response so I can display it on a web page response.
I translated the example c# code to VB. Here is my code behind for an aspx page that I wish to use to make the request and then display the response in my page:
Imports OffAmazonPaymentsService
Imports OffAmazonPaymentsService.Model
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write(GetOrderReferenceDetails(???service???, "asdfsadf", "asdfsadf", "asdfasdf"))
End Sub
Private Shared Function GetOrderReferenceDetails(service As IOffAmazonPaymentsService, sellerId As String, amazonOrderReferenceId As String, addressConsentToken As String) As GetOrderReferenceDetailsResponse
' Required parameters
Dim request As New GetOrderReferenceDetailsRequest()
request.SellerId = sellerId
request.AmazonOrderReferenceId = amazonOrderReferenceId
' Optional parameters
request.AddressConsentToken = addressConsentToken
Return service.GetOrderReferenceDetails(request)
End Function
End Class
I don't know how to call that function's first (service) parameter and to then display the contents of the response.
Let me know if my question is not clear enough.
here is the example they gave in c sharp format....
using OffAmazonPaymentsService;
using OffAmazonPaymentsService.Model;
public class GetOrderReferenceDetailsSample
{
/**
* Sample GetOrderReferenceDetails method that takes generic inputs, constructs a request object,
* and make a call to the service.
*/
private static GetOrderReferenceDetailsResponse GetOrderReferenceDetails(
IOffAmazonPaymentsService service,
string sellerId,
string amazonOrderReferenceId,
string addressConsentToken)
{
// Required parameters
GetOrderReferenceDetailsRequest request = new GetOrderReferenceDetailsRequest();
request.SellerId = sellerId;
request.AmazonOrderReferenceId = amazonOrderReferenceId;
// Optional parameters
request.AddressConsentToken = addressConsentToken;
return service.GetOrderReferenceDetails(request);
}
}
Disclaimer: my VB is "rusty" so debug and improve as necessary
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim props As OffAmazonPaymentsServicePropertyCollection = OffAmazonPaymentsServicePropertyCollection.getInstance()
Dim client As New OffAmazonPaymentsServiceClient(props)
Dim result as GetOrderReferenceDetailsResponse = GetAmzOrderRef(client, props, "oref", "token")
End Sub
Private Shared Function GetAmzOrderRef(service As IOffAmazonPaymentsService, props As OffAmazonPaymentsServicePropertyCollection, amazonOrderReferenceId As String, addressConsentToken As String) As GetOrderReferenceDetailsResponse
Dim request as New GetOrderReferenceDetailsRequest()
With request
.SellerId = props.MerchantID
.AmazonOrderReferenceId = amazonOrderReferenceId
.AddressConsentToken = addressConsentToken
End With
Return service.GetOrderReferenceDetails(request)
End Function
Notes:
you should have your config values set (web.config or app.config as necessary), that's where OffAmazonPaymentsServicePropertyCollection.getInstance() will obtain values
the above sample code will fail (as expected) because of dummy values for reference id and token, but that "error" is from the Amazon API (already) - e.g. response error "invalid reference id" or "invalid token" etc....
Hth....

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

Categories