Websocket-sharp not raising OnOpen event upon opening websocket - c#

I'm in the early stages of writing a program to interface with an IP camera. A bit of code I wrote yesterday worked, but when I came back to it this morning it didn't. I know, I probably did something, but to the best of my memory it worked when I clicked debug before leaving and didn't when I clicked debug when I came in. I even left my computer on with VS running overnight (which I almost never do, and I have restarted since) so I could it and all my internet tabs as I left them. The computer was locked, so unless some very resourceful individual decided to mess with me, nothing changed overnight.
I'm using websocket-sharp, and when I connect to the websocket (which does seem to happen successfully), the OnOpen event isn't raised.
The bit where websocket-sharp raises the event is in the following lines.
private void open ()
{
_inMessage = true;
startReceiving ();
try {
OnOpen.Emit (this, EventArgs.Empty);
}
catch (Exception ex) {
_logger.Error (ex.ToString ());
error ("An error has occurred during the OnOpen event.", ex);
}
It reaches the OnOpen.Emit, and doesn't throw the exception, so it seems to think it's raising the event. Event is seen below
public event EventHandler OnOpen;
It does not seem to reach this line as when I put a breakpoint there it isn't paused. I've never used the .Emit way of raising events before, and not finding much in research, so maybe somethings is going wrong there?
My code is below.
public Form1()
{
InitializeComponent();
this.Shown += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, EventArgs e)
{
using (var ws = new WebSocket("ws://169.254.101.183"))
{
ws.OnMessage += (sender2, e2) =>
textBox1.Text = e2.Data.ToString();
ws.Connect();
ws.OnOpen += (sender2,e2) =>
textBox1.Text = "connected";
/*ws.OnError += (sender2, e2) =>
textBox1.Text = e2.Message;*/
//textBox1.Text = ".";
}
}
Is there any obvious reason that OnOpen.Emit should not actually raise the OnOpen event?

In your case the real reason is this line
using (var ws = new WebSocket("ws://169.254.101.183"))
When your block ends 'ws' object becomes disposed including your event handler. After some delay you have response from WebSocket, but handler already destroyed.

In the MainWindow_Loaded method are you calling Connect before you subscribe to the OnOpen event.
If you subscribe to the event before calling Connect then the textBox1.Text should be set to "connected" after a successful connection.

Related

Joining a worker thread in a windows forms app

My program works like this:
I press a radio button which opens the port.
Next i press a button "Read" which starts a thread that reads data continously from the Serial Port using port.ReadLine() and prints it in a textbox;
I have another radio which should first join the thread and after that close the port;the problem is the printing goes well until i close the port when the UI freezes.
public Form1()
{
mythread = new Thread(ReadFct);
myPort = new SerialPort("COM3", 9600);
myPort.ReadTimeout = 3500;
InitializeComponent();
foreach (var t in Constants.ComboParameters)
this.paramCombo.Items.Add(t);
radioClose.CheckedChanged += new EventHandler(radioButtonCheckedChanged);
radioOpen.CheckedChanged += new EventHandler(radioButtonCheckedChanged);
}
Below is the function attached to the thread
void ReadFct()
{
string aux = "";
while (readCondition)
{
if (myPort.IsOpen)
aux = myPort.ReadLine();
this.SetText(aux);
}
}
Below is the radio button event handler
public void radioButtonCheckedChanged(object sender,EventArgs e)
{
if (radioOpen.Checked && !myPort.IsOpen)
try
{
myPort.Open();
mythread.Start();
}
catch (Exception)
{
MessageBox.Show("Nu s-a putut deschide port-ul");
}
if (radioClose.Checked && myPort.IsOpen)
{
readCondition = false;
mythread.Join();
myPort.Close();
// myPort.DataReceived -= DataReceivedHandler;
}
}
The read button function:
private void readbtn_Click(object sender, EventArgs e)
{
if (!myPort.IsOpen)
MessageBox.Show("PORT NOT OPENED!");
else
{
// myPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
readCondition = true;
if (!mythread.IsAlive)
{
mythread = new Thread(ReadFct);
mythread.Start();
}
}
I have used what MSDN suggest when changing control from another thread:
private void SetText(string text)
{
if (this.textBox1.InvokeRequired)
{
StringTb del = new StringTb(SetText);
this.Invoke(del, new object[] { text });
}
else
SetData = text;
}
It's hard to know exactly what you need, lacking a good Minimal, Complete, and Verifiable code example to illustrate the question. That said, the issue here is that the Thread.Join() method causes that thread to stop doing any other work, and the thread you use to call that method is the thread that handles all of the user interface. Worse, if your port never receives another newline, the thread you're waiting on will never terminate, because you're stuck waiting on the ReadLine() method. Even worse, even if you do get a newline, if that happens while you're stuck waiting on the Thread.Join(), the call to Invoke() will deadlock, because it needs the UI thread to do its work, and the Thread.Join() call is preventing it from getting the UI thread.
In other words, your code has multiple problems, any one of which could cause problems, but all of which together mean it just can't possibly work.
There are a variety of strategies to fix this, but IMHO the best is to use await. The first step in doing that is to change your I/O handling so that it's done asynchronously instead of dedicating a thread to it:
// Ideally, you should rename this method to "ReadFctAsync". I am leaving
// all names intact for the same of the example though.
async Task ReadFct()
{
string aux = "";
using (StreamReader reader = new StreamReader(myPort.BaseStream))
{
while (true)
{
aux = await reader.ReadLineAsync();
// This will automatically work, because the "await" will automatically
// resume the method execution in the UI thread where you need it.
this.SetText(aux);
}
}
}
Then, instead of creating a thread explicitly, just create a Task object by calling the above:
public Form1()
{
// In this approach, you can get rid of the "mythread" field altogether
myPort = new SerialPort("COM3", 9600);
myPort.ReadTimeout = 3500;
InitializeComponent();
foreach (var t in Constants.ComboParameters)
this.paramCombo.Items.Add(t);
radioClose.CheckedChanged += new EventHandler(radioButtonCheckedChanged);
radioOpen.CheckedChanged += new EventHandler(radioButtonCheckedChanged);
}
public async void radioButtonCheckedChanged(object sender,EventArgs e)
{
if (radioOpen.Checked && !myPort.IsOpen)
{
try
{
myPort.Open();
await ReadFct();
// Execution of this method will resume after the ReadFct() task
// has completed. Which it will do only on throwing an exception.
// This code doesn't have any continuation after the "await", except
// to handle that exception.
}
catch (Exception)
{
// This block will catch the exception thrown when the port is
// closed. NOTE: you should not catch "Exception". Figure out what
// *specific* exceptions you expect to happen and which you can
// handle gracefully. Any other exception can mean big trouble,
// and doing anything other than logging and terminating the process
// can lead to data corruption or other undesirable behavior from
// the program.
MessageBox.Show("Nu s-a putut deschide port-ul");
}
// Return here. We don't want the rest of the code executing after the
// continuation, because the radio button state might have changed
// by then, and we really only want this call to do work for the button
// that was selected when the method was first called. Note that it
// is probably even better if you just break this into two different
// event handlers, one for each button that might be checked.
return;
}
if (radioClose.Checked && myPort.IsOpen)
{
// Closing the port should cause `ReadLineAsync()` to throw an
// exception, which will terminate the read loop and the ReadFct()
// task
myPort.Close();
}
}
In the above, I have completely ignored the readbtn_Click() method. Lacking a good MCVE, it's not clear what role that button plays in the overall scheme. You seem to have a radio button group (of two buttons) that control whether the port is open or closed. It is not clear why then you have an additional regular button that is seemingly able to also open the port and start reading, independently of the radio group.
If you want that extra button, it seems to me that all it ought to do is change the radio group state, by checking the "open" radio button. Then let the radio group buttons handle the port state and reading. If you need more specific advice as to how to fully integrate my code example above with your entire UI, you will need to provide more detail, preferably in a new question. That new question must include a good MCVE.

Unexpected behavior in async method

I am currently experiencing some unexpected/unwanted behavior with an aync method I am trying to use. The async method is RecognizeAsync. I am unabled to await this method since it returns void. What is happening, is that ProcessAudio method will be called first and will seemingly run to completion however the webpage never returns my "Contact" view as it should or errors out. After the method runs to completion, the breakpoints in my handlers start being hit. If I let it play through to completion, no redirect will ever happen- in the network tab in chrome debugger, the "status" will stay marked as pending and just hang there. I believe my issue is being caused by issues with asynchronousity but have been unable to found out what exactly it is.
All help is appreciated.
[HttpPost]
public async Task<ActionResult> ProcessAudio()
{
SpeechRecognitionEngine speechEngine = new SpeechRecognitionEngine();
speechEngine.SetInputToWaveFile(Server.MapPath("~/Content/AudioAssets/speechSample.wav"));
var grammar = new DictationGrammar();
speechEngine.LoadGrammar(grammar);
speechEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(SpeechRecognizedHandler);
speechEngine.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(SpeechHypothesizedHandler);
speechEngine.RecognizeAsync(RecognizeMode.Multiple);
return View("Contact", vm); //first breakpoint hit occurs on this line
//but it doesnt seem to be executed?
}
private void SpeechRecognizedHandler(object sender, EventArgs e)
{
//do some work
//3rd breakpoint is hit here
}
private void SpeechHypothesizedHandler(object sender, EventArgs e)
{
//do some different work
//2nd breakpoint is hit here
}
UPDATE: based on suggestions, I have changed my code to (in ProcessAudio):
using (speechEngine)
{
speechEngine.SetInputToWaveFile(Server.MapPath("~/Content/AudioAssets/speechSample.wav"));
var grammar = new DictationGrammar();
speechEngine.LoadGrammar(grammar);
speechEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(SpeechRecognizedHandler);
speechEngine.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(SpeechHypothesizedHandler);
var tcsRecognized = new TaskCompletionSource<EventArgs>();
speechEngine.RecognizeCompleted += (sender, eventArgs) => tcsRecognized.SetResult(eventArgs);
speechEngine.RecognizeAsync(RecognizeMode.Multiple);
try
{
var eventArgsRecognized = await tcsRecognized.Task;
}
catch(Exception e)
{
throw (e);
}
}
and this is resulting in some wrong behavior:
The return View("Contact",vm) breakpoint will now be hit AFTER the handlers are finished firing however there is still no redirect that ever happens. I am never directed to my Contact page. I just si ton my original page indefinitely just like before.
You're going too early. The speech engine probably hasn't even started by the time you hit the return View line.
You need to wait until the final event is fired from the speech engine. The best approach would be to convert from the event based asynchrony to TAP-based asynchrony.
This can be achieved by using TaskCompletionSource<T>
Let's deal with (what I believe) should be the last event to fire after speechEngine.RecognizeAsync is called, i.e. SpeechRecognized. I'm assuming that this is the event that fires when the final result has been calculated by the speech engine.
So, first:
var tcs = new TaskCompletionSource<EventArgs>();
now lets hook it up to complete when SpeechRecognized is fired, using inline lambda-style method declaration:
speechEngine.SpeechRecognized += (sender, eventArgs) => tcs.SetResult(eventArgs);
(...wait... what happens if no speech was recognized? We'll also need to hook up the SpeechRecognitionRejected event and define a custom Exception subclass for this type of event... here I'll just call it RecognitionFailedException. Now we're trapping all possible outcomes of the recognition process, so we would hope that the TaskCompletionSource would complete in all outcomes.)
speechEngine.SpeechRecognitionRejected += (sender, eventArgs) =>
tcs.SetException(new RecognitionFailedException());
then
speechEngine.RecognizeAsync(RecognizeMode.Multiple);
now, we can await the Task property of our TaskCompletionSource:
try
{
var eventArgs = await tcs.Task;
}
catch(RecognitionFailedException ex)
{
//this would signal that nothing was recognized
}
do some processing on the EventArgs that is the Task's result, and return a viable result back to the client.
In the process of doing this, you are creating IDisposable instances that will need to be properly disposed.
So:
using(SpeechRecognitionEngine speechEngine = new SpeechRecognitionEngine())
{
//use the speechEngine with TaskCompletionSource
//wait until it's finished
try
{
var eventArgs = await tcs.Task;
}
catch(RecognitionFailedException ex)
{
//this would signal that nothing was recognized
}
} //dispose
if anyone is curious- i solved my issue by doing the following:
I changed to using Recognize() instead of RecognizeAsync(..) which lead to InvalidOperationException due to async events trying to be executed at an "invalid time in the pages lifecycle". To overcome this, I wrapped my operations in a thread and joined the thread back to the main thread directly after running it. Code below:
using (speechEngine)
{
var t = new Thread(() =>
{
speechEngine.SetInputToWaveFile(#"C:\AudioAssets\speechSample.wav");
speechEngine.LoadGrammar(dictationGrammar);
speechEngine.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(SpeechRecognizedHandler);
speechEngine.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(SpeechHypothesizedHandler);
speechEngine.Recognize();
});
t.Start();
t.Join();
}
}

Calling the pose triggered event using Myo arm band

I'm developing a project in WPF using a Myo arm band which works so far in recognizing the device has connected and updates info to the textbox, but when I set up the event handler for recognizing if a pose is triggered the event never fires.
I debugged this by making poses with the device and holding them, also I set a break point on this line pose.Triggered += Pose_Triggered; and the start of the pose triggered event.
The break point triggers on the first line where the but it doesn't trigger the breakpoint on the actual event private void Pose_Triggered(object sender, PoseEventArgs e)
This is the C# wrapper I'm using for the project: https://github.com/tayfuzun/MyoSharp
Does anyone know why the event doesn't trigger although the poses are being made?
This is the method where pose_triggered is called and the event:
// listen for when the Myo connects
hub.MyoConnected += (sender, e) =>
{
this.Dispatcher.Invoke((Action)(() =>
{
statusTbx.Text = "Myo has connected! " + e.Myo.Handle;
e.Myo.Vibrate(VibrationType.Short);
// unlock the Myo so that it doesn't keep locking between our poses
e.Myo.Unlock(UnlockType.Hold);
// setup for the pose we want to watch for
var pose = HeldPose.Create(e.Myo, Pose.Fist);
pose.Triggered += Pose_Triggered;
e.Myo.OrientationDataAcquired += Myo_OrientationDataAcquired;
}));
};
Code for triggered event:
private void Pose_Triggered(object sender, PoseEventArgs e)
{
App.Current.Dispatcher.Invoke((Action)(() =>
{
//need to measure abduction of arm from 0 to 180 degrees.
poseStatusTbx.Text = "{0} arm Myo holding pose {1}" + e.Myo.Arm + e.Myo.Pose;
pitch = pitchCentre;
}));
}
Here is the complete code for the class: http://hastebin.com/xinirugufo.cs
I compare the sample code from GitHub and your. Did you forget to call pose.Start()?
var pose = HeldPose.Create(e.Myo, Pose.Fist);
pose.Interval = TimeSpan.FromSeconds(0.5);
pose.Start(); //this???
pose.Triggered += Pose_Triggered;

Backgroundworker is always busy

I'm new to using event handlers and backgroundworkers, so I may be missing something completely obvious here. Still, I've been trying to fix this for two days, so I thought I might as well see what anyone had to say.
I have a backgroundworker called SqlExpressDownloader. It starts running at the beginning of my program, the rest of the work runs, and then it should wait for the operations in the SqlExpressDownloader_DoWork() method to complete before continuing. The only problem is that for some reason whenever I do while(SqlExpressDownloader.IsBusy), it always responds as busy and therefore will wait forever.
The code for the event handler is here:
private void SqlExpressDownloader_DoWork(object sender, DoWorkEventArgs e)
{
string sSource = string.Format("{0}\\{1}", Paths.Settings_Common, "sqlexpr_x64_enu.exe");
Debug.WriteLine(sSource);
Debug.WriteLine("http://www.elexioamp.com/Install/redistributables/sql2008r2express/sqlexpr_x64_enu.exe");
if (!System.IO.File.Exists(sSource))
{
WebClient oWebClient = new WebClient();
oWebClient.DownloadProgressChanged += DownloadProgressChanged;
oWebClient.DownloadDataCompleted += DownloadComplete;
oWebClient.DownloadFileAsync(new System.Uri("http://www.elexioamp.com/Install/redistributables/sql2008r2express/sqlexpr_x64_enu.exe"), sSource);
while (oWebClient.IsBusy)
{
Thread.Sleep(100);
}
e.Result = "";
DownloadFinished = true;
}
}
I have watched the code and have watched it complete this method. I even added a return after the DownloadFinished = true, but it still responds as busy. What I want to know is how to make the backgroundworker respond as not busy.
EDIT
The events are all added in the constructor as shown here:
SqlExpressDownloader = new BackgroundWorker();
SqlExpressDownloader.DoWork += new DoWorkEventHandler(this.SqlExpressDownloader_DoWork);
SqlExpressDownloader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.SqlExpressDownloader_RunWorkerCompleted);
The RunWorkerCompleteEventHandler looks like this:
private void SqlExpressDownloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Debug.WriteLine("The actions are complete.");
}
else
{
Debug.WriteLine("Error in completed work.");
}
}
But, when I debugged it last, it didn't actually trigger.
Instead of querying SqlExpressDownloader.IsBusy in a loop, try subscribing to the RunWorkerCompleted event of the BackgroundWorker and place your code in there that should only occur after the DoWork event has completed.
You'll also have access to the RunWorkerCompletedEventArgs, which you can check to make sure no error was thrown from the DoWork portion of your BackgroundWorker.
...
...
SqlExpressDownloader.RunWorkerCompleted += SqlExpressDownloader_RunWorkerCompleted;
SqlExpressDownloader.RunWorkerAsync();
}
private void SqlExpressDownloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
// do something in response to the error
}
// stuff to do after DoWork has completed
}
I found Joe Albahari's tutorial helpful when I was learning how to use these.
You can replace your code with more elegant async/await solution like this
private async Task SqlExpressDownloadAsync()
{
string sSource = string.Format("{0}\\{1}", Paths.Settings_Common, "sqlexpr_x64_enu.exe");
Debug.WriteLine(sSource);
Debug.WriteLine("http://www.elexioamp.com/Install/redistributables/sql2008r2express/sqlexpr_x64_enu.exe");
if (!System.IO.File.Exists(sSource))
{
WebClient oWebClient = new WebClient();
oWebClient.DownloadProgressChanged += DownloadProgressChanged;
oWebClient.DownloadDataCompleted += DownloadComplete;
await oWebClient.DownloadFileTaskAsync(new System.Uri("http://www.elexioamp.com/Install/redistributables/sql2008r2express/sqlexpr_x64_enu.exe"), sSource);
}
}
I had a similar issue. DownloadASync would fire but .IsBusy would always stay on true.
This probably won't be a common problem, just thought I share my resolution.
I used
MessageBox.Show(new Form() { TopMost = true }, "", "")
This was the cause. I also tried:
var t = new Form() { TopMost = true };
MessageBox.Show(t, "", "");
t.Dispose();
This caused the same issue.
My code had multiple threads, I assume one of them must have gotten stuck, or perhaps the MessageBox(the new Form() { TopMost = true; } ) call created a stuck thread.
As soon as I removed that part, eg.
MessageBox.Show("", "");
Everything worked as expected again.
So maybe you are creating another thread somewhere that is causing your issue.

