Get Windows Server shutdown reason in C# - 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.

Related

INotifyPropertyChanged Resubscribe not working, only the first time subscription working

I developing a Xamarin application, and I communicating an external custom device. My problem is very strange, firstly the application starting, and connecting automatically to device, so everything is fine. When i suddenly remove the battery from the external device, the bluetooth connection is broken, and it's working fine to, but when I turn on the external device again, my Xamarin application connecting to it very well well, but the subscriptions not working anymore.
I debugged it, but not calling anymore. I think the unsubscribe/subscribe process is wrong.
...
if (ble.GetConnectionStatus())
{
Device.BeginInvokeOnMainThread(() =>
{
...
ble.Adapter.DeviceConnectionLost -= Adapter_DeviceConnectionLost;
ble.Adapter.DeviceConnectionLost += Adapter_DeviceConnectionLost;
ble.PropertyChanged -= Ble_PropertyChanged;
ble.PropertyChanged += Ble_PropertyChanged;
data.PropertyChanged -= data_PropertyChanged;
data.PropertyChanged += data_PropertyChanged;
...
});
...
So it's so strange, because first time this working, when starting the app, but when I call it after reconnect that same subscription not working. So if its wrong, then why working this at very first time?
I have no error, just not fire the functions again after resubscribe.
So as you see, I need to "refresh" the subscription. Is there another way to solve this problem?
If that "button to recreate everything" works, then I see two alternatives.
Option 1:
Have such a button, so that user can manually "fix" the situation.
PRO: Gives the user a solution that is guaranteed to work.
CON: Requires user intervention.
Option 2:
Have a periodic timer, that decides whether/when to forcibly "fix" the situation.
PRO: Automatically recovers.
CON: Risks losing data, if forces a recovery at the same time data is arriving.
In pseudo-code, option 2 might be something like this:
// pseudo-code
static Timer timer = ..start a timer that has an event every 10 seconds.
OnTimerElapsed:
if (!eventSeenRecently)
ForceReset();
eventSeenRecently = false;
..whereever you receive data..
if (..has data..)
eventSeenRecently = true;
The concept is that you keep track of whether data continues to be received. If the device stops sending you information (but you believe it should be), then you "ForceReset" - whatever is needed to get everything going again.
DeviceConnectionLost should also set some flag, that you use to ForceReset when the device "comes back".
// pseudo-code
DeviceConnectionLost:
resetNeeded = true;
OnTimerElapsed:
if (resetNeeded && ..test that device is available again..) {
ForceReset();
resetNeeded = false;
}
Perhaps this custom device has some option or info that can help.
For example, there might be a way to query some id or other info, so you can discover that the device is now "different", in a way that requires the reset. Then the timer does that query, and uses that info to decide to reset.

Windows.System.User events not being raised in UWP

I am trying to have some logic when Windows user is being changed while my UWP app is running and for that in my OnLaunchApplicationAsync method I have:
var userWatcher = Windows.System.User.CreateWatcher();
userWatcher.AuthenticationStatusChanged += AuthenticationStatusChanged;
and I also have
private void AuthenticationStatusChanged(Windows.System.UserWatcher sender, Windows.System.UserChangedEventArgs args)
{
// Some logic
}
But the problem is that when I log off with my current user and sign in with another one, the expected event is not being raised.
I have also tried out userWatcher.Updated for updating user data as well as userWatcher.AuthenticationStatusChanging with the same result.
Am I doing this in a wrong way?
You need to start the watcher, otherwise these events are not fired.

Custom events not showing up in event log

I'm trying to write to the application event log. The following code executes without error under Windows 8 (when run with admin privileges), but I don't see any events showing up when looking at the Application log in the Windows Event Viewer. Can anyone help me figure out what I'm doing wrong. Do I need to add something to app.config?
using System.Diagnostics;
namespace tracetest2
{
class Program
{
static void Main(string[] args)
{
if (!EventLog.SourceExists("TestSource"))
{
EventLog.CreateEventSource("TestSource", "Application");
}
EventLog appLog = new EventLog("Application", ".", "TestSource");
appLog.EnableRaisingEvents = true;
appLog.EndInit();
Debug.WriteLine(appLog.Entries.Count);
appLog.WriteEntry("An entry to the Application event log.");
Debug.WriteLine(appLog.Entries.Count);
}
}
}
According to the Microsoft website, we have the following information:
Note:
If a source has already been mapped to a log and you remap it to a new log, you must restart the computer for the changes to take effect.
The machine must be restarted every time you create a new custom event key. (Or just restart the EventViewer service) :)

