How identify that form is consuming a Data Service - c#

I have a C# WinForms application with using of WCF Data Services and I can't find a way to know if the application is doing a process to a web service. I have tried to implement IClientMessageInspector, etc. but it seems that it doesn't work.
Is there any other way to catch when a Windows Form app is consuming a web service? The purpose is to display a "running process" icon when the communication to a service is opened and then hide it when it's close.
Thanks.

you should add event in place where you calling WcfService methods and then listen to this event in UI layer. With custom event argument in this event, you should provide more info for consuming UI layer like enum values Connected, TransferStarted, TransferEnded, Closed,...
I think there are two main possible cases:
Wcf communication take place synchronous - you are calling some wrapper methods of object which handles connection/requests/responses with wcf service - in this case i think its trivial, you make UI actions before every call of wrapper for example
try
{
WcfEx.IwcfS5ExtensionClient client = new IwcfS5ExtensionClient("MyEndpointConfigurationName");
client.Open();
if (client.State == CommunicationState.Opened)
{
//change UI to Connected
}
else
{
//change ui to Connection Error
}
Application.DoEvents();
//Change UI to Transfering data
Application.DoEvents();
client.DoWork();
//change UI to transfer done
Application.DoEvents();
client.Close();
//change ui to Closed
}
catch (Exception e)
{
//change ui to Comunication error
}
Second is if wcf communication is async
-i will add more sofisticated sample later today
EDIT: Example with async work and notifying form
using System;
using System.ComponentModel;
using System.Threading;
using WcfEx;
public class MyForm : Form
{
public MyForm()
{
WcfHandler WcfConnection = new WcfHandler();
WcfConnection.ProgressChanged += WcfConnectionOnProgressChanged;
}
private delegate void WcfConnectionOnProgressChangedDelegate(object Sender, WcfHandler.ProgressChangedEventArgs EventArgs);
private void WcfConnectionOnProgressChanged(object Sender, WcfHandler.ProgressChangedEventArgs EventArgs)
{
//multi thread synchronization check
if (this.InvokeRequired)
{
object[] Parameters = new object[2];
Parameters[0] = Sender;
Parameters[1] = EventArgs;
this.Invoke(new WcfConnectionOnProgressChangedDelegate(WcfConnectionOnProgressChanged), Parameters);
}
else
{
if (EventArgs == null)
return;
switch (EventArgs.StateValue)
{
case WcfHandler.ProgressChangedEventArgs.State.Started:
{
this.Text = "Starting connection...";
break;
}
case WcfHandler.ProgressChangedEventArgs.State.Processing:
{
this.Text = "Downloading updates...";
break;
}
case WcfHandler.ProgressChangedEventArgs.State.Finished:
{
this.Text = EventArgs.Succes ? "Update completed" : "Update failed";
break;
}
}
Application.DoEvents();
}
}
public class WcfHandler
{
public class ProgressChangedEventArgs : EventArgs
{
public enum State : int
{
Started,
Processing,
Finished
};
public bool Succes { get; set; }
public State StateValue { get; set; }
}
public delegate void ProgressChangedEventHandler(object sender, ProgressChangedEventArgs EventArgs);
public event ProgressChangedEventHandler ProgressChanged;
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
if (ProgressChanged != null)
{
ProgressChanged(this, e);
}
}
public void StartChecking()
{
BackgroundWorker bWorker = new BackgroundWorker();
bWorker.DoWork += CheckStatesAsync;
bWorker.RunWorkerCompleted += BWorkerOnRunWorkerCompleted;
bWorker.RunWorkerAsync();
}
private void CheckStatesAsync(object sender, DoWorkEventArgs e)
{
while (true)
{
WcfEx.IwcfS5ExtensionClient client = new IwcfS5ExtensionClient("MyWcfBindingConfig");
ProgressChangedEventArgs Controller = new ProgressChangedEventArgs();
Controller.StateValue = ProgressChangedEventArgs.State.Started;
Controller.Succes = true;
this.OnProgressChanged(Controller);
try
{
client.Open();
Controller.StateValue = ProgressChangedEventArgs.State.Processing;
Controller.Succes = true;
this.OnProgressChanged(Controller);
//do some work
}
catch (Exception)
{
this.OnProgressChanged(new ProgressChangedEventArgs()
{
StateValue = ProgressChangedEventArgs.State.Finished,
Succes = false
});
}
Thread.Sleep(8000);
}
}
private void BWorkerOnRunWorkerCompleted(object Sender, RunWorkerCompletedEventArgs RunWorkerCompletedEventArgs)
{
ProgressChangedEventArgs Controller = new ProgressChangedEventArgs();
Controller.StateValue = ProgressChangedEventArgs.State.Finished;
Controller.Succes = true;
this.OnProgressChanged(Controller);
}
}

