Background service to check internet connectivity in Xamarin forms C# - c#

I have implemented a function in Xamarin (C# based code) that check for internet connectivity. I have access this method called CheckInternet() through a Dependency Service in the PCL.
What I want to achieve is to implement a sort of Background Service that runs when the app is running to keep checking internet connectivity. My app detects a list of items and send it to a server if there is an internet connection. If no, the item color remains red on my screen.
And once the internet connectivity is back, the items that have not been sent to the server are automatically sent.
Can someone help me to achieve this background service in C# ?

I think you can take a look to this plugin
and this event
/// <summary>
/// Event handler when connection changes
/// </summary>
event ConnectivityChangedEventHandler ConnectivityChanged;
CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
page.DisplayAlert("Connectivity Changed", "IsConnected: " + args.IsConnected.ToString(), "OK");
};

In addition to #alessandro-caliaro answer; I believe what you need to look for is how to implement backgrounding in your apps. Its slightly tricky to get it working in forms projects, as it needs plaform-specific implementation.
These are two articles that talk about this concept in detail (and illustrate how to implement resilient network calls using backgrounding techniques for each platform and also, have shared logic at PCL level).
http://arteksoftware.com/backgrounding-with-xamarin-forms/
https://xamarinhelp.com/xamarin-background-tasks/

Related

Detect is when a windows service has been deleted

Is there a way to detect when a windows service has been deleted? I've checked the event log but it doesn't pick up deleted actions only added.
I believe there may be a way using audit logs but I'm unsure how to do this?
Any help is much appreciated.
Thanks
While there is no trace of service deletion in Event or Audit logs, what you can do is create a small console app that detects if a service exists and attach this app to Windows Task Scheduler such that it is scheduled to execute based on frequency or a Trigger that you can customize to your requirements such that you will receive an alert if a service has been added or removed etc..
The console app is designed such that on the first run, it logs all
the services on the system and on the subsequent runs it will be
tracking changes made on the services via servicesRemoved and
servicesAdded, with this we can decide what action to take when a
service has been modified
Console App: ServiceDetector.exe
static void Main(string[] args)
{
var path = #"C:\AdminLocation\ServicesLog.txt";
var currentServiceCollection = ServiceController.GetServices().Select(s => s.ServiceName).ToList(); //Queries the most current Services from the machine
if (!File.Exists(path)) //Creates a Log file with current services if not present, usually means the first run
{
// Assumption made is that this is the first run
using (var text = File.AppendText(path))
{
currentServiceCollection.ForEach((s) => text.WriteLine(s));
}
return;
}
// Fetches the recorded services from the Log
var existingServiceCollection = File.ReadAllLines(path).ToList();
var servicesRemoved = existingServiceCollection.Except(currentServiceCollection).ToList();
var servicesAdded = currentServiceCollection.Except(existingServiceCollection).ToList();
if (!servicesAdded.Any() && !servicesRemoved.Any())
{ Console.WriteLine("No services have been added or removed"); return; }
//If any services has been added
if (servicesAdded.Any())
{
Console.WriteLine("One or more services has been added");
using (var text = File.AppendText(path))
{
servicesAdded.ForEach((s) => text.WriteLine(s));
}
return;
}
//Service(s) may have been deleted, you can choose to record it or not based on your requirements
Console.WriteLine("One or more services has been removed");
}
Scheduling Task
Windows Start > Task Scheduler > Create Basic Task > Set Trigger > Attach your exe > Finish
You're right that deleting a Windows Service does cause an event to be added to the System Event Log (source: https://superuser.com/questions/1238311/how-can-we-detect-if-a-windows-service-is-deleted-is-there-an-event-log-id-for-i).
AFAIK there's no audit policy to audit the deletion of a service and I think if there were I think it would be listed here: https://learn.microsoft.com/en-us/windows/security/threat-protection/auditing/basic-audit-process-tracking
I assume polling ServiceController.GetServices() is out of the question because your program might not be running when the service is uninstalled?
There are lots of ways to build instrumentation, until you learn what constitutes good instrumentation. My how-to is essentially taken directly from the Wikipedia entry https://en.wikipedia.org/wiki/Instrumentation.
Instrumentation How-to
http://www.powersemantics.com/e.html
Non-integrated
Primary data only
Pull not push
Organized by process
Never offline
The solution to the problem of measuring indicators exists, but you're stuck conceptualizing how to also have "push-based" instrumentation signal another system. As my E article explains, instruments should always pull data never push it. Event-driven signalling is a potential point of failure you don't need.
To clear up any indecisiveness or doubts you may have about building a separate application, monitors are normally independent (non-integrated as Wikipedia says) processes. So saying your monitor "might not be running" means you have not chosen to build a real non-integrated monitor, one which is always on. Your consumer system doesn't correctly model instrumentation, because it integrates the check in its own process.
Separate these responsibilities and proceed. Decide how often the instrument should reasonably poll for deleted services and poll the data with a timer. If you use the API call simon-pearson suggested, you can also detect when services have been added. Of course, the monitor needs to locally cache a copy of the service list so that indicators can infer what's been added or removed.

