Inactivity and activity ,application idle , user-inactivity auto logout - c#

After lot of googling and spending 4 hours I guess this is the best way to find user inactive and lock screen.
public MainWindow()
{
InitializeComponent();
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(10) };
timer.Tick += delegate
{
timer.Stop();
MessageBox.Show("Logoff trigger");
timer.Start();
};
timer.Start();
InputManager.Current.PostProcessInput += delegate(object s, ProcessInputEventArgs r)
{
if (r.StagingItem.Input is MouseButtonEventArgs || r.StagingItem.Input is KeyEventArgs)
timer.Interval = TimeSpan.FromSeconds(10);
};
}

If your question is, "Is there a better way to implement a session timeout?" - then I would say, possibly - this is how I do it.
A session timeout can do one of two things. It can work like an arcade game where you have a timeout duration in which to complete your tasks. Or it can monitor for inactivity and close if nothing happens.
Either way, I would wrap this functionality into a session provider - assuming MVVM is the goal, I use provider to refer to a service or data source of some sort.
The provider gets instantiated as a singleton and so exists as one instance throughout the app life cycle. I usually manage this by creating it in app.xaml. I then interact with the provider using a message framework such as MVVM light.
Once created the provider manages a thread which checks a datetime to see if it occurs in the past. If it does it issues a session over event or message. This message is picked up by your application to shut down or whatever.
If you want a finite period or time, you implement a start message which sets the monitored date time to a point in the future according to the time span you want to run. If you want an inactivity log out then you send this message from whatever user interactions you see fit to prevent log out such as input changes or ICommand executes.
I take this a stage further so my provider also issues an 'ending' message a few seconds before the timeout completes so I can display a warning - but hopefully you get the general idea.
If this sounds like what you're after then I will add in some examples, but haven't so far in case this is not what you're asking.

Related

C# performing a task every hour

I have a CSV importer tool I use at my company that imports 10-20k records at a time but it can take a couple hours, the issue is that the application is connecting to an API that has an OAuth token that expires after an hour.
to me this sounds like a job for timer, but the actual code that imports and needs the oauth token are in modules since each vendor I have to upload have their own mappings to the api we use.
so I need to programmatically need to see if 3590 seconds (or 50 minutes) has passed so that I can refresh my OAuth token.
does anyone know how I can do this? if timer is not the best way to go, what way would you suggest?
it'd be nice if timer has an Elapsed property I could access from my other objects (like I can with background worker).
You could just make it part of your processing loop:
{
DateTime lastReset = DateTime.Min;
TimeSpan resetInterval = TimeSpan.FromMinutes(50);
foreach (var whatever in enumerable)
{
if ((DateTime.Now - lastReset) > resetInterval)
{
ResetAuthToken();
lastReset = DateTime.Now;
}
ProcessWhatever();
}
}
I would suggest that you can use the timer's elapsed event. This will be triggered based on the interval may be 50 minutes etc, which you can read from the configuration file of the windows service.
Then in the timer interval, you can just update a global variable [property] with the Auth token that will be used for the subsequent API calls.
In case you just want to keep the session alive, you can just refresh the token as itmse86 said. However, the timer elapsed event will come handy for you.
Reference here

Monitor web pages access

