Stall Internet Activity When App is Terminated - c#

I'm messing around with the FiddlerCore and .NET and making an Internet Filter application. I'd like to "stall" or prevent Internet Activity if the app isn't running, similar to how Covenant Eyes behaves when it is terminated or logged out.
I'd like to implement a similar behavior. I tried just not closing the FiddlerCore at all, which works but the proxy can easily be removed by anyone who knows what they're doing.
Doing this:
Fiddler.FiddlerApplication.Startup(8877,fcsf);
Fiddler.FiddlerApplication.BeforeRequest += new SessionStateHandler(FiddlerApplication_BeforeRequest);
Console.ReadLine();
and never calling Fiddler.FiddlerApplication.Shutdown(); works, as mentioned (HTTP[s] connections fail), but connectivity is easily restored by removing that proxy.
I tried setting FiddlerCore to not be the system proxy (using: FiddlerCoreStartupFlags fcsf = FiddlerCoreStartupFlags.Default;
fcsf = (fcsf & ~FiddlerCoreStartupFlags.RegisterAsSystemProxy); ) but it still seemed to setup a proxy.
Basically, I'd like to hang connectivity when the app stops running, and restore it when it loads back up. Any ideas? Lemme know if i need to provide any more information. Thanks!

I'm pretty sure you can't do this. Fiddler is just a proxy, and Windows allows users to change their proxy settings.

Related

Why can't a windows service created in C# detect that a screen saver is currently running?

