I'm using WMI to monitor start and stop processes on Win XP machine
My code goes like this:
ManagementEventWatcher m_Create;
ManagementEventWatcher m_Delete;
private void SetMonitors()
{
string queryStartTrace = "SELECT * FROM Win32_ProcessStartTrace";
string queryStopTrace = "SELECT * FROM Win32_ProcessStopTrace";
m_Create = new ManagementEventWatcher(queryStartTrace);
m_Delete = new ManagementEventWatcher(queryStopTrace);
m_Create.EventArrived += new EventArrivedEventHandler(this.OnCreationArrived_Event);
m_Delete.EventArrived += new EventArrivedEventHandler(this.OnDeletionArrived_Event);
}
private void OnCreationArrived_Event(object sender, EventArrivedEventArgs e){...}
private void OnDeletionArrived_Event(object sender, EventArrivedEventArgs e){...}
Everything works fine. But suddenly it stops working, don't know why. Only after restart my machine it returns to work.
Edit 1
As #Alexandru helped me, I assigned the watchers to stopped and disposed events:
m_Create.Stopped += new StoppedEventHandler(watcherCreate_Stopped);
m_Create.Disposed += new EventHandler(watcherCreate_Disposed);
m_Delete.Stopped += new StoppedEventHandler(watcherDelete_Stopped);
m_Delete.Disposed += new EventHandler(watcherDelete_Disposed);
And added those methods:
void watcherCreate_Stopped(object sender, StoppedEventArgs e)
{
if (m_activeWatchers)
m_watcherCreate.Start();
}
void watcherCreate_Disposed(object sender, EventArgs e)
{
if (m_activeWatchers)
m_watcherCreate.Start();
}
void watcherDelete_Disposed(object sender, EventArgs e)
{
if (m_activeWatchers)
m_watcherDelete.Start();
}
void watcherDelete_Stopped(object sender, StoppedEventArgs e)
{
if (m_activeWatchers)
m_watcherDelete.Start();
}
Now I'm dealing with an interesting problem, the stopped event fired -> and then there is there are the calls m_Create.Start(), m_Delete.Start() and then stopped event fired -> and so on until full quota...
Edit 2
Found this link ManagementEventWatcher stops raising EventArrived. with no helpful answer but with some hint-
Should I unregister WMI events when my program closes?
Any help?
Try this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
namespace EventWatcher
{
class Program
{
static void Main(string[] args)
{
StartMonitoringProcessCreation();
StartMonitoringProcessTermination();
Console.ReadLine();
}
private static void StartMonitoringProcessCreation()
{
ManagementEventWatcher startWatcher = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace");
startWatcher.EventArrived += new EventArrivedEventHandler(startWatcher_EventArrived);
startWatcher.Stopped += new StoppedEventHandler(startWatcher_Stopped);
startWatcher.Disposed += new EventHandler(startWatcher_Disposed);
startWatcher.Start();
}
private static void StartMonitoringProcessTermination()
{
ManagementEventWatcher stopWatcher = new ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace");
stopWatcher.EventArrived += new EventArrivedEventHandler(stopWatcher_EventArrived);
stopWatcher.Stopped += new StoppedEventHandler(stopWatcher_Stopped);
stopWatcher.Disposed += new EventHandler(stopWatcher_Disposed);
stopWatcher.Start();
}
static void startWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Got creation event.");
}
static void startWatcher_Stopped(object sender, StoppedEventArgs e)
{
Console.WriteLine("The startWatcher has stopped. Disposing it.");
((ManagementEventWatcher)sender).Dispose();
}
static void startWatcher_Disposed(object sender, EventArgs e)
{
Console.WriteLine("The startWatcher has been disposed. Restarting it.");
StartMonitoringProcessCreation();
}
static void stopWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Got termination event.");
}
static void stopWatcher_Stopped(object sender, StoppedEventArgs e)
{
Console.WriteLine("The stopWatcher has stopped. Disposing it.");
((ManagementEventWatcher)sender).Dispose();
}
static void stopWatcher_Disposed(object sender, EventArgs e)
{
Console.WriteLine("The stopWatcher has been disposed. Restarting it.");
StartMonitoringProcessTermination();
}
}
}
Edit: Because of what you've told me, it may just be easier for you to do something like this...
new Thread(() =>
{
while (true)
{
Process[] list = Process.GetProcessesByName("yourProcessName");
if (list.Length == 0)
Console.WriteLine("Not running.");
else
Console.WriteLine("Running.");
Thread.Sleep(1000);
}
}).Start()
Related
I have a pair of com ports.one of them sends data and the other one reads data. I want it to send a command (p) automatically every five seconds and wait to get the answer and read it and the sends the command again. Now it just sends the command automatically every 5 seconds. I don't know what to add to wait for the answer...
private Timer _timer;
public Form1()
{
InitializeComponent();
_timer = new Timer();
_timer.Interval = 5000;
_timer.Tick += _timer_Tick;
}
private void _timer_Tick(object sender , EventArgs e)
{
SendData();
}
private void Form1_Load(object sender, EventArgs e)
{
btnSendData.PerformClick();
}
private void btnSendData_Click(object sender, EventArgs e)
{
if (!_timer.Enabled)
{
SendData();
_timer.Enabled = true;
}
else
{
_timer.Enabled = false;
}
}
private void SendData()
{
if (serialPort1.IsOpen)
{
dataOut = "P<CR>";
serialPort1.Write(dataOut);
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
dataIn = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ShowData));
}
private void ShowData(object sender, EventArgs e)
{
tBoxDataIn.Text += dataIn;
}
I think this will be helpful:
async
await
Using async to create a task and then awaiting it is the way to go i think.
I've been trying to use a proxy on my webBrowser1.Navigate request using the following stackoverflow answer: https://stackoverflow.com/a/9036593/7443548
But this code would crash my for loop which I'm running in my own code.
How could I use a proxy for each request inside my code function?
Function which needs to use a proxy:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Uri currentUri = new Uri(bunifuMaterialTextbox1.Text);
int views = bunifuSlider1.Value;
for (int i = 0; i < views; i++)
{
webBrowser1.Navigate(currentUri);
System.Threading.Thread.Sleep(3000);
backgroundWorker.ReportProgress(i + 1);
}
}
My full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows.Forms;
namespace YoutubeViewBot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.WorkerReportsProgress = true;
}
youtubeViewBot youtubeBot = new youtubeViewBot();
List<string> proxyList = new List<string>();
private void bunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
private void bunifuImageButton2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void bunifuSlider1_ValueChanged(object sender, EventArgs e)
{
bunifuCustomLabel5.Text = bunifuSlider1.Value + " Views will be added.";
}
private void bunifuFlatButton3_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
proxyList = youtubeBot.getProxyList(openFileDialog1.FileName);
bunifuCustomLabel2.Text = proxyList.Count().ToString();
}
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
if (!backgroundWorker.IsBusy)
{
backgroundWorker.RunWorkerAsync();
}
else
{
MessageBox.Show("There is already a process running.", "YoutubeViewbot response");
}
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Uri currentUri = new Uri(bunifuMaterialTextbox1.Text);
int views = bunifuSlider1.Value;
for (int i = 0; i < views; i++)
{
webBrowser1.Navigate(currentUri);
System.Threading.Thread.Sleep(3000);
backgroundWorker.ReportProgress(i + 1);
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
bunifuCustomLabel7.Text = e.ProgressPercentage.ToString();
bunifuCustomLabel7.Update();
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bunifuCustomLabel9.Text = "Finished";
MessageBox.Show("Finished", "YoutubeViewBot response");
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
}
}
}
And here the code which I was trying to use:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows.Forms;
namespace YoutubeViewBot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.WorkerReportsProgress = true;
}
youtubeViewBot youtubeBot = new youtubeViewBot();
List<string> proxyList = new List<string>();
Uri currentUri;
private void bunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
private void bunifuImageButton2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void bunifuSlider1_ValueChanged(object sender, EventArgs e)
{
bunifuCustomLabel5.Text = bunifuSlider1.Value + " Views will be added.";
}
private void bunifuFlatButton3_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
proxyList = youtubeBot.getProxyList(openFileDialog1.FileName);
bunifuCustomLabel2.Text = proxyList.Count().ToString();
}
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
if (!backgroundWorker.IsBusy)
{
backgroundWorker.RunWorkerAsync();
}
else
{
MessageBox.Show("There is already a process running.", "YoutubeViewbot response");
}
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Uri currentUri = new Uri(bunifuMaterialTextbox1.Text);
int views = bunifuSlider1.Value;
for (int i = 0; i < views; i++)
{
Random rnd = new Random();
int r = rnd.Next(proxyList.Count);
string proxy = proxyList[r];
currentUri = new Uri(bunifuMaterialTextbox1.Text);
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(currentUri);
WebProxy myProxy = new WebProxy(proxy);
myRequest.Proxy = myProxy;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
webBrowser1.DocumentStream = myResponse.GetResponseStream();
webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
backgroundWorker.ReportProgress(i + 1);
}
}
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (e.Url.AbsolutePath != "blank")
{
currentUri = new Uri(currentUri, e.Url.AbsolutePath);
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(currentUri);
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
webBrowser1.DocumentStream = myResponse.GetResponseStream();
e.Cancel = true;
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
bunifuCustomLabel7.Text = e.ProgressPercentage.ToString();
bunifuCustomLabel7.Update();
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bunifuCustomLabel9.Text = "Finished";
MessageBox.Show("Finished", "YoutubeViewBot response");
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
}
}
}
Steps it should do:
On click on the button: bunifuFlatButton2_Click it should start the backgroundWorker_DoWork functon
backgroundWorker_DoWork should run the loop x times and for each run it should attach a new proxy to the request
I would appreciate any kind of help.
Edit 1:
While debugging step by step, I realized the for loop crashes after running the second time on the following line:
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Video can be seen here:
https://www.youtube.com/watch?v=H3y2jFvuK3M
It finished after running the for loop twice instead of 454 times.
I'm having a problem using WebSocket4Net library.
I have the event websocket_opened and when this event is raised on open if I don't send any messages I have an Exception
System.Exception : You must send data by websocket after websocket is
opened
After I send this message I can't send any other messages. I execute the send command but I have no exceptions and it isn't working and If I check the state the websocket is open
If I close the Socket on the opened event and open it again in the closed_event I can send another message without problems.
So, if I want to send multiple messages I have to disconnect after sending a message and reconnect again to send the next message.
private static void websocket_Opened(object sender, EventArgs e)
{
websocket.Send(msg);
websocket.Close();
}
private static void websocket_Closed(object sender, EventArgs e)
{
websocket.Open();
}
Is this normal? Can you help me with this please?
I had a similar questions when I first time used WebSocket4Net.
A good thing about this library that it has a repository on github with many examples of use (tests). These tests was very helpful for me to understand how it should work.
UPDATE:
I saw Fred's comment below and I think I really need to add an example.
So here is it, I've used this api:
using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocket4Net;
namespace TestProj
{
public class WebSocketTest
{
static string webSocketUri = "wss://ws.binaryws.com/websockets/v3?app_id=1089";
static void Main(string[] args)
{
var socketManager = new WebSocketManager(webSocketUri);
socketManager.Send("{\"time\": 1}");
socketManager.Send("{\"ping\": 1}");
socketManager.Close();
Console.WriteLine("Console can be closed...");
Console.ReadLine();
}
}
public class WebSocketManager
{
private AutoResetEvent messageReceiveEvent = new AutoResetEvent(false);
private string lastMessageReceived;
private WebSocket webSocket;
public WebSocketManager(string webSocketUri)
{
Console.WriteLine("Initializing websocket. Uri: " + webSocketUri);
webSocket = new WebSocket(webSocketUri);
webSocket.Opened += new EventHandler(websocket_Opened);
webSocket.Closed += new EventHandler(websocket_Closed);
webSocket.Error += new EventHandler<ErrorEventArgs>(websocket_Error);
webSocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
webSocket.Open();
while (webSocket.State == WebSocketState.Connecting) { }; // by default webSocket4Net has AutoSendPing=true,
// so we need to wait until connection established
if (webSocket.State != WebSocketState.Open)
{
throw new Exception("Connection is not opened.");
}
}
public string Send(string data)
{
Console.WriteLine("Client wants to send data:");
Console.WriteLine(data);
webSocket.Send(data);
if (!messageReceiveEvent.WaitOne(5000)) // waiting for the response with 5 secs timeout
Console.WriteLine("Cannot receive the response. Timeout.");
return lastMessageReceived;
}
public void Close()
{
Console.WriteLine("Closing websocket...");
webSocket.Close();
}
private void websocket_Opened(object sender, EventArgs e)
{
Console.WriteLine("Websocket is opened.");
}
private void websocket_Error(object sender, ErrorEventArgs e)
{
Console.WriteLine(e.Exception.Message);
}
private void websocket_Closed(object sender, EventArgs e)
{
Console.WriteLine("Websocket is closed.");
}
private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine("Message received: " + e.Message);
lastMessageReceived = e.Message;
messageReceiveEvent.Set();
}
}
}
i think that this will resolve your problem
websocket.Open();
private static void websocket_Opened(object sender, EventArgs e)
{
websocket.Send(msg);
websocket.Close();
}
private static void websocket_Closed(object sender, EventArgs e)
{
//DO SOMETHINGS
}
I have a Form where one can Sign In and it could take a while till the data gets loaded into the Form. So I wanted to create a seperate Form (loadScreen.cs) with a Progress Bar when the Form is loading. I tried this in the loadScreen.cs Form:
private void Form1_Load(object sender, EventArgs e)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged +=
new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
int percentFinished = (int)e.Argument;
while (!worker.CancellationPending && percentFinished < 100)
{
percentFinished++;
worker.ReportProgress(percentFinished);
System.Threading.Thread.Sleep(50);
}
e.Result = percentFinished;
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
I've read that the worker_DoWork method should have the code which takes longer to load. I don't know how to handle this since my button is in Form1. When it's clicked then I go to another class with
private void signIn_Click(object sender, EventArgs e)
{
var logIn = new LogIn(this);
logIn.checkUserInput(this);
}
and there I execute the operations which load certain things. How to connect everything? I need help!
I'm actually in the process of creating a general-purpose dialogue for this sort of thing. It's not going to be ready in time to be of use to you but I would suggest that you go along similar lines. Create your "Loading" dialogue so that it accepts a delegate and invokes it in the DoWork event handler. The main form can then contain a method that does the work and you can pass a delegate for that method to the dialogue. I'll post a very basic example.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable table;
private void button1_Click(object sender, EventArgs e)
{
var work = new Action(GetData);
using (var f2 = new Form2(work))
{
f2.ShowDialog();
this.dataGridView1.DataSource = this.table;
}
}
private void GetData()
{
this.table = new DataTable();
using (var adapter = new SqlDataAdapter("SELECT * FROM MyTable", "connectionstring here"))
{
adapter.Fill(table);
}
}
}
public partial class Form2 : Form
{
private Action work;
public Form2(Action work)
{
InitializeComponent();
this.work = work;
}
private void Form2_Load(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.work();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.DialogResult = DialogResult.OK;
}
}
Note that there's no real way to measure progress when using a data adapter so you could only really display a marquee progress bar in this case.
Trying to develop small application using GsmComm Library.
At the moment a have some problems with detecting if phone is connected or no.
it's detects when phone is disconnected, but doesn't want to detect phone when is connected back again ...
Any idea why ?
my code:
GsmCommMain gsm = new GsmCommMain(4, 115200, 200);
private void Form1_Load(object sender, EventArgs e)
{
gsm.PhoneConnected += new EventHandler(gsmPhoneConnected);
gsm.PhoneDisconnected += new EventHandler(gsmPhoneDisconnected);
gsm.Open();
}
private delegate void ConnctedHandler(bool connected);
private void onPhoneConnectedChange(bool connected)
{
try
{
if (connected)
{
phoneStatus.Text = "OK";
}
else
{
phoneStatus.Text = "NG";
}
}
catch (Exception exce)
{
logBox.Text += "\n\r" + exce.ToString();
}
}
public void gsmPhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { true });
}
private void gsmPhoneDisconnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { false });
}
Sorry for late answer. Just noticed your question.
There is no need to use EventHandler for connection. If you want to call some functions after phone/gsm modem is connected you should call them after you opened port and (!) checked whether connection is established using IsConnected() member function in GsmCommMain class.
var gsm = new GsmCommMain(4, 115200, 200);
private void Form1_Load(object sender, EventArgs e)
{
//gsm.PhoneConnected += new EventHandler(gsmPhoneConnected); // not needed..
gsm.PhoneDisconnected += new EventHandler(gsmPhoneDisconnected);
gsm.Open();
if(gsm.IsConnected()){
this.onPhoneConnectedChange(true);
}
}
private delegate void ConnctedHandler(bool connected);
private void onPhoneConnectedChange(bool connected)
{
try
{
if (connected)
{
phoneStatus.Text = "OK";
}
else
{
phoneStatus.Text = "NG";
}
}
catch (Exception exce)
{
logBox.Text += "\n\r" + exce.ToString();
}
}
/*public void gsmPhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { true });
}*/
private void gsmPhoneDisconnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { false });
}