SqlDependency OnChange Not Firing

This is the first time I've ever needed to use an SqlDependency so I am hoping that its a stupid mistake I've made.
The problem I'm having is that the OnChanged event doesn't fire when the sql table changes. No errors or anything just it doesn't fire.
Here is the code
public class SqlWatcher
{
private const string SqlConnectionString = "Data Source = CN-PC08\\DEV; Initial Catalog=DEP; User = sa; Password=******";
public SqlWatcher()
{
SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
perm.Demand();
SqlCommand cmd = new SqlCommand("SELECT [DataAvaliable], [RowNumber] FROM [dbo].[Trigger]", new SqlConnection(SqlConnectionString));
SqlDependency sqlDependency = new SqlDependency(cmd);
sqlDependency.OnChange += On_SqlBitChanged;
}
private void On_SqlBitChanged(object sender, SqlNotificationEventArgs sqlNotificationEventArgs)
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= On_SqlBitChanged;
// Fire the event
if (NewMessage != null)
{
NewMessage(this, new EventArgs());
}
}
public void Start()
{
SqlDependency.Start(SqlConnectionString);
}
public void Stop()
{
SqlDependency.Stop(SqlConnectionString);
}
public event EventHandler NewMessage;
And in my main window I have this
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
try
{
SqlWatcher sqlWatcher = new SqlWatcher();
sqlWatcher.Start();
sqlWatcher.NewMessage += On_NewMessage;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void On_NewMessage(object sender, EventArgs eventArgs)
{
MessageBox.Show("Message Received");
}
}
So the expected behaviour is that if I run the following sqlQuery a messageBox will be displayed saying "Message Received"
INSERT INTO [DEP].[dbo].[Trigger] Values(0,3)
Could anyone give me a hint on what to check/change?
I'm aware that only a subset of Sql features can be used in dependencies but I don't think I'm trying to do anything to fancy here.
I'm hoping that its a stupid mistake I've made.
Unfortunately (or fortunately?) you are making several mistakes.
First is you need to understand that Query Notifications will invalidate one query. So you will only be notified at most once and you have to re-subscribe again (re-submit the query) if you want to receive further notifications.
Next you need to understand that you will be notified for any reason, not only for changes. In your callback you must check the reason you're notified, which are passed in via the SqlNotificationEventArgs.
Next you need to understand asynchronous programming basic principles: if you subscribe for an event make sure you subscribe before the event can happen first time. Case in point: the On_SqlBitChanged can fire as soon as you submit the query. This should happen in the SqlWatcher.SqlWatcher constructor, but you subscribe to the sqlWatcher.NewMessage after the constructor runs. On_SqlBitChanged can be invoked between the constructor finishes before you hook up the NewMessage event callback in which case the notification is silently ignored.
If you want to use a service make sure you start it before you use it. You are using SqlDependency in SqlWatcher.SqlWatcher but you start it after that when you call SqlWatcher.Start().
Finally, if you want to be notified of changes on a query you have to submit the query. You are constructing the SqlCommand object, set up the notification and then... discard the object. Unless you actually submit the query, you did not yet subscribed to anything.
Suggestions for fix:
Make Start and Stop statics, call Start in application start up.
Make sure you subscribe to NewMessage before you submit the query
Actually submit the query (call SqlComamnd.ExecuteQuery())
Inspect the Info, Type and Source in the On_SqlBitChanged callback, if your submission contains an error this is the only way to learn (the SqlComamnd.ExecuteQuery() will succeed even if the notification request is invalid)
You must re-subscribe once you're notified of a change, execute the query again.
One more thing: don't invoke UI code in background callbacks. You cannot call MessageBox.Show("Message Received"); from a callback, you must route through the form main thread via Form.Invoke. YEs, I know that strictly speaking MessageBox.Show does work on a non-UI thread but you will soon move away from alert boxes to actually form interaction and then things will break.

Categories