As part of some work I need to get done for Windows 10, I have written a code in C# that essentially detects every minute whether a PC is in screen saver mode or not, and it writes to a table in MySQL the relevant status ("PC in use" if the screen saver is off, "available PC" if the screen saver is on).
I did this using (full link if required - https://www.codeproject.com/Articles/17067/Controlling-The-Screen-Saver-With-C):
// Returns TRUE if the screen saver is actually running
public static bool GetScreenSaverRunning( )
{
bool isRunning = false;
SystemParametersInfo( SPI_GETSCREENSAVERRUNNING, 0,
ref isRunning, 0 );
return isRunning;
}
The code works flawlessly in console application mode (I made a loop to test it out over a minute with a check up on screen save status every 10 seconds), this means in MySQL the status was set correctly every time, depending on the screen save status at the moment of the check up.
The problem occurs when I use this code for a windows service. The service is installed correctly, the log on tab is set on Local System (I also tried with the logged in user instead, same results) and I allow the service to interact with the desktop, just in case, but the difference here is that no matter if the PC enters screen save or not, it always returns false on GetScreenSaverRunning(), thus setting the status of the PC in MySQL as "PC in use", even if the screen saver is on at the moment of check up.
I get the sense that the problem isn't in the code itself, since it works without any issues as a console application, but perhaps something behind the scenes. I tried to search here and on many other websites, haven't found anything related to such a problem.
Does anyone have any idea at all what might be the issue? Any help and/or suggestions will be greatly appreciated!
Thank you in advance.
(I could post the code if required, but it is pretty much straight forward and the main part of it, controlling the screen save detection, is taken from the website mentioned above, afterwards it's a simple if (GetScreenSaverRunning() == true) )
Ever since Vista, Services are barred from a Interactive Session. Even if they run under the same rights, they do not get a interactive Session. I would guess that is getting in the way here.
While you can overwrite this behavior in the Service settings, this is not adviseable for new code. Consider making this a Background Task started by the Task Sheduler instead.
Because the windows service runs in different session then the windows logon. You can't interact with the desktop related services unless you run the windows service in win logon session. There used to be an option in Windows service manager where you can set the properties to "Interact with desktop session" but I don't think that ever worked.
There's a work around to run the windows service using the win logo session.
See this helper class that can get the current logged on user session and interact with the desktop services. https://github.com/murrayju/CreateProcessAsUser/blob/master/ProcessExtensions/ProcessExtensions.cs

Programmatically enabling Windows 8 Pro mobile broadband device

Background
The company I work on is developing a kiosk-like application for tablets running Windows 8 Pro (on desktop mode). The user shouldn't be able to access anything that isn't the application itself: charms will be disabled, the taskbar will be hidden behind the application, etc.
This also means the user shouldn't be able to change network settings, leaving the responsability to keep the device always connected to us. Up to now, I had success using the Mobile Broadband API to assure the device is connected whenever there's a mobile network available. It'll detect disconnect events and try to connect again.
The Problem
Although the user shouldn't be able to do it, I'm considering the case where the user follows this steps:
User opens right-side charm,
clicks on Settings,
clicks on Network,
clicks on More PC Settings,
clicks on Wireless, and
disables the mobile broadband device.
I would like to be able to revert this programmatically and enable it again.
The Attempts
I have tried some different ways to force 3G being reenabled. Most of them give me the same result: they supposedly enable the device without errors, but I still cannot use it. Enable-NetAdapter in Powershell doesn't throw errors, and the Enable method of Win32_NetworkAdapter appears to work, but no dice.
I thought maybe the method IMbnRadio::SetSoftwareRadioState could be what I'm after, but I can't get to it when the device is disabled. The method IMbnInterfaceManager::GetInterfaces throws a COMException claiming the element could not be found (HRESULT = 0x80070490).
MbnInterfaceManager mbnInterfaceManager = new MbnInterfaceManager();
IMbnInterfaceManager interfaceManager = (IMbnInterfaceManager)mbnInterfaceManager;
// The following line throws a COMException:
IMbnInterface[] interfaces = (IMbnInterface[])interfaceManager.GetInterfaces();
mobileInterface = interfaces[0];
mobileRadio = (IMbnRadio)mobileInterface;
uint requestId;
mobileRadio.SetSoftwareRadioState(MBN_RADIO.MBN_RADIO_ON, out requestId);
Is there a way to override user preferences set on "More PC Settings?"
I found a sketchy way to solve this. Keep in mind this is undocumented, wrong, shameless and immoral, and will probably break eventually. The client is aware of this, but prefers to keep the access to the OS limited.
The setting in case is saved in the Registry. At least in the computers I've checked, it's stored in HKLM\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\0022 in a key named RadioOff.
The Airplane Mode setting is also stored in the Registry, but in a different place. It's at HKLM\SYSTEM\CurrentControlSet\Control\RadioManagement\SystemRadioState in a key named (Default).
After changing these keys and rebooting, everything seems to work fine. I'll repeat though: you really shouldn't be doing this, especially the Airplane Mode thing.

In need of some advice controlling a C# winforms application via a asp.net website

I'm working on a little project for a basic Youtube remote control, whereby I have a helper app running on my PC, and then can send commands from a website accessed via the web browser on my phone.
Reading through threads on other sites from people trying to do the same thing I've realized it is not a concept that most people would be comfortable with, but I am struggling to think of another way to do it beyond writing a native app for my phone and having it communicate with the helper application internally via WLAN(Would be happy to do this, but don't have the cash to spring for a new mac to develop for my iphone).
If I were to stick with the Website/Winforms model, is there a way to do this in such a way that (most) people would be comfortable running?
The ideas I had so far were:
a) Build a web server into the helper app(Though not sure of the logistics of having it host an ASP.net site)
b) Host the site externally, and have the helper app periodically poll a database/webservice on a server to receive commands (Sketchy and i imagine very resource heavy)
Sorry for the wall of text, I'm capable of running with an idea and building it, I'm just not sure what is possible and considered the 'best' way to do something like this.
Any advice would be appreciated.
Cheers
Edit Thanks, just to be clear, when i say uncomfortable, I mean - Would you be ok with having a website being able to send potentially ANY command to your computer? This seems to be the problem raised in other discussions about this topic. Obviously I'm not trying to do anything malicious, but as I said, it seemed to be a concern.
If this is a controlled environment where you can always open a port on the firewall for incoming communication, you can have the web app make a WCF call back to the Windows Client through the users firewall.
If not (which is what I suspect), you may be better off polling a web service. Just do it every few seconds and whatever you're checking in that web service call (a database?) make sure it's well optimized. Perhaps just have it return some status int/enum or something very light weight to instruct the client on the next call to make (0 = no update, 1 = command1, 2 = command2, etc).
As for how you do the polling, you could do something like:
int seconds = 4;
System.Timers.Timer _clientTimer = new System.Timers.Timer(seconds * 1000);
_clientTimer.AutoReset = false;
_clientTimer.Elapsed += clientTimer_Elapsed;
_clientTimer.Start();
private void clientTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
// Connect to web service, get status, if status != 0 do something...
}
finally
{
_clientTimer.Start();
}
}
NOTE: the auto-reset = false means that each time the Elapsed event fires, the timer is stopped. In the approach I've taken, I let the timer stop so the client can process the web service results and then start the timer once again after it's done. This will help prevent multiple requests from piling up if a connection is real slow.
That's all I can think of :)