Related

Passing events between threads run from separate class C#

I'm struggling to pass data between a thread started in a separate class from my main form. I believe (I could be wrong) that I should use an event. The problem I have is my subscribers are always null as I call the BluetoothScan class and start the thread before the event is subscribed to:
BluetoothScan bluetoothScan = new BluetoothScan(this);
bluetoothScan.BluetoothDeviceDiscovered += OnBluetoothDeviceDiscovered;
How do I subscribe to the event before starting the thread?
I have my Main Form:
using System;
using System.Windows.Forms;
//https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.invoke?view=net-5.0#System_Windows_Forms_Control_Invoke_System_Delegate_System_Object___
namespace YieldMonitor
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void BtnConnectBT_Click(object sender, EventArgs e)
{
//Start looking for the yield monitor device.
BluetoothScan bluetoothScan = new BluetoothScan(this);
bluetoothScan.BluetoothDeviceDiscovered += OnBluetoothDeviceDiscovered;
}
static void OnBluetoothDeviceDiscovered(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Message recieved from event");
}
}
}
My class that looks for bluetooth devices and if the right one is found should fire the event:
using InTheHand.Net.Sockets;
using System;
using System.Linq;
namespace YieldMonitor
{
class BluetoothScan
{
public event EventHandler BluetoothDeviceDiscovered;
public BluetoothScan(MainForm mainForm)
{
System.Diagnostics.Debug.WriteLine("Starting BluetoothScan Class");
Run();
}
public void Run()
{
System.Diagnostics.Debug.WriteLine("Running BluetoothScan Class");
string myDeviceName;
ulong myDeviceAddress;
BluetoothClient btClient = new BluetoothClient();
BluetoothDeviceInfo[] btDevices = btClient.DiscoverDevices().ToArray();
foreach (BluetoothDeviceInfo d in btDevices)
{
System.Diagnostics.Debug.WriteLine(d.DeviceName);
System.Diagnostics.Debug.WriteLine(d.DeviceAddress);
//have we found the device we are looking for?
if (d.DeviceName == "DSD TECH HC-05")
{
myDeviceName = d.DeviceName;
myDeviceAddress = d.DeviceAddress;
//Send out found adapter to the next stage
OnBluetoothScanned(EventArgs.Empty);
break;
}
}
}
protected virtual void OnBluetoothScanned(EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Running OnBlueToothScanned");
EventHandler handler = BluetoothDeviceDiscovered;
if (handler != null)// we have a subscriber to our event
{
System.Diagnostics.Debug.WriteLine("BluetoothScanned is Not empty");
handler(this, e);
}
else
{
System.Diagnostics.Debug.WriteLine("BluetoothScanned is Empty");
}
}
}
}
EDIT
I've found some nice solutions using Tasks where I need to update a label once a task is completed ie.
bool myDevicePaired = false;
var eventDevicePaired = new Progress<bool>(boDevicePaired => myDevicePaired = boDevicePaired);
await Task.Factory.StartNew(() => BluetoothPair.Run(myDeviceAddress, eventDevicePaired), TaskCreationOptions.LongRunning);
//Register the device is paired with the UI
if (myDevicePaired)
{
BtnConnectBT.Text = "Disconnect?";
}
Which is working well for Tasks that have an end that I am waiting for example waiting for a bluetooth device to connect.
But I'm beginning to pull my hair out with System.InvalidOperationException: 'Cross-thread operation not valid: Control 'tbInfo' accessed from a thread other than the thread it was created on.' error when trying to update a form text box.
Example:
in my MainForm Class:
I create what I've called an Event Reciever...
private void BluetoothSocketEventReciever(object sender, EventArgs e)
{
Debug.WriteLine("Event!!!"); //writes data to debug fine
tbInfo.AppendText("Event!!!!"); //causing error
}
I create a task to read from the device...
private void ReadDataFromDevice(UInt64 myDeviceAddress)
{
BluetoothSocket bluetoothSocket = new BluetoothSocket(myDeviceAddress);
bluetoothSocket.BluetoothDataRecieved += BluetoothSocketEventReciever;
Task.Factory.StartNew(() => bluetoothSocket.Run(), TaskCreationOptions.LongRunning);
}
In my BluetoothSocket class I have an endless while loop which will be reading data from a socket (hopefully) At the moment its just creating an empty EventArgs to trigger the Event every second:
namespace YieldMonitor
{
class BluetoothSocket
{
ulong myDeviceAddress;
public event EventHandler BluetoothDataRecieved;
public BluetoothSocket (ulong deviceAddress)
{
myDeviceAddress = deviceAddress;
}
public void Run()
{
System.Diagnostics.Debug.WriteLine("Were in BluetoothSocket ... Address: " + myDeviceAddress);
while (true)
{
Thread.Sleep(1000);
Debug.WriteLine("In BluetoothSocket - Address = " + myDeviceAddress);
OnBluetoothDataRecieved(EventArgs.Empty);
}
}
protected virtual void OnBluetoothDataRecieved(EventArgs e)
{
EventHandler handler = BluetoothDataRecieved;
if (handler != null)
{
handler(this, e);
} else
{
//No subscribers
}
}
}
}
I'm sure I'm missing something simple here but how can I pass the data from the endless loop to the text box on the main form?
EDIT
Think I've just sorted it.
private void BluetoothSocketEventReciever(object sender, EventArgs e)
{
Debug.WriteLine("Event!!!");
tbInfo.Invoke((Action)delegate
{
tbInfo.AppendText("Event!!!");
});
//tbInfo.AppendText("Event!!!!");
}
Is this the correct way to do it?
You can Pass the event handler as a parameter on the constructor
public event EventHandler BluetoothDeviceDiscovered;
public BluetoothScan(MainForm mainForm, EventHandler bluetoothDeviceDiscovered)
{
System.Diagnostics.Debug.WriteLine("Starting BluetoothScan Class");
BluetoothDeviceDiscovered += bluetoothDeviceDiscovered
Run();
}
Personally, i'm not so fun of calling method on constructor. It can be source of bugs or performance issues
Constructor
In class-based object-oriented programming, a constructor
(abbreviation: ctor) is a special type of subroutine called to create
an object. It prepares the new object for use, often accepting
arguments that the constructor uses to set required member variables.
You can pass eventhandler as parameter and call Run later

