Dispatcher.BeginInvoke Error in VB but not C# - 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.

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;

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

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

Calling text message from XML file

Currently i'm developing a software which uses layered architecture using Visual Studio 2008 and C#.
In that system I want to keep all the text messages(that will be shown using message boxes when necessary) in an XML file so that if I update any message I dont have to compile the whole system. How can I accomplish this? What will be the XML file structure? How the messages will be called from C# code? Please be descriptive and give example.
Thanks.
A better choice for your scenario may be a Resource Satellite DLL. This is a separate DLL which contains a set of resoures that are dynamically loaded into your application. This is how many different applications do localization. And most importantly, there are many tools which support this type of feature.
Changing the messages would simply involve changing this DLL. This does result in a compile, but only of the resources and not the system.
http://msdn.microsoft.com/en-us/library/e9zazcx5.aspx
I would create a class that used a .NET DataSet and DataTable to store the ids and messages (and whatever else you need).
That way the class can use the DataSet.WriteXML() and DataSet.ReadXML() to save/load from any filename you specify and you don't have to worry about "hand crafting" the XML format yourself.
This sounded like a handy class to have, so I wrote one up as a "proof of concept":
'*************************************************************************
' Class: MsgFile
' Author: Ron Savage
' Date: 05/14/2009
'
' This class is an example for using an XML file to hold messages to be
' displayed by an application.
'
' Modification History
' Date Init Comment
' 05/14/2009 RS Created.
'*************************************************************************
Imports Microsoft.VisualBasic
Imports System.IO
Public Class MsgFile
'*************************************************************************
' Class Variables
'*************************************************************************
Private MsgFile As String
Private msgData As DataSet
Private msgTable As DataTable
'*************************************************************************
' Sub: New()
' Author: Ron Savage
' Date: 05/14/2009
'
' Creates a new MsgFile from an existing file, or creates an empty one
' with the specified file name.
'*************************************************************************
Sub New(ByVal msg_File As String)
Dim srcFile As New FileInfo(msg_File)
If (srcFile.Exists()) Then
msgData = New DataSet()
Load(msg_File)
Else
NewFile(msg_File)
End If
End Sub
'*************************************************************************
' Sub: NewFile()
' Author: Ron Savage
' Date: 05/14/2009
'
' Creates a new XML message file.
'*************************************************************************
Sub NewFile(ByVal msg_File As String)
Me.MsgFile = msg_File
If (IsNothing(msgData)) Then
msgData = New DataSet("MyAppMessages")
msgTable = New DataTable("Messages")
msgTable.Columns.Add(New DataColumn("Id", GetType(System.Int32), Nothing, MappingType.Attribute))
msgTable.Columns.Add(New DataColumn("Text", GetType(System.String), Nothing, MappingType.Attribute))
msgData.Tables.Add(msgTable)
setMessage(0, "New file created")
End If
Save()
End Sub
'*************************************************************************
' Sub: Load()
' Author: Ron Savage
' Date: 05/14/2009
'
' Loads an existing XML message file into the dataset.
'*************************************************************************
Public Sub Load(ByVal msgFileName As String)
Dim srcFile As FileInfo = Nothing
Me.MsgFile = msgFileName
srcFile = New FileInfo(msgFileName)
msgData.Clear()
If (srcFile.Exists()) Then
msgData.ReadXml(msgFileName)
msgTable = msgData.Tables("Messages")
End If
End Sub
'*************************************************************************
' Sub: Save()
' Author: Ron Savage
' Date: 10/05/2008
'
' This routine saves the DataSet to an XML file.
'*************************************************************************
Public Overridable Sub Save()
If (Not IsNothing(msgData) And Not MsgFile.Equals("")) Then
Dim fileWriter As StreamWriter = New StreamWriter(MsgFile)
msgData.WriteXml(fileWriter)
fileWriter.Close()
End If
End Sub
'*************************************************************************
' Sub: getMessage()
' Author: Ron Savage
' Date: 05/14/2009
'
' This gets the text of the message.
'*************************************************************************
Public Function getMessage(ByVal msgId As String) As String
Dim rowsFound() As System.Data.DataRow
Dim msgText As String = ""
If (Not IsNothing(msgTable)) Then
rowsFound = msgTable.Select("Id = " + msgId.ToString)
If (rowsFound.Length > 0) Then
msgText = rowsFound(0).Item("Text").ToString
End If
End If
Return (msgText)
End Function
'*************************************************************************
' Sub: setMessage()
' Author: Ron Savage
' Date: 05/14/2009
'
' This sets the text of the message.
'*************************************************************************
Public Sub setMessage(ByVal msgId As Integer, ByVal msgText As String)
Dim rowsFound() As System.Data.DataRow
Dim msgRow As System.Data.DataRow
If (Not IsNothing(msgTable)) Then
rowsFound = msgTable.Select("Id = " + msgId.ToString)
If (rowsFound.Length > 0) Then
msgRow = rowsFound(0)
msgRow.Item("Id") = msgId
msgRow.Item("Text") = msgText
Else
msgRow = msgTable.NewRow()
msgRow.Item("Id") = msgId
msgRow.Item("Text") = msgText
msgTable.Rows.Add(msgRow)
End If
End If
Save()
End Sub
End Class
You might want to add your own custom section to your app.config file to store your messages. However this would require you to update the app.config file each time a message changes.
http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx

Categories