Set service dependencies after install

I have an application that runs as a Windows service. It stores various things settings in a database that are looked up when the service starts. I built the service to support various types of databases (SQL Server, Oracle, MySQL, etc). Often times end users choose to configure the software to use SQL Server (they can simply modify a config file with the connection string and restart the service). The problem is that when their machine boots up, often times SQL Server is started after my service so my service errors out on start up because it can't connect to the database. I know that I can specify dependencies for my service to help guide the Windows service manager to start the appropriate services before mine. However, I don't know what services to depend upon at install time (when my service is registered) since the user can change databases later on.
So my question is: is there a way for the user to manually indicate the service dependencies based on the database that they are using? If not, what is the proper design approach that I should be taking? I've thought about trying to do something like wait 30 seconds after my service starts up before connecting to the database but this seems really flaky for various reasons. I've also considered trying to "lazily" connect to the database; the problem is that I need a connection immediately upon start up since the database contains various pieces of vital info that my service needs when it first starts. Any ideas?
Dennis
what your looking for is SC.exe. This is a command line tool that users can use to configure services.
sc [Servername] Command Servicename [Optionname= Optionvalue...]
more specificly you would want to use
sc [ServerName] config ServiceName depend=servicetoDependOn
Here is a link on the commandlike options for SC.EXE
http://msdn.microsoft.com/en-us/library/ms810435.aspx
A possible (far from ideal) code solution:
In you startup method code it as a loop that terminates when you've got a connection. Then in that loop trap any database connection errors and keep retrying as the following pseudo code illustrates:
bool connected = false;
while (!connected)
{
try
{
connected = openDatabase(...);
}
catch (connection error)
{
// It might be worth waiting for some time here
}
}
This means that your program doesn't continue until it has a connection. However, it could also mean that your program never gets out of this loop, so you'd need some way of terminating it - either manually or after a certain number of tries.
As you need your service to start in a reasonable time, this code can't go in the main initialisation. You have to arrange for your program to "start" successfully, but not do any processing until this method had returned connected = true. You might achieve this by putting this code in a thread and then starting your actual application code on the "thread completed" event.
Not a direct answer put some points you can look into
Windows service can be started Automatically with a delay. You can check this question in SO for some information about it.
How to make Windows Service start as “Automatic (Delayed Start)”
Check this post How to: Code Service Dependencies

check internet connection in linux using mono?

is there any way to check internet connection status in linux using mono
If it's desktop app, you could query NetworkManager (which is the network connection manager on most Linux desktops) over d-bus, using the NDesk.DBus library.
See Banshee for an example: http://git.gnome.org/cgit/banshee/tree/src/Core/Banshee.Services/Banshee.Networking/NetworkManager.cs
Apart from what Michael already suggested for a desktop application, you can also do something like:
foreach (NetworkInterface ni in NetworkInformation.GetAllNetworkInterfaces ()) {
// Check that any or all of:
// -ni.OperationalStatus == OperationalStatus.Up
// -that ni.NetworkInterfaceType is ethernet or wireless80211
// -ni.GetIPProperties() has a gateway and a DNS server
// ...
}
No matter what you end up using, it won't be reliable.
I see it all the time with Windows Vista and 7 at home. I use a home network, so my computers are always "connected." However, they are not always connected to the Internet.
That said, I would recommend checking the network interfaces as Gonzalo said. It is your best bet.
I would not rely on NetworkManager being present. I hate that thing and turn it off whenever I can. It is huge, ungainly, has an ugly name, relies on junk like HAL and DBUS. Early versions permanently put me off because they didn't work unless you were logged in to a GUI. It also collected bug work-arounds for wifi that were completely ridiculous in an open-source operating system that should have just fixed the original bugs. That led to other wifi managers and the command-line not being able to work properly and people being told to use NetworkManager, only because no one ever bothered to fix the actual bug!
You could try to open your connection as it is needed. If that fails display an error message.
Alternatively, if you really need a general check (e.g. at application start) you could try to make HTTP requests to one or more omnipresent websites like google.com. (Or what ever protocol you mean by "internet").
Check out HttpWebRequest.

Categories

Resources