pjsip c#, System.AccessViolationException on answering an incoming call on an separated thread

In the overrided void onIncomingCall I open a new Background thread which shows a new (Popup) Form.
I try to pickup or decline the Call in this Form but then I get an System.AccessViolationException.
it seems that the current call object is locked and cannot be accessed from another Form.
If I use the currentcall.answer(prm) in the onIncomingCall void then the call is established successfully (without another Form and thread).
public class myaccount : Account
{
public override void onIncomingCall(OnIncomingCallParam prm)
{
Call call = new Call(this, prm.callId);
CallOpParam param = new CallOpParam();
param.statusCode = pjsip_status_code.PJSIP_SC_RINGING;
param.statusCode = pjsip_status_code.PJSIP_SC_OK;
pjsipfunctions.currentparam = param;
pjsipfunctions.currentcall = call;
var thread = new Thread(() =>
{
ShowPopup(call,prm.callId.ToString());
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
// Thread myCallingThread = new Thread(new ThreadStart(ShowPopup));
//myCallingThread.SetApartmentState(ApartmentState.STA);
//myCallingThread.IsBackground = true;
//myCallingThread.Start();
}
public void ShowPopup(Call myCall,string call_id)
{
IncommingCallPopup win = new IncommingCallPopup(ref myCall, call_id );
win.Show();
System.Windows.Threading.Dispatcher.Run();
}
}
#####################################
public IncommingCallPopup(ref Call info, string callid)
{
currentCall = info;
Callid = callid;
CurrentCall = currentCall;
Prm.statusCode = pjsip_status_code.PJSIP_SC_RINGING;
InitializeComponent();
labelCallId.Content = callid;
}
private void rejectcall(object sender, RoutedEventArgs e)
{
Prm.statusCode = pjsip_status_code.PJSIP_SC_DECLINE;
CurrentCall.hangup(Prm);
}
private void transfercall(object sender, RoutedEventArgs e)
{
}
private void takecall(object sender, RoutedEventArgs e)
{
Prm.statusCode = pjsip_status_code.PJSIP_SC_OK;
try
{
CurrentCall.answer(Prm);
}
catch(Exception ex)
{
}
}
After crazy searching and trying some things i've figured it out.
Every Thread must registered in the Endpoint that you can hangup, pickup or transfer your call in another Class(Window).
All you need is to write this Method in a Public class and call this void everytime you call your void from another window ->
public void callpopup(String number) {
checkThread();
//answer, decline or something else
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static void checkThread()
{
try
{
if (ep != null && !ep.libIsThreadRegistered())
ep.libRegisterThread(Thread.CurrentThread.Name);
}
catch (Exception e)
{
}
}

Calling own WCF WebService twice from different BackgroundWorkers closes application

I've written a small WCF WebService (.svc) which I want to call from other applications. It's working fine so far.
In another application I've got a Windows Form. When this is shown, it will call BackgroundWorker1 to get a list of objects from the WebService and show it to the user on it's completed1-method. So far, so good.
Now, after the user selects one object and clicks "ok", then BackgroundWorker2 will call the WebService again to gather more information. But here, within the doWork2-method exactly after the WebService-call, the whole application breaks without any exceptions or errors. It just closes directly after the WebService is called.
This is very weird, because as I have a look at the WebServices log files, it seems to work normal and still logs the successful operation AFTER the other application is closed. So the WebService cannot be the problem, I think.
Another weird thing: If I call the WebService the second time on the GUI thread (and not with BackgroundWorker2), it just works. It blocks the UI, but it works.
So, why is my application just "broken" after the second call without any notification?
Any ideas are very much welcomed.
Thanks in advance.
Greets
Here's some simplified code. The application closes in "bgwGetSingleCar_DoWork":
public partial class MyForm : Form
{
private Controller _ctrl { get; set; }
private Config _config { get; set; }
private List<Cars> _cars { get; set; }
public bool Result { get; private set; }
public MyForm(Controller ctrl, Config config)
{
this._ctrl = ctrl;
this._config = config;
this.Result = false;
InitializeComponent();
}
private void MyForm_Load(object sender, EventArgs e)
{
try
{
this.bgwGetAllOffers.RunWorkerAsync(new WorkerInfo()
{
WorkerType = WorkerType.Type1,
IdLocal = this._config.IdLocal,
IdExternal = this._config.IdExternal,
});
}
catch (Exception ex)
{
// ...
}
}
private void FillList(List<Cars> list)
{
// ...
}
private void btnOk_Click(object sender, EventArgs e)
{
CarListItem v = (CarListItem)this.lstBoxCars.SelectedValue;
this._config.IdExternal = v.IdExternal;
try
{
this.bgwGetSingleCar.RunWorkerAsync(new WorkerInfo()
{
WorkerType = WorkerType.Type2,
IdLocal = this._config.IdLocal,
IdExternal = this._config.IdExternal,
});
}
catch (Exception ex)
{
// ...
}
}
private void bgwGetAllCars_DoWork(object sender, DoWorkEventArgs e)
{
try
{
WorkerInfo info = (WorkerInfo)e.Argument;
Client client = new Client();
GetCarsResult result = client.GetAllCars(new GetAllCarsRequest()
{
IdLocal = info.IdLocal,
IdExternal = info.IdExternal
});
if (!result.Success)
{
// ...
}
if (result.Cars != null)
{
this._cars = result.Cars.ToList();
}
}
catch (Exception ex)
{
/// ...
}
}
private void bgwGetAllCars_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.FillList(this._cars);
}
private void bgwGetSingleCar_DoWork(object sender, DoWorkEventArgs e)
{
try
{
WorkerInfo info = (WorkerInfo)e.Argument;
Client client = new Client();
// Application closes after this line, but WebService log still shows activity
GetCarsResult result = client.GetSingleCar(new GetSingleCarRequest()
{
IdLocal = info.IdLocal,
IdExternal = info.IdExternal
});
if (result.Success)
{
this.Result = true;
}
}
catch (Exception ex)
{
/// ...
}
}
private void bgwGetSingleOffer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
public class CarListItem : Car
{
public override string ToString()
{
return ((DateTime)this.LastUpdate).ToString("dd.MM.yyyy - HH:mm");
}
}
I just found my "design break".
It was the button's "DialogResult" which caused the application to close too soon. But strange that the debugger didn't step ahead...

variable not set by background worker on first pass

I have an observer with a background worker. Lets say the observer has the following structure:
internal class Observer
{
private readonly BackgroundWorker bw1;
internal Object target;
public Observer()
{
bw1 = new BackgroundWorker();
bw1.DoWork += bw1_DoWork;
bw1.RunWorkerCompleted += bw1_RunWorkerCompleted;
bw1.WorkerSupportsCancellation = true;
}
private void bw1_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = new object(); // Query to database
}
private void bw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
target = e.Result as object;
if (ChangedScannedValue != null)
{
ChangedScannedValue(_scannedValue);
}
}
private String _scannedValue = string.Empty;
internal delegate void OnChangedScannedValue(String scannedValue);
internal event OnChangedScannedValue ChangedScannedValue;
internal String ScannedValue
{
get { return _scannedValue; }
set
{
_scannedValue = value;
bw1.RunWorkerAsync(_scannedValue);
//ProcessScannedValue();
}
}
}
I have another class listening to the event.
public partial class myControl : UserControl
{
Observer _observer = new Observer();
public myControl()
{
InitializeComponent();
}
internal void LoadData(Observer observer)
{
_observer = observer;
_observer.ChangedScannedValue += _observer_ChangedScannedValue;
}
void _observer_ChangedScannedValue(string ScannedValue)
{
if (_observer.target != null)
{
// Do Stuff
}
else
{
MessageBox.Show("NO TARGET FOUND.");
}
}
}
The thing is. initially, after the background worker finishes, I get the message box "NO TARGET FOUND.", however immediatley after, it would //Do Stuff Debugging shows that the RunWorkerCompleted event fires twice. This only happens on the first change to scanned value, all changes afterwards work as desired.
Questions:
1) Why does RunWorkerCompleted fire twice?
2) Why is the target not updated on the first fire of RunWorkerCompleted
You could try again with target being set in bw1_DoWork already, i.e.:
private void bw1_DoWork(object sender, DoWorkEventArgs e) {
target = new object(); // Query to database
}
private void bw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (ChangedScannedValue != null) {
ChangedScannedValue(_scannedValue);
}
}
Eventually you may want to replace the BackgroundWorker by a simpler solution with ThreadPool. I'd suggest this:
internal String ScannedValue {
get { return _scannedValue; }
set {
_scannedValue = value;
ThreadPool.QueueUserWorkItem( (WaitCallback) delegate {
target = new object(); // query database
if (ChangedScannedValue != null) ChangedScannedValue(_scannedValue);
} );
}
}

Handling events after receiving a MSMQ message (thread issue?)

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).

Categories

Resources