C# Refresh of the event in debug mode - c#

Here I try to recover some values into variables.
I send a message to a server which returns different values. These values are read in a thread. I catch all values returned by the server with an event.
I try to store it but I have a problem: when I use my debugger I can see all refresh of my event only at the end (at display time in a WindowsForm).
Example with code:
ModuleProtocole.SendMessage("VER"); // after this command I will receive the version
ModuleProtocole.SendMessage("NA1"); // after this command I will receive the name of hardware
public void MessageRec(object source, MesACK e)
{
ReceptionMessage = e.getinfos(); //My globale variable ReceptionMessage is refresh for every new value on port
}
if(ReceptionMessage[0] == "M") //When i debug line by line ReceptionMessage is always = "Monitor" but at the end of debug all variable like "Name" is completed by the good word
Version = ReceptionMessage;
else Name=ReceptionMessage;
So my question is: Why my event is refresh only one time in debug? In my code, it should be trigger 2 times but only the first one is show and apply to variables in debug console.

I colleague found the solution: in the subscribe function to the event, add Console.Writeline(ReceptionMessage); then you can see refresh of ReceptionMessage.
Event is complicated in debug mode, this is the best way for see the refresh !
public void MessageRec(object source, MesACK e)
{
ReceptionMessage = e.getinfos();
Console.Writline(ReceptionMessage);
}

Related

Is this SQLDependency's normal behavior?

void OnDependencyChange(object sender,SqlNotificationEventArgs e)
{
MessageBox.Show("changed");
}
I'm running a query in ViewModel, I get the result (Let's say 10). If I try to insert instantly to SQL a new row, I don't the MessageBox. However, If I stop debugging and re-run my application, It will show as If the value changed which it did. Isn't SQLDependency supposed to give you real time notifications?
I was expecting the MessageBox to show the minute I add a new row in my table.

How can i show connection status in real time on my form?

I'm creating an OPC client, that reads data from the server. I need to show status of connection with server in real time on my form. Can this be done?
For example:
private void checkStatus()
{
testValue.Text = cl.GetConnectionState().ToString();
}
cl.GetConnectionState() - method that shows connection status.
Add a timer to call that function. Function itself is fine, and should update the status correctly.
Although, if you want to do it right, I will say put this code in StateChange event handler. That way, your code will not run this function forever, and instead wait for the state to change.

Making file picker asynchronous - Windows Phone 8.1

I tried to make File open picker asynchronous using TaskComplectionSource however sometimes I get my application closed with -1 return value, sometimes I get exception like:
[System.Runtime.InteropServices.COMException] = {System.Runtime.InteropServices.COMException (0x80004005): Unspecified error
Unspecified error
at Windows.Storage.Pickers.FileOpenPicker.PickSingleFileAndContinue()
at PhotosGraphos.Mobile.Common.StorageFileExtensions.<PickSingleFileAsyncMobile..
Code:
public static class StorageFileExtensions
{
private static TaskCompletionSource<StorageFile> PickFileTaskCompletionSource;
private static bool isPickingFileInProgress;
public static async Task<StorageFile> PickSingleFileAsyncMobile(this FileOpenPicker openPicker)
{
if (isPickingFileInProgress)
return null;
isPickingFileInProgress = true;
PickFileTaskCompletionSource = new TaskCompletionSource<StorageFile>();
var currentView = CoreApplication.GetCurrentView();
currentView.Activated += OnActivated;
openPicker.PickSingleFileAndContinue();
StorageFile pickedFile;
try
{
pickedFile = await PickFileTaskCompletionSource.Task;
}
catch (TaskCanceledException)
{
pickedFile = null;
}
finally
{
PickFileTaskCompletionSource = null;
isPickingFileInProgress = false;
}
return pickedFile;
}
private static void OnActivated(CoreApplicationView sender, IActivatedEventArgs args)
{
var continuationArgs = args as FileOpenPickerContinuationEventArgs;
sender.Activated -= OnActivated;
if (continuationArgs != null && continuationArgs.Files.Any())
{
StorageFile pickedFile = continuationArgs.Files.First();
PickFileTaskCompletionSource.SetResult(pickedFile);
}
else
{
PickFileTaskCompletionSource.SetCanceled();
}
}
}
What's weird - this bug is hardly reproduced while debugging. Does anyone have any idea what could be reason of that?
Don't do that (don't try to turn Continuation behaviour into async). Why?
Normally when your app is put into the background (for example when you call file picker), it's being suspended, and here is one small pitfall - when you have a debugger attached, your app will work without being suspended. Surely that can cause some troubles.
Note also that when you normally run your app and you fire a picker, then in some cases your app can be terminated (low resources, user closes it ...). So you need here two things which are added by VS as a template: ContinuationManager and SuspensionManager. More you will find at MSDN. At the same link you will find a good procedure to debug your app:
Follow these steps to test the case in which your app is terminated after calling the AndContinue method. These steps ensure that the debugger reattaches to your app after completing the operation and continuing.
In Visual Studio, right-click on your project and select Properties.
In Project Designer, on the Debug tab under Start action, enable Do not launch, but debug my code when it starts.
Run your app with debugging. This deploys the app, but does not run it.
Start your app manually. The debugger attaches to the app. If you have breakpoints in your code, the debugger stops at the breakpoints. When your app calls the AndContinue method, the debugger continues to run.
If your app calls a file picker, wait until you have opened the file provider (for example, Phone, Photos, or OneDrive). If your app calls an online identity provider, wait until the authentication page opens.
On the Debug Location toolbar, in the Process dropdown list, select the process for your app. In the Lifecycle Events dropdown list, select Suspend and Shutdown to terminate your app but leave the emulator running.
After the AndContinue operation completes, the debugger reattaches to your app automatically when the app continues.
I've changed file picker to standard way provided by #Romasz - it still was crashing. I've been debugging it for hours and I get same COMException but sometimes with information provided:
"GetNavigationState doesn't support serialization of a parameter type which was passed to Frame.Navigate"
It seems that code with TaskCompletionSource works and there is nothing wrong with that. I found out in msdn documentation for Frame
Note: The serialization format used by these methods is for internal use only. Your app should not form any dependencies on it. Additionally, this format supports serialization only for basic types like string, char, numeric and GUID types.
And I was passing my model-class object in navigation parameter - so it was kept in navigation stack therefore it couldn't be serialized. The lesson is: do not use non-primitive types for navigation parameter - Frame.Navigate should disallow such navigation and throw exception - but it doesn't..
EDIT:
Another bug - if you bind tapped (let say button tapped) or event like that to command which launch FileOpenPicker you need to check if picker.PickFile.. was called before - otherwise when you tap fast on that button you'll get few calls to picker.PickFile.. and UnauthorizedAccessException will be thrown.

