vb.net - managementeventwatcher not capturing a second instance of any process [closed] - vb.net

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I've got an application which is watching over executed processes on a device using a managementeventwatcher, like so...
Dim wmiq As String = "SELECT TargetInstance FROM __InstanceCreationEvent WITHIN .025 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name like '%'"
Dim scope As String = "\\.\root\CIMV2"
startProcWatcher = New ManagementEventWatcher(scope, wmiq)
AddHandler startProcWatcher.EventArrived, AddressOf ProcessStarted
startProcWatcher.Start()
And my handler (just logging for now)...
Private Shared Sub ProcessStarted(sender As Object, e As EventArrivedEventArgs)
Dim targetinstance As ManagementBaseObject = e.NewEvent.Properties("TargetInstance").Value
Dim processname As String = targetinstance.Properties("Name").Value.ToString
Dim exepath As String = targetinstance.Properties("ExecutablePath").Value.ToString
Dim thisexeinfo As New FileInfo(exepath)
If Not ProcessExclusionList.Contains(processname) Then
MyApp.DoLogging("Process Started : " & processname & "(" & exepath & ")")
End If
End Sub
This works a treat and I successfully capture the event creation with minimal resource usage (as opposed to Process.GetProcesses(), which was hammering resource!), however I notice that if a second instance of the same process is run, I do not get an event on the second execution.
For example, I can run calculator and my watcher will log calc.exe was executed with all the associated properties. If I then open a second calculator my watcher sees nothing.
I'm guessing I need to modify the WMI query slightly, but my WMI is limited and I'm not struggling.
Can anyone help out with this?
TIA

The code I posted actually works perfectly for multiple instances of a process, however when I was testing, I used calc and it turns out calc spawns multiple instances of itself all under the same process.
repeating the test with any other executable/process results in the desired behavior.

Related