Receiving either WM_QueryEndSession or WM_WTSSESSIONCHANGE in WinPE10 in C#

My apologies if this question has been asked and already answered, I have spent the best part of three days experimenting with WndProc() in WinPE (for Windows 10).
How do I "Catch" Messages through WndProc() (or a Handler Routine) in WinPE (Windows 10)?
I have a custom application(written in C# .Net 4.5.2) that is launched by WinPEShl.exe, on boot of WinPE. This is currently an Application that provides access to other applications to enable Windows deployment or Image Capture.
While this Application may not always be the current Windows Form, there a one or two routines that need to be completed before Windows PE has shutdown. I would like this to happen on either the WM_QUERYENDSESSION/WM_ENDSESSION or WTS_SESSION_CHANGE notifications through the overriden WndProc() function.
Currently this is my WndProc() function:
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref Message m)
{
// Listen for operating system messages.
if (m.Msg == WM_QUERYENDSESSION)
{
Program.WriteLogFile(4, 1, "WM_QUERYENDSISSION: received. Return Bool=True");
}
if (m.Msg == WTS.WM_WTSSESSION_CHANGE)
{
int wValue = m.WParam.ToInt32();
if (wValue == WTS.WTS_SESSION_LOGOFF)
{
//Write my darn Log file!
Program.WriteLogFile(4, 1, "WM_WTS_SESSION_LOGOFF: received. Return Bool=True");
}
if (wValue == WTS.WTS_CONSOLE_DISCONNECT)
{
Program.WriteLogFile(4, 1, "WM_WTS_SESSION_DISCONNECT: received. Return Bool=True");
}
}
base.WndProc(ref m);
}
Program.WriteLogFile() is a Log File writer (as it says!) that will be used to report that the system is shutting down.
From this Link I am aware that as WinPE is a Stream lined version of Windows, with only a small number of API's being available for usage. I have looked through both of the MinCore.lib sets for both Windows API Sets mentioned - resulting in nill success for finding any function in relation to the WndProc() holder function. I have evensearched OneCore.lib aswell.
I did however find the WTSRegiSessionNotifications() functions. Again even though they register fine in WinPE, my Shell App doesn't receive the messages if another application shuts down the system (such as Windows Setup on completion of the first phase).
Testing in Windows provides both results in the associated application log file.
Should I be using a hidden console app, to capture the CTRL_LOGOFF_EVENT/CTRL-SHUTDOWN_EVENT, or should i be using a service (and have all log writing routed through it)?
Log files from Windows 10 (working as should be) and WinPE available on request.
Thanks for any and all help in this matter.
Kind regards
Richie
I'm not sure why you're not using the regular winforms form lifetime events. I'm guessing you're somewhat more used to C-oriented ways of doing things?
If you've built a winpeshl.ini that starts your program, and it's the only program listed (beyond winpeinit.exe), then when it shuts down, PE shuts down. This is true even if you spawn other applications from your main program (via System.Diagnostics.Process).
So, don't list a lot of programs in winpeshl.ini. Let your one-and-only main program start the rest.
FWIW, I've got a similar app...does image capture, deploy and periodic maintenance. We put our winPE in it's own partition and do a lot of active BCD management to make it boot when we want. I've closed off all the "normal" shutdown routes. Yes, I suppose a persistent user can circumvent...but if they're determined, so be it...but we haven't had an issue with that.