I hope I can get some help.
I’m trying to create an host based application using C# (in the simplest way) to monitor access to a web page from the computer that hosts the application, if this web page is accessed while the program is running an event should rise.
So far I have used the SHDocVw.ShellWindows() but it works only if the web page has already been accessed not while is being accessed.
It monitors Windows Internet Explorer
I have also researched the httplistener but to no avail.
Do you have any solution?
Please let me know if you require more details
This may or may not be valid for your situation, but I had to do something similar with an Intranet website (cross-browser so it was a little harder than just with IE) recently. My solution was to setup a client-side application which hosts a WCF service. Then, when the user clicks a link on the web page (or raises any event, such as, $(document).ready) it sends an message back to the server telling the server to connect to the IP address associated with the current session (really just the IP Address on the request) on a known port. This connection is made to the client side application which is listening at that IP address and port for instructions on what to do (in my case it is dynamically compiling code in the request and running it).
That of course will only work for Intranet websites. A more general approach that will work for IE across the internet, is to create a IE extension (or maybe a Silverlight application) that talks on localhost. I've never done it, so I can't tell you how or if it is actually possible (but in principle seems possible).
If you don't have access to the website at all then perhaps using SharpPCAP or the Fiddler API would work for you.
Assuming the question is "I want to know when a program on my local computer accesses a give web page": A transparent http proxy is likely approach you want to take. Check out Fiddler to see if it is exactly what you want.
If your question is more "I want to know when a particular page is hit on my remote server": There are plenty of monitoring tools that parse web server logs and event logs to know state of the server. If you want to do something yourself and control the server's code - collect hit information for the page you are interested and provide some page that reports this data.
After few hours of work I have found a solution, not the most elegant one so far,(and at times causes a memory dump) but it does what I need.
Thanks
Just last edit, I solved the crash issue by adding a time so it checks the page every sec or so.
once again thanks for your iterest in my question.
class wait
{
private static System.Timers.Timer aTimer;
public void timed1()
{
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//NetKeyLogger klog = new NetKeyLogger();
// Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
Kelloggs.Program KKA = new Kelloggs.Program();
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename.Equals("iexplore"))
{
string ddd = (ie.LocationURL);
// Console.WriteLine(ddd);
if (ie.LocationURL == "http://www.testPage.com/")
{
Console.WriteLine("Page found");
// Console.ReadLine();
aTimer.Enabled = false;
KKA.Maino();
}
}

Using a C# Timer for regular events in ASP.NET

I am working with an ASP site which requires a "reminder" email to be sent out every x, y and z minutes. I have attempted to start a timer upon an event (like a button click or page load) but this proved to be unreliable as the timers would be disposed of when the server performed an automatic backup or when the aspx.cs file was updated.
My new idea is to have a timer constantly running (a check is performed on a page load which ensures its running) and, when it elapses, it checks to see if either x, y or z minutes have elapsed. So if y elapses, it needs to send out a "reminder" email and then restart y's timer.
void ParentTimer_Elapsed(object sender, ElapsedEventArgs e)
{
foreach(Timer childTimer in ChildTimerList)
{
if(childTimer.Enabled == false) // And therefore has elapsed
{
sendReminderEmail(childTimer);
childTimer = checkAndSetCorrectInterval(childTimer);
childTimer.AutoReset = false;
childTimer.Enabled = true;
}
}
}
The list ChildTimerList would obviously contain x, y and z.
Can anybody forsee me running into any problems with this, or are there any better ways to approach it? My perfect solution would be a timer running costantly which doesn't need to be started upon an event but I don't think this is possible with ASP.
Furthermore, where should I initialise my parent timer and childlist variables? In a class within the App_Code folder or, statically, in a code-behind aspx.cs page?
Thanks in advance.
EDIT:
Yes, I do mean ASP.NET... :)
I would probably implement this with a simple console application (responsible for sending e-mails) and Task Scheduler in Windows (responsible for running the application on a schedule). Keep it simple. And robust.
Edit: Provided that you are in control of the server - it will probably not be the best solution in a shared hosting environment where you're only allowed to run web apps.

Increasing the Lifetime element for EWS Streaming Subscription Connection

Using Microsoft's EWS, we're able to listen to a mailbox and take actions when a new email comes in. However, I can't figure out how to avoid the connection timing out.
Per Microsoft, here is the constructor for a StreamingSubscriptionConnection:
public StreamingSubscriptionConnection (
ExchangeService service,
int lifetime
)
In my app, I've coded it as follows:
service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
StreamingSubscriptionConnection conn = new StreamingSubscriptionConnection(service, 30);
In other words, I've got the timeout (lifetime) set to 30 minutes, because that's the highest I've been able to set it. How can I increase this? Or, how can I trick this subscription into staying alive, even if ~45 minutes transpire between incoming emails?
30 minutes is a hard limit. You can not change it to a higher value.
To solve this issue, wire up a handler to the OnDisconnected handler of the OnDisconnect event of the connection instance. Restart the subscription from there (just call connection.Open() from that handler).
If anyone else is interested, this is how I am accomplishing this.
I want to keep the connection open, so I am resetting it in the OnDisconnect handler.
However, before resetting it, I check the private "subscriptions" dictionary on the connection object using reflection.
This allows me to unsubscribe from my connections elsewhere in my code (OnNotificationEvent), and when all subscriptions have been unsubscribed from, I am then able to close the connection.
Here is my Code:
void connection_OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
var c = (Dictionary<string, StreamingSubscription>)typeof(StreamingSubscriptionConnection).GetField("subscriptions",System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(sender);
if (c.Count > 0)
{
// reopen the connection
((StreamingSubscriptionConnection)sender).Open();
using (var db = new Metrics_DatabaseEntities())
{
PushNotificationTest pt = new PushNotificationTest();
pt.RetObj = "Connection reset";
db.PushNotificationTests.Add(pt);
db.SaveChanges();
}
}
else
{
using (var db = new Metrics_DatabaseEntities())
{
PushNotificationTest pt = new PushNotificationTest();
pt.RetObj = "Connection closed!";
db.PushNotificationTests.Add(pt);
db.SaveChanges();
}
}
}
Please disregard the poor way that this is written, this is just my first version, as I plan to write this more cleanly soon. I just thought I would share my methodology with folks that might be interested.
If people are interested, here's the little bit of logic that got added.
I added this to my Start method:
conn.OnDisconnect +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
I then added the OnDisconnect method:
private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
Start();
}
Ultimately, this still needs improved, because this simply times-out and reconnects every half-hour, regardless of incoming email activity. I'd rather get something in place that resets the counter every time a new message comes in. Then, it would only time-out a couple times per day, instead of 48! Still, this is serving its purpose of keeping my email-listening program online.

