I Have Code for EventHandler like this below.
void ConnectionManager_Error(object sender, EventArgs<string> e)
{
BeginInvoke((MethodInvoker)delegate()
{
State = ConnectState.NotFound;
MessageBox.Show(e.Value);
});
}
My Problem:
MessageBox never appears even when the device is not connected to the computer.
I think that comes MessageBox supposed that show error messages.
Can someone show me what is wrong?
Note:
I have this code that I thought would trigger ConnectionManager Error EventHandler.
private void LogError(string error)
{
if (Error != null)
Error(this, new EventArgs<string>(error));
}
I also have this code that gives an error message containing the string to LogError method.
int lasterror = Marshal.GetLastWin32Error();
if (lasterror != 0)
LogError("Bluetooth API returned: " + lasterror.ToString());
or
if (BluetoothSetServiceState(IntPtr.Zero, ref device, ref HumanInterfaceDeviceServiceClass_UUID, BLUETOOTH_SERVICE_ENABLE) != 0)
LogError("Failed to connect to wiimote controller");
Another Hint
To be more specific, I also already have the code below:
public event EventHandler<EventArgs<string>> Error;
and
ConnectionManager.Error += new EventHandler<EventArgs<string>>(ConnectionManager_Error);
And also this class:
public class EventArgs<T> : EventArgs
{
public T Value
{
get;
set;
}
public EventArgs(T value)
: base()
{
Value = value;
}
}
Is it standard BeginInvoke that executes code in the separate thread?
You have to work with GUI methods only in GUI thread.
To switch to the GUI thread please try Control.IsInvokeRequired and Control.Invoke methods.
Related
I have a page - Page A, that has a method that subscribes to an event on another page - Page B. I figured I could instantiate Page B in my code in Page A before having my method in Page A subscribe to the event in Page B, and then finally pushing Page B to the navigation stack.
Unfortunately, I keep getting a NullReferenceException on the line in which the method subscribes to the event when I test my application on iOS. The code runs perfectly fine when I deploy and test as an Android application, but I always get the NullReferenceException on iOS. What's causing this exception to be thrown, and how can I fix it? Why is it platform specific to iOS?
Code on Page A
var confirmationPage = new EmailConfirmationPage(username);
confirmationPage.EmailConfirmed += this.OnEmailConfirmed;
await this.Navigation.PushModalAsync(confirmationPage);
...
private void OnEmailConfirmed(object source, EventArgs args)
{
this.LabelMessage.Text = "Email Confirmed!";
}
Code on Page B
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace appFBLA2019
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EmailConfirmationPage : ContentPage
{
private string username;
private string email;
public delegate void EmailConfirmedEventHandler(object source, EventArgs args);
public event EmailConfirmedEventHandler EmailConfirmed;
public EmailConfirmationPage(string username)
{
InitializeComponent();
this.username = username;
this.LabelTitle.Text = "Loading...";
GetEmail();
}
private void GetEmail()
{
try
{
ServerConnector.QueryDB($"getEmail/{this.username}/-");
this.email = ServerConnector.ReceiveFromDB();
this.LabelTitle.Text = $"Enter the confirmation code sent to {this.email.Split('/')[1]}";
}
catch
{
this.LabelMessage.Text = "Connection Error: Please Try Again.";
}
}
private async void ButtonConfirmEmail_Clicked(object sender, EventArgs e)
{
try
{
string userInputToken = this.EntryConfirmationCode.Text.Trim();
ServerConnector.QueryDB($"confirmEmail/{this.username}/{userInputToken}/-");
string returnData = ServerConnector.ReceiveFromDB();
if (returnData == "true/-")
{
OnEmailConfirmed();
await this.Navigation.PopModalAsync(true);
}
else
{
this.LabelMessage.Text = "Email could not be confirmed. Please try your code again.";
}
}
catch
{
this.LabelMessage.Text = "Connection Error: Please try again.";
}
}
private void ButtonFixEmail_Clicked(object sender, EventArgs e)
{
string newEmail = this.EntryChangeEmail.Text;
ServerConnector.QueryDB($"changeEmail/{this.username}/{newEmail}/-");
string result = ServerConnector.ReceiveFromDB();
if (result == "true/-")
{
this.LabelMessage.Text = $"Enter the confirmation code sent to {newEmail}";
}
else
{
this.LabelMessage.Text = $"Email could not be changed: {result.Split('/')[1]}";
}
}
private async void ButtonClose_Clicked(object sender, EventArgs e)
{
await this.Navigation.PopModalAsync(true);
}
protected virtual void OnEmailConfirmed()
{
EmailConfirmed?.Invoke(this, EventArgs.Empty);
}
}
}
Call Stack before subscribing method to event:
0xC0 in appFBLA2019.CreateAccountPage.ButtonCreateAccount_Clicked at C:\Users\chung\source\repos\appFBLA2019\appFBLA2019\appFBLA2019\CreateAccountPage.xaml.cs:30,21 C#
Call stack after subscribing method to event:
0x1B8 in appFBLA2019.CreateAccountPage.ButtonCreateAccount_Clicked at C:\Users\chung\source\repos\appFBLA2019\appFBLA2019\appFBLA2019\CreateAccountPage.xaml.cs:39,13 C#
Upon further testing, I noticed that this issue occurs on both iOS and Android, but ONLY when running the application with Xamarin Live Player. I contacted Microsoft and they pointed out that Xamarin Live Player unfortunately has limitations. Deploying directly to a device causes no issues, and the code runs fine.
So I am just messing around here nothing production just proof of concept with my first ever Windows Service.
I am trying to essentially create a windows service that sits as the listener for a signalr connection. In essence, I will have a windows application and a windows service. The win service will handle connecting to the signalr hub and on signalr calls fire an event. The windows application will listen for these events and perform actions based on them.
Currently I cannot get this to work. I have never worked with events, or windows services before. In my windows application my events never hit their break points, as well I log an error of null reference exception from the
ConnectToHub()
Alright if I comment out the OnConnected() method call I log a successful connection to the hub. I have never worked with events before so is my mistake with the events?
I debated that this approach was a bit overkill. However, for me it was a proof of concept that I could find a use for a long running windows service, and adding some events into the mix.
Code for service:
public delegate void MessageRecievedEventHanlder(object sender, MessageRecievedArgs e);
public delegate void ConnectedToHubEventHandler(object sender, ConnectedArgs e);
public partial class SignalRService : ServiceBase
{
IHubProxy _hub;
HubConnection connection;
string url = #"http://localhost:8080/";
private Message LastMessage;
public static event MessageRecievedEventHanlder NewMessage;
protected virtual void OnNewMessage(MessageRecievedArgs e)
{
NewMessage(null, e);
}
public static event ConnectedToHubEventHandler Connected;
protected virtual void OnConnected(ConnectedArgs e) {
System.IO.File.WriteAllText(#"C:\Users\Bailey Miller\Desktop\FTP\Logg.txt", "Hit OnConnected " + e.Success +" " + Connected != null ? "Isn't null" : "Null event");
Connected(null, e);
}
public SignalRService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ConnectToHub().Wait();
}
private async Task ConnectToHub()
{
try
{
//Connecting
if (connection == null)
{
connection = new HubConnection(url);
}
if (_hub == null)
{
_hub = connection.CreateHubProxy("ChatHub");
}
await connection.Start();
//Connected
//Configure all the incoming options
_hub.On<Message>("RecieveMessage", IncomingMessage);
System.IO.File.WriteAllText(#"C:\Users\Bailey Miller\Desktop\FTP\Succes.txt", "Connected");
OnConnected(new ConnectedArgs(true));
}
catch (Exception ex)
{
//Failed
//OnConnected(new ConnectedArgs(false));
System.IO.File.WriteAllText(#"C:\Users\Bailey Miller\Desktop\FTP\Fail.txt", "Failed to connect " + ex.Message.ToString());
}
}
private void IncomingMessage(Message state)
{
DateTime? lmt;
//Determine if has lastmessagetime
if (LastMessage == null) {
lmt = null;
}
else {
lmt = LastMessage.RecievedAt;
}
LastMessage = state;
//New Message
//OnNewMessage(new MessageRecievedArgs(state, lmt));
}
protected override void OnStop()
{
}
}
public class MessageRecievedArgs : EventArgs
{
public Message NewMessage { get; }
public DateTime? LastMessageTime { get; }
public MessageRecievedArgs(Message msg, DateTime? lmt) {
this.NewMessage = msg;
this.LastMessageTime = lmt;
}
}
public class ConnectedArgs : EventArgs {
public bool Success { get; }
public ConnectedArgs(bool suc) {
this.Success = suc;
}
}
My windows application as of now:
public MainWindow()
{
InitializeComponent();
SignalRService.SignalRService.NewMessage += SignalRService_NewMessage;
SignalRService.SignalRService.Connected += SignalRService_Connected;
}
private void SignalRService_Connected(object sender, SignalRService.ConnectedArgs e)
{
throw new NotImplementedException();
}
private void SignalRService_NewMessage(object sender, SignalRService.MessageRecievedArgs e)
{
throw new NotImplementedException();
}
Your question is a bit broad- you don't describe exactly what isn't working, so I am guessing that when you start your service, it says "starting..." for a long while and eventually windows service manager gives you an error saying your service didn't start in a timely fashion. The issue is that OnStart() is expected to return- you can't block the thread there with the Wait() call. My suggestion would be to spawn a new background thread here to perform the waiting, then exit. That should get you past the first hurdle.
As another aside... You can add a regular main method to a windows service project, change the project type to Console Application, and run it that way to reduce your debugging cycle time. Then when you are sure it basically works, change the project type back to Windows Service and install it.
EDIT: Now that you have a better error description, I see the real problem. The issue is that you are raising an event without checking for null first. Event fields are null until you attach a listener. So change your code as follows:
protected virtual void OnConnected(ConnectedArgs e) {
System.IO.File.WriteAllText(#"C:\Users\Bailey Miller\Desktop\FTP\Logg.txt", "Hit OnConnected " + e.Success +" " + Connected != null ? "Isn't null" : "Null event");
ConnectedToHubEventHandler connectedEvent = Connected;
if (connectedEvent != null) // This event might be null, so check first
connectedEvent(null, e);
}
I created two separate Windows Forms applications in C# that use MSMQ for communicating. Here's how it works, it looked simple enough though:
App1 sends a details request to App2.
App2 creates an event to open the window.
App2 opens a "details" window.
The only problem I have is that when received the message, the "details" window freezes after appearing.
As I handle MSMQ messages handling in an object that uses threads, I suspect the problem comes from there... But I have no experience in handling MSMQ messages or specific events handling between parts of an application.
Here's part of the code I use for App2:
/*Class declared in the Core namespace*/
public class TaskMessageQueueHandler
{
public TaskMessageQueueHandler()
{
this.Start();
}
private Thread m_thread;
private ManualResetEvent m_signal;
public event System.EventHandler messageReceived;
public void Start()
{
m_signal = new ManualResetEvent(false);
m_thread = new Thread(MSMQReceiveLoop);
m_thread.Start();
}
public void Stop()
{
m_signal.Set();
}
protected virtual void SendEvent(object sender, EventArgs e)
{
if (messageReceived != null)
messageReceived(this.message, e);
}
public string message;
private void MSMQReceiveLoop()
{
bool running = true;
MessageQueue queue = new MessageQueue(#".\Private$\queue1");
while (running)
{
try
{
var message = queue.Receive();
message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });
this.message = message.Body.ToString();
string m = this.message;
SendEvent(m, System.EventArgs.Empty);
if (m_signal.WaitOne(10))
{
running = false;
}
}
catch
{
Console.WriteLine("ERROR");
running = false;
}
}
}
}
/*Main process, in the Program namespace*/
[...]
Core.TaskMessageQueueHandler tmqh = new Core.TaskMessageQueueHandler();
EventListener el = new EventListener();
tmqh.messageReceived += new System.EventHandler(el.ShowDetails);
[...]
/* Class in the Program namespace */
class EventListener
{
public void ShowDetails(object sender, EventArgs e)
{
int numero = int.Parse(sender as string);
Details details = new Details(numero);
details.Show();
}
}
Where did I go wrong? Where did I go right?
Thanks a lot,
Stephane.P
EDIT: if the MSMQ handler is stopped with Stop() anywhere around the event sending, the details window appears then disappears right away...
EDIT2: After the workaround given by Slugart, I managed to make this work:
class EventListener
{
Main control;
public EventListener(Main main)
{
control = main;
}
public void ShowDetails(object sender, EventArgs e)
{
int numero = int.Parse(sender as string);
control.Invoke((Action)(() => ShowDetails(numero)));
}
private void ShowDetails(int numero)
{
Details details = new Details(numero);
details.Show();
}
}
Which is used like:
Core.TaskMessageQueueHandler tmqh = new Core.TaskMessageQueueHandler();
EventListener el = new EventListener(this);
tmqh.messageReceived += new System.EventHandler(el.ShowDetails);
You're creating and displaying a form Details on a thread other than the main GUI thread and not an STA thread at that.
Your EventListener should have a reference to a running form (your main form perhaps) and then call form.Invoke() on it.
class EventListener
{
Control control; // A valid running winforms control/form created on an STA thread.
public void ShowDetails(object sender, string message)
{
int numero = int.Parse(message);
control.Invoke(() => ShowDetails(numero))
}
private void ShowDetails(int numero)
{
Details details = new Details(numero);
details.Show();
}
}
Also sending your event data as the sender is not really following the Event pattern that has been put in front of you. You want to use the EventArgs parameter for this, use the EventHandler delegate (EventHandler in your case).
I've created my custom MessageBox using MessagePrompt from the Coding4Fun toolkit.
The problem occurs when I run ResetData_Click. I expected that after launching ComplexMessage.Show rest of the code inside ResetData_Click stops executing while ComplexMessage is open. As occurred it is completely different. All code is executed at once and it doesn't matter what user will chose in ComplexMessage because
if (ComplexMessage.Result)...
is already executed.
What should I do to make my ComplexMessage act like System.Windos.MessageBox? It means when MessageBox is called the parent's thread is waiting for the user's decision.
private void ResetData_Click(object sender, RoutedEventArgs e)
{
ComplexMessage.Show("You are about to delete all data", "Are you sure?", true);
if (ComplexMessage.Result)
{
DataControl.DataFileReset();
}
}
public class ComplexMessage
{
private static MessagePrompt messageprompt;
private static bool messageresult;
public static void Show(string message, string title, bool vibrate)
{
if (!(!(messageprompt == null) && messageprompt.IsOpen))
{
messageprompt = new MessagePrompt
{
Title = title,
Message = message
};
messageprompt.Completed += new EventHandler<PopUpEventArgs<string, PopUpResult>>(messageprompt_Completed);
messageprompt.IsCancelVisible = true;
messageprompt.Show();
if (vibrate) { Tools.VibrateMessage(); }
}
}
static void messageprompt_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
{
if (!e.PopUpResult.Equals(PopUpResult.Cancelled))
{
messageresult = true;
}
else
{
messageresult = false;
}
((MessagePrompt)sender).Completed -= messageprompt_Completed;
}
public static bool Result
{
get { return messageresult; }
}
}
Since you are displaying the MessageBox from a click event, you are running on the UI thread, which you don't want to freeze.
One option is to make ComplexMessage expose a static event, which it fires in messageprompt_Completed.
Then in ResetData_Click subscribe to the event prior to calling ComplexMessage.Show, and in the event handler, depending on the result, call DataControl.DataFileReset, and unsubscribe.
An alternative is to rethink making the members of ComplexMessage static, and instead to pass an "Action<bool> callback" parameter to the Show method, which you store away in a private member, and then invoke the callback in messageprompt_Completed.
Well I've tried several methods of getting this to work, background worker, Dispatcher.Invoke, threading within the called class and nothing seems, to work. The best solution so far is an Extension method which calls the invoke of the control. Also I've tried avoid passing the data for the label through my event classes and simply invoking within my processing code, however this made no difference.
In regards to the background component, I kept getting exceptions saying the background worker was busy, so I instantiated the class several times, however the label only visibly changed once the entire operation had been complete.
I've removed my previous code, here's everything that is relevant, as it seems the issue is difficult to resolve.
Method Being Called
private void TestUris()
{
string text = new TextRange(rtxturis.Document.ContentStart, rtxturis.Document.ContentEnd).Text;
string[] lines = Regex.Split(text.Remove(text.Length - 2), "\r\n");
foreach (string uri in lines)
{
SafeUpdateStatusText(uri);
bool result;
string modUri;
if (!uri.Contains("http://"))
{
modUri = uri;
result = StoreData.LinkUriExists(new Uri("http://" + modUri));
}
else
{
modUri = uri.Substring(7);
result = StoreData.LinkUriExists(new Uri(uri));
}
if (!result)
{
Yahoo yahoo = new Yahoo();
yahoo.Status.Sending += (StatusChange);
uint yahooResult = 0;
yahooResult = yahoo.ReturnLinkCount(modUri);
if (yahooResult > 1000 )
{ results.Add(new ScrapeDetails(Guid.NewGuid(), modUri, 1000, "Will be processed", true)); }
else
{ results.Add(new ScrapeDetails(Guid.NewGuid(), modUri, (int)yahooResult, "Insufficient backlinks", false)); }
}
else
{
results.Add(new ScrapeDetails(Guid.NewGuid(), modUri, 0, "Previously been processed", false));
}
}
foreach (var record in results)
{
dgvresults.Items.Add(record);
}
EnableStartButton();
}
Yahoo Class
public class Yahoo
{
/// <summary>
/// Returns the amount of links each Uri has.
/// </summary>
public uint ReturnLinkCount(string uri)
{
string html;
Status.Update(uri, false); //this is where the status is called
try
{
html = client.DownloadString(string.Format("http://siteexplorer.search.yahoo.com/search?p=http%3A%2F%2F{0}&fr=sfp&bwm=i", uri));
}
catch (WebException ex)
{
ProcessError(ex.ToString());
return 0;
}
return (LinkNumber(html));
}
Status Classes
public class StatusEventArgs : EventArgs
{
private string _message;
private bool _isidle;
public StatusEventArgs(string message, bool isidle)
{
this._message = message;
this._isidle = isidle;
}
public bool IsIdle
{
get { return _isidle; }
}
public string Message
{
get { return _message; }
}
}
public class Status
{
public Status()
{
}
// Declaring an event, with a custom event arguments class
public event EventHandler<StatusEventArgs> Sending;
// Some method to fire the event.
public void Update(string message, bool isIdle)
{
StatusEventArgs msg = new StatusEventArgs(message, isIdle);
OnUpdate(msg);
}
// The method that invokes the event.
protected virtual void OnUpdate(StatusEventArgs e)
{
EventHandler<StatusEventArgs> handler = Sending;
if (handler != null)
{
handler(this, e);
}
}
}
Method That Changes the labels Content
private void StatusChange(object sender, StatusEventArgs e)
{
if(!e.IsIdle)
{
lblstatus.Content = e.Message;
lblstatus.Foreground = StatusColors.Green;
lblstatus.Refresh();
}
else
{
lblstatus.Content = e.Message;
lblstatus.Foreground = StatusColors.Grey;
lblstatus.Refresh();
}
}
The Refresh static method called:
public static class ExtensionMethods
{
private static Action EmptyDelegate = delegate() { };
public static void Refresh(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke(DispatcherPriority.Render , EmptyDelegate);
}
Another EDIT: Staring at my code for a bit longer, I've realised, that the foreach loop will execute really quickly, the operation which takes the time, is
yahooResult = yahoo.ReturnLinkCount(modUri);
Therefore I've declared the status class (which handles the event and invokes the label etc) and subscibed to it. I've gotten better results, although it still feels random, sometimes I see a couple of label updates, and sometimes one even though the exact same URI's are passed, so weird.
I hope there is sth. helpful...
private void button1_Click(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem(o =>
{
int result = 0;
for (int i = 0; i < 9999999; i++)
{
result++;
Dispatcher.BeginInvoke(new Action(() =>
{
this.label1.Content = result;
}));
Thread.Sleep(1);
}
});
}
SOLVED IT YES WOOHOOOOOOOO 3 days of testing, testing, testing.
I decided to start a new project just with the extension method above and a simply for loop to test UI update functionality. I started testing different DispatchPrioraties (tested them all).
Weirdly, I found the highest priorities were the worse, for example using Send didn't update the label at all, Render updated it twice on average. This was the weird behavior I was experiencing as I tried different priorities. I discovered Background:
The enumeration value is 4. Operations are processed after all other non-idle operations are completed.
Now this sounded exactly what I didn't want, as obviously the label should update during processing, hence why I never tried it. I'm guessing that once one of my method has been completed, before the next it called, the UI is updated. I'm find of guessing, but it 100% consistently updates correctly on two separate operations.
Thanks all.
Well this is going to sound stupid but you could just reference the forms namespace, and then you can do this
using System.Windows.Forms;
mylabel = "Start";
Application.doEvents();
myLabel = "update"
Application.doEvents();
now the problem using this would be you are using wpf but you can still reference forms and use this namespace. The other issue is what ever is in the que would execute directly to the ui. However this is the most simplistic way of doing label updates i could think of.
would it be easier/better to add the status info as a property on this object, and have it just fire property change notifications?
that way the label text (or whatever) could be bound to the property instead of having the async work try to update a label?
or add a method like this to update status if you have to update it?
void SafeUpdateStatusText(string text)
{
// update status text on event thread if necessary
Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate
{
lblstatus.Content = text;
}, null);
}
otherwise, i don't think we have enough details to help yet....
I hope this helps:
private delegate void UpdateLabelDelegate(DependencyProperty dp, object value);
public void UpdateLabelContent(Label label, string newContent)
{
Dispatcher.Invoke(new UpdateLabelDelegate(label.SetValue), DispatcherPriority.Background, ContentProperty, newContent);
}
Usage:
while (true)
{
UpdateLabelContent(this.lblStatus, "Next random number: " + new Random().Next());
Thread.Sleep(1000);
}