Disabling Wifi on Windows 10/Surface Pro4 programatically?

I have a Surface Pro 4 that is being used in a medical environment and we would like to be able to disable to WiFi on the device when certain applications are running. Is this possible?
Disable is a relative term and as long as the device can't communicate over the wifi, even if technically active, that would meet the requirements. I wasn't able to find any way to do this though.
We could disable Wifi completely but would prefer to have it as an option for the users of the device when the specific applications aren't running.
The application in question is written in C#
You can do this with the Windows.Devices.Radios.Radio class by calling SetStateAsync(...).
There's a full example available at Microsoft's GitHub page, here's a snippet:
private async void SetRadioState(bool isRadioOn)
{
var radioState = isRadioOn ? RadioState.On : RadioState.Off;
Disable();
await this.radio.SetStateAsync(radioState);
NotifyPropertyChanged("IsRadioOn");
Enable();
}

Azure Application Insights custom response metric

I need some help to find a good pattern for a custom application insights metric.
Environment
I have a custom Windows Service running on multiple Azure VMs.
I can successfull add Events to my Monitoring instance on Azure.
Goal
I want to create a custom metric that allows me to monitor if my windows services are running and responding per instance. It would be perfect if it acts like the respond timeout in website metric.
Each service instance has a custom maschine related identifier, like:
TelemetryClient telemetry = new TelemetryClient();
telemetry.Context.Device.Id = FingerPrint.Instance;
Now I wnat to create a alert if one of my Service instances (Context.Device.Id) is not running or responding.
Question
How to achive this?
Is it even possible or usefull to Monitor multiple instance of one service type onside on application insight? Or must I open one single application insight per instance?
Can anybody help me?
Response to Paul's answere
Track Metric Use TrackMetric to send metrics that are not attached to particular events. For example, you could monitor a queue length at regular intervals.
If I do so, whats happens if my server made a restart (update or somethink) and my service don't start up. Now the service did't send a TrackMetric to the application insight and no alert is raised because the value don't drop below 1, but the Service is still not running.
Regards Steffen
I found a good working solution, with only a few simple steps.
1) Implement a HttpListener instance on a service port (for example 8181) with a simple text response "200: OK"
2) Add a matching endpoint to the azure VM imstande
3) Create a default web test on "myVM.cloudapp.net:8181" with checkup of response text
Work great so far and matches all my needs! :)
Per the documentation on Azure portal:
https://azure.microsoft.com/en-us/documentation/articles/app-insights-api-custom-events-metrics/#track-metric
Track Metric
Use TrackMetric to send metrics that are not attached to particular events. For example, you could monitor a queue length at regular intervals.
Metrics are displayed as statistical charts in metric explorer, but unlike events, you can't search for individual occurrences in diagnostic search.
Metric values should be >= 0 to be correctly displayed.
c# code looks like this
private void Run() {
var appInsights = new TelemetryClient();
while (true) {
Thread.Sleep(60000);
appInsights.TrackMetric("Queue", queue.Length);
}
}
I don't think there is currently a good way to accomplish this. What you're actually looking for is a way to detect a "stale heartbeat." For example, if your service was sending up an event "Service Health is okay", you'd want an alert that you haven't received one of those events in a certain amount of time. There aren't any date/time conditional operators in AI's alert system.
Microsoft might explain that this scenario is not intended to be satisfied by AI, as this is more of a "health checking" system's responsibility, like SCOM or Operation Insights or something else entirely.
I agree this is something that needs a solution, and using AI for it would be wonderful (I've already attempted to accomplish the same thing with no luck); I just think "they" will say its not a scenario in the realm of responsibility for AI.

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

Categories

Resources