How to Run a Macro Properly in Outlook [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I Believe this question is very common but I am getting a very unique situation.
I have a code that I am using for delay delivery.
But the problem is I am unable to run the macro.
Public Sub Applicaion_Reminder(ByVal Item As Object)
Dim objPeriodicalMail As MailItem
If Item.Class = olTask Then
If InStr(LCase(Item.Subject), "send an email periodically") Then
Set objPeriodicalMail = Outlook.Application.CreateItem(olMailItem)
'Change the following email information as per your actual needs
With objPeriodicalMail
.Subject = "Email to Gmail"
.To = "bfarhan8#gmail.com"
.HTMLBody = "<HTML><BODY>It's a Test</HTML></BODY>"
.Importance = olImportanceHigh
.ReadReceiptRequested = True
.Send
End With
End If
End If
End Sub
When I hit on the run it asks me for Macro Name when I define a name it creates a new Sub.
If I remove the parameters of the
Application_Reminder()
to match the name with a macro name It gives an error on line number 3.
My question is how to run this Macro Properly. I searched the web but didn't find any useful help.
What you have missed is that macros can either be subroutines or functions and for each there are two major types.
A subroutine does something. Your Application_Reminder is a subroutine because it does something: send a reminder. A function can do something, but its real purpose is to return a value.
Some subroutines and functions need parameters, but some do not.
If I write a function Sqrt, the immediate question is: square root of what? I want to be able to write:
Answer = Sqrt(5)
That is, today I want the square root of 5. Tomorrow, I might want the square root of 7.
I would write:
Function Sqrt(ByVal Number as Double) as Double
‘ Code to calculate square root of Number
Sqrt = ResultOfCalculation
End Function
Almost all functions have parameters, but it is not essential. I could have a function, GetCurrentTemperature that reads a thermometer and returns a temperature. It would not need a parameter.
You have written a subroutine that has a parameter: Applicaion_Reminder(ByVal Item As Object). When you try to run Applicaion_Reminder, the interpreter wants to know what Item. I do not think the interpreter’s response is very sensible. It should have just told you, “You cannot run a subroutine with a parameter.”
You need a subroutine without a parameter that decides which Item is to be processed. With some computer languages, that subroutine must have the name Main. With VBA it can have any name.
That is, you need a subroutine like this:
Sub PickAnItemThatNeedsAReminder()
Dim Item as Object
‘ Code to set Item to the required MailItem
Call Applicaion_Reminder(Item)
End Sub
There are four distinct methods of selecting a MailItem. I imagine you scrolling down your Sent Items folder looking for emails to which you have not received a reply. When you find such an email, you run PickAnItemThatNeedsAReminderwhich sends a reminder.
Sub PickAnItemThatNeedsAReminder ()
Dim Exp As Explorer
Dim Item As Object
Set Exp = Outlook.Application.ActiveExplorer
If Exp.Selection.Count = 0 Then
Call MsgBox("Please select one or more emails then try again", vbOKOnly)
Exit Sub
Else
For Each Item In Exp.Selection
Call Applicaion_Reminder(Item)
Next
End If
End Sub
Exp.Selection is a list of all the currently selected emails. You can select as many emails as you want and them run PickAnItemThatNeedsAReminder. It will call Applicaion_Reminder for every selected email.
Additional Background
My belief is you have found a routine that runs off an event and have tried to adapt it to your requirements. Events are an incredibly useful feature of Outlook. However, if you do not yet understand that you cannot run a macro without a parameter, you are not yet ready for events. We say: walk before you run.
BraX and Super Symmetry would be correct in telling you to use ThisOutlookSession if you are going to use events. I have suggested you use Explorer (which is technically an event) but which is much easier for a beginner to understand than an application level event which is what you seemed to have found. With my approach, all your code can be in an ordinary module.
Application.Reminder event Occurs immediately before a reminder is displayed
set up Task Item with reminder then call your vba function - Applicaion_Reminder
See example on this answer
https://stackoverflow.com/a/40144594/4539709
if you want to call it with selected email then see Tony's answer

Call a form in another form with button click [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I want to open FrmNovaRegra with a button click in another form.
I already tried the basic "Dim form as new FrmNovaRegra" and "form.show()" it didnt work, how can i open it? The code of the Form that i want to open is in the next line:
Public Class FrmNovaRegra
Private regras As BServices.NovaRegra
'Private MyDictionary As New Dictionary(Of String, List(Of String))
Public Sub New(ByVal cls As BServices.NovaRegra)
InitializeComponent()
Me.regras = cls
End Sub
Your form needs it's parameter, because there are no other overloads. There are many ways you can correct this.
If you have the cls As BServices.NovaRegra you can create the form using:
Dim form as new FrmNovaRegra(cls)
If you want to create a new one on the fly, that's also possible:
Dim form as new FrmNovaRegra(New BServices.NovaRegra())
This new cls might need some parameters too, I'm not familiar with this class.
Another way to work around this would be to add a new overload which doesn't need a parameter, but your form looks like it needs the cls, so let me know if you need more explanations for this one as a comment.

What to return when a string function fails? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Many of the applications I develop tap into the databases of pre-existing applications (I develop largely for small businesses that are trying to expand cheaply); A lot of this kind of work involves grabbing information out of other applications' databases (for example "site name", etc).
I normally have class libraries to do this kind of work, saving on database calls where possible. For example I might have a function like the below:
Private Function GetSiteName(ByVal dbPath As String) As String
Dim returned As String
Dim conn As New AdsConnection("data source = " & Path & "; ServerType=remote|local; TableType=CDX")
Dim cmd As AdsCommand
Try
conn.Open()
cmd = conn.CreateCommand()
cmd.CommandText = "select stSiteName from Sites;"
returned = cmd.ExecuteScalar
conn.Close()
Return returned
Catch e As AdsException
' write to log here
End Try
End Function
(For those not familiar, in the particular example above I'm accessing a database from Advantage Database Server).
In the above example, I would get a warning saying not all code paths return a value. If I move the Return statement to just before the End Function (outside the Try...Catch block, I would get a warning saying the variable may not be initialised.
Is there a standard/preferred way of handling this? At the moment I generally handle by putting the error message into the returned value, then testing for it from the calling code but it feels clunky to me.
The problem is that you handled the exception in your function. A handled exception is transparent to the caller, i.e. code outside this function will have no way of determining whether the exception was raised. This design is only correct when your function behaves correctly even when a exception is raised (hence can be handled).
When the catch statement is executed, the function does not know what value to return. That is the problem. You should not catch the exception at this level. You should let the exception raise, then past it to the upper level, where you can show appropriate error messages to the user.
The problem you are facing has nothing to do with Error Handling in particular. The compiler issues a warning if a function doesn't return something on all code paths, and you can choose it ignore it, since it is not categorized as an Error.
e.g. You will get the same warnings with If...Else if the code inside either If or Else doesn't return a value. Similarly you will get the warning in a Select..Case block if at least one of the Case blocks don't return a value.
It is however good to pay attention to what warnings the compiler issues and minimize the number of such warnings.
There are two approaches around this problem.
Keep multiple exit points in your function and ensure that all the exit points return some value.
Initialize your variable with some default value, and keep only one exit point for the function.
While it is debatable which one of the above is better, I personally like the second approach. It is better from code maintenance perspective too (when the function is too large).
For Example, you can initialize the variable with empty value or nothing to get rid of that warning.
Dim returned As String = String.Empty
...
Try
...
Catch e As AdsException
...
End Try
...
Return returned
In this example, you have 4 code paths from where the function can exit out (shown by ... in the example above). Assume that you had 10 or 15. You get a warning if you do not set the return value on any of the code paths. The above solution solves the problem by initializing the variable at the beginning, and return it at the end. Then you need not worry which code path sets the variable and which doesn't.

Write does not produce a value issue [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Alright, I've managed to get a string containing HTML content inside of it, but I need to get into an HTMLDocument for parsing.
I've tested the following code, and I've been unable to get it to work through any of the variations I've tried.
Dim webclient As New System.Net.WebClient
Dim result As String = webclient.DownloadString(link)
Dim htm As HtmlDocument
htm = htm.Write(result)
Dim sDD As Object
sDD = htm.GetElementById("tag-sidebar")
Dim IDD As Object
IDD = htm.GetElementById("highres")
Currently it is telling me that htm = htm.Write(result) does not produce a value, so I'm sort of stumped.
I'm Currently using Microsoft Visual Studio 2013 Professional
The error just indicates that the Write method does not produce a value. In VB-speak that means Write is a Sub, not a Function.

How to read From Text Files line by line - multiple choice Quiz [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Hi i really need some help with this, I need to make a multiple choice question program that reads the questions and answers from 2 different text files (notepad files)
but when I try I cant seem to get it working. i have tried loops but that didn't work then I tried arrays but that didn't meet the requirements of reading form a text file
So I come to you all I need help is with reading a text file line by tine and then updating it when a new question needs to be given
I cannot 1 read the line by line (questions.txt) and i need to have match the question which are in answers.txt then i need to update it when next question is clicked
VB.Net
Program i need to create must do the following
Questions and answers should be loaded from a file called questions.txt and answers.txt respectively
-Questions should also appear in random order, every time program is executed
-update form for next question
-keep track on how many questions are correct
Any resources or tutorials on any of the above would be muchly appreciated
Total edits: 198305769 lol. Cleaned up the answer, and this should get you nearly complete. Cheers.
Declare a global variable (integer); that's where you'll assign the amount of questions the user has answered:
Public Class Form1
Dim keepScore As Integer = 0
Not the neatest, but it appends each line from a selected text file into an array and then you can iterate through it.
Dim ofd As New OpenFileDialog
ofd.ShowDialog()
Dim xstr = ofd.FileName
Dim questions() As String = IO.File.ReadAllLines(ofd.FileName)
Dim answers() As String = IO.File.ReadAllLines(ofd.FileName)
Dim sw As New StringBuilder
Dim i As Integer = 0
Do Until i = questions.Count()
sw.AppendLine(Trim(questions(i)))
MsgBox(questions(i)) 'Only added this so you can see the lines
i = i + 1
Loop
Do Until i = answers.Count()
sw.AppendLine(Trim(answers(i)))
MsgBox(answers(i)) 'Only added this so you can see the lines
i = i + 1
Loop
Add onto the end of this function an if statement:
If CorrectAnswer.Checked = True 'Assuming you are using a RadioButton Group, or CheckBox
keepScore = keepScore + 1
End If
Here is a quick number randomiser, assuming you have 20 questions (change the 20 accordingly to whatever amount of questions you have):
Randomize()
Dim i As Integer = CInt(Int(20 * Rnd() + 1))
MsgBox(i)
Best of luck.