check for condition every period of time

i have a specific state(business case),i want to check it every period of time,to execute an action..they tell me to write a patch to handle this situation ..
the application i works in is a web application (asp.net)..
i don't know how to write the patch ,, and i don't know if the patch is the ideal solution in this state or not..
please any suggestions ,, any details explanation for this issue..
thanks in advance.
Firstly, it is quite simple to setup a timer to do this check. Initialise a timer,
int _State;
System.Timers.Timer stateCheckTimer = new System.Timers.Timer();
stateCheckTimer.Interval = 1000; // TODO - set to desired interval (in ms)
stateCheckTimer.AutoReset = true;
stateCheckTimer.Elapsed += stateCheckTimer_Elapsed;
Then just check your state in the stateCheckTimer_Elapsed function,
void stateCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Check for the desired state
if (_State == 1)
{
// Do something
}
}
The most difficult thing will be accessing the _State, so you'll probably have to put the timer in the same location as it (or have it passed, whatever works). I would suggest an event driven solution though. Make a public event handler on your class that handles the state,
public EventHandler OnStateChanged;
Then, encapsulate the access to your state variable (in this example, _State) so that you control the setting of it. When it is set, fire off this event. I do this through a property,
public int State
{
get { return _State; }
set
{
_State = value;
if (OnStateChanged != null)
{
OnStateChanged(this, null);
}
}
}
Then, you just need to wire up an event handle to execute your desired action,
OnStateChanged += StateChangeAction;
And in that function execute your desired action,
void StateChangeAction(object sender, EventArgs args)
{
// Check for the desired state
if (_State == 1)
{
// Do something
}
}
(you will have to pass the state in through the EventArgs args but that is pretty simple to do). This way, whenever the state changes you will immediately be able to act upon it (send an email, do whatever it is) rather than having to poll the state every x seconds or minutes. It will use less resources, be more reactive (quicker), and ultimately be neater code! If you are able to do it this way, I would highly recommend it.
this checking is done from the browser or on the server side application ?
if it is done from the client( Browser ) than you can do it with JavaScript See this Post
If you want to do it from the Server Side code than , you can do it with a thread, make thread sleep for some time and when it's wake up than check the state of your object
Is the action to be executed a database one, e.g. update some row in the database? If yes you can create a database job that handles this situation.
What about writing a small simple service that works in the background 24/7. I think its the simplest solution.

Get Windows Server shutdown reason in C#

Is it possible to get shutdown reason in Windows Server 2008 immediately after user choose the reason in dialog window? For the shutdown event I'm using SystemEvents.SessionEnding.
I want to write windows service, which will send e-mail about this event.
Or is there any other way in windows server to send e-mails about shutdown/restart event with getting the reason entered by user? Also, I want to notify about power source change (electic line/battery), but this I have already solved by Kernel32.dll > GetSystemPowerStatus.
You can get the shutdown reason inspecting the EventLog.
I assembled a quick demo on Windows Forms that you can adapt to your Windows service.
I've added a EventLog component to the Form and configured it properly. The snippet below shows the code generated in InitializeComponent() for the settings I've maid through the designer.
this.eventLog1.EnableRaisingEvents = true;
this.eventLog1.Log = "System";
this.eventLog1.Source = "USER32";
this.eventLog1.SynchronizingObject = this;
this.eventLog1.EntryWritten += new System.Diagnostics.EntryWrittenEventHandler(this.eventLog1_EntryWritten);
On the event handler, you'll have something along the following lines:
private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
{
EventLogEntry entry = e.Entry;
if (e.Entry.EventID == 1074)
{
File.AppendAllText(#"c:\message.txt", entry.Message);
}
}
Take a look at your event log to see the appropriate EventIds to filter out.
The compiler will warn you about EventID being deprecated and telling you that you should use InstanceId, but in the quick tests I've done here, it didn't write to my log file and I think we already have enough information to put you on track.
sure it's possible.
in case you want to get that comboBox value in real-time, you will need to run a Thread monitor on that process to raise an event when that value change.

Categories