Integrating Lync 2010 with an external program

How can I integrate Lync 2010, with a program that does a DB look up and shows a small popup, with the information found, and also a few buttons with some options.
The program is already running with some other types of phone systems, I kind of need a connector for Lync.
I don't want to put a tab or other UI inside Lync.
You'll need to start with the Lync SDK. You can build your app as a Winforms or WPF app.
Signing In
To connect and sign in to the running instance of Lync, check out this page from the SDK. Make sure you keep a reference to the LyncClient object that represents Lync. This can be got by calling the static method LyncClient.GetClient()
Detecting an incoming call
To detect an incoming call, you can listen for the ConversationManager.ConversationAdded event. ConversationManager is a property on your LyncClient instance.
To determine if the call is a) an Audio call, and b) incoming (as opposed to an outgoing call placed by the user) you can use the following method:
bool IsIncomingAVCall(Conversation conversation)
{
// Test to see if the call contains the AV modality
bool containsAVModality = conversation.Modalities.ContainsKey(ModalityTypes.AudioVideo);
if (containsAVModality)
{
// Get the state of the AV modality
var state = conversation.Modalities[ModalityTypes.AudioVideo].State;
// 'Notified' means the call is incoming
if (state == ModalityState.Notified) return true;
}
return false;
}
In the ConversationAdded event, you should sign up to the Conversation.ParticipantAdded event, so you can check who the caller is. The EventArgs object has a Participant property, which in turn has a Contact property. The Contact property has a number of properties including Uri, which should give you the phone number (if that's what you need).
You can then make your DB call and pop your info.
Edit: I've written a blog post about screen pops which goes into much more detail - here
Placing a call
If your app is WPF, the easiest way to allow a call to be placed is by using the StartAudioCallButton control. Otherwise, the instructions here should help.

Silverlight 4 Clipboard Security Exception "access is not allowed"?

I'm new in Silverlight and i am doing some tests. With my current test I try to display in real time the current Clipboard content. But there is a weird behaviors with this code :
namespace SilverlightTest
{
public partial class MainPage : UserControl
{
private Timer _timer;
public MainPage()
{
InitializeComponent();
var dispatcher_timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, 0, 5)};
dispatcher_timer.Tick += new EventHandler(timer_Callback);
dispatcher_timer.Start();
}
private void timer_Callback(object state, EventArgs eventArgs)
{
current_clip_board.Content = Clipboard.GetText();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
current_clip_board.Content = Clipboard.GetText();
}
}
}
The button Event and the timer Event are suppose to do exactly the same action.
But it doesn't ! The Button works fine and set the clipboard text into the label but the timer throw an exception :
Clipboard access is not allowed
The question is : why ? :)
Thanks.
PS : I would bet on a thread problem :p
Clipboard access, in a partial trust (in-browser) Silverlight application (the scenario you're likely referring to above), is restricted. The GetText property is accessible only in scenarios that the Silverlight runtime determines were initiated by the user. Your example is perfect -- by a button click for example. A dispatch timer however is not user initiated, so the property throws an exception (this is especially important within the context of a in-browser application, which could be a big security hole if you could create a Silverlight application that just ran silently in the browser, watching the user's clipboard updates without their knowledge).
See this clipboard documentation for more details.
Just trigger Clipboard.ContainsText() instead of Text. The method ContainsText is allowed!
Have you tried this:
private void timer_Callback(object state, EventArgs eventArgs)
{
Dispatcher.Invoke(new System.Threading.ThreadStart(delegate()
{
current_clip_board.Content = Clipboard.GetText();
}
}
edit
After a quick search, it appears that Clipboard is only available in response to a user action see here and here.
In partial trust (the default mode for
browser-hosted Silverlight-based
applications), Silverlight also
restricts clipboard access to its two
key APIs GetText and SetText. These
APIs can only be invoked from within a
context that is determined by the
Silverlight runtime to be in response
to a user-initiated action. For
example, clipboard access is valid
from within a handler for a Click or
KeyDown event. In contrast, clipboard
access is not valid from a handler for
Loaded or from a constructor, and
access attempts throw exceptions.
If your only option is to use a timer, then don't do it at all. The clipboad is a shared resource, and you're going to raise "cannot open clipboard" errors in other programs as they try to access the clipboard. i.e. user copies something from WinWord, WinWord tries to open the clipboard, but can't, because you've got it locked while you're examining it.
Hello this works for me but only in IE Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() => HtmlPage.Window.Eval("window.clipboardData.setData('Text','testtestest')"));
just use getData method

Categories