How to programmatically detect when the OS (Windows) is waking up or going to sleep

Background
My son likes to use his laptop when he's not supposed to and I just thought it would be handy if I could write an application that would email me whenever he opened / closed his laptop.
(I'd even settle for something that notified me when there was network traffic on the machine)
Question
How do you programmatically detect when an OS is waking up or going to sleep? I found this link from this related post. But that covers OS X. I'm looking for the same thing for Windows 7.
(I'd like to do this in Java, if possible, but I'd settle for C#/C++)
Easiest way is not to write any code at all, even though this is stack overflow. Click Start, type Schedule and choose Scheduled Tasks. Set one up (click Create Task) and set a Trigger when the machine is unlocked. For the Action, have it send you an email.
Repeat for startup and when a user logs in, if you want. Done.
You're going to want to create a window and watch for the WM_POWERBROADCAST message (http://msdn.microsoft.com/en-us/library/aa373248%28v=vs.85%29.aspx) and check the wParam for your desired action. For example, your window should receive a WM_POWERBROADCAST with PBT_APMSUSPEND as the wParam when the system is about to enter a suspended state (i.e. closing a laptop). Resuming seems to have a few different wParam values: PBT_APMRESUMESUSPEND, PBT_APMRESUMECRITICAL and PBT_APMRESUMEAUTOMATIC
I search for a long time and found that this was the best way, the 'Sleep'-event was never working before:
private ManagementEventWatcher managementEventWatcher;
private readonly Dictionary<string, string> powerValues = new Dictionary<string, string>
{
{"4", "Entering Suspend"},
{"7", "Resume from Suspend"},
{"10", "Power Status Change"},
{"11", "OEM Event"},
{"18", "Resume Automatic"}
};
public void InitPowerEvents()
{
var q = new WqlEventQuery();
var scope = new ManagementScope("root\\CIMV2");
q.EventClassName = "Win32_PowerManagementEvent";
managementEventWatcher = new ManagementEventWatcher(scope, q);
managementEventWatcher.EventArrived += PowerEventArrive;
managementEventWatcher.Start();
}
private void PowerEventArrive(object sender, EventArrivedEventArgs e)
{
foreach (PropertyData pd in e.NewEvent.Properties)
{
if (pd == null || pd.Value == null) continue;
var name = powerValues.ContainsKey(pd.Value.ToString())
? powerValues[pd.Value.ToString()]
: pd.Value.ToString();
Console.WriteLine("PowerEvent:"+name);
}
}
public void Stop()
{
managementEventWatcher.Stop();
}
A very simple, perhaps crude, but effective way may be to have a program with a timer firing every minute. If the timer fires and it's been, say, 5 minutes of real time since its last execution then you can likely assume that the computer was sleeping since it's unlikely that your thread was unable to be scheduled for so long.
The other reason for the difference may be a clock adjustment, like DST or a manual change, but that kind of "noise" should be very low, in your scenario.
You could write a simple app and register it as a Windows service, to be started automatically at system startup. This app could then do whatever you want when it starts. And if it's a proper Windows app, it can register to get notification about impending system shutdown too (I don't remember the details but I implemented this in a C++ MFC app many years ago).
If you prefer Java, you could register your app as a service via a suitable service wrapper like Tanuki (it seems they have a free Community License option). Although this might be overkill. And it may be possible to get notification about the JVM shutting down when the system is closing (but I have no concrete experience with this).
http://www.pinvoke.net/default.aspx/powrprof.CallNtPowerInformation - Check out the link. It has almost all win32api for all windows function. You can call power management feature directly in your windows 7 laptop. For that create a Windows Service , that will use these specific api to notify the machine state.

Categories

Resources