How to detect if RDS (Remote Desktop Service) is enabled? - c#

I'm searching for a method to detect if RDS (Remote Desktop Service) is enabled on a Windows 10 / 11 Client or not. The results found by google dont work. (Path: HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server, Value: fDenyTSConnections)
Any ideas?

As #Uwe Keim commented, you can check if the Remote Desktop Service is running using the ServiceController package from Microsoft: https://www.nuget.org/packages/System.ServiceProcess.ServiceController/7.0.0?_src=template
The Remote Desktop Service's "Service Name" is TermService and the "Display Name" is Remote Desktop Services. Check against those properties and then check if the service is running or not.
using System.Linq;
using System.ServiceProcess;
bool IsRemoteDesktopServiceRunning() {
ServiceController[] serviceControllers = ServiceController.GetServices();
return serviceControllers.FirstOrDefault((serviceController) => {
if (serviceController.ServiceName != "TermService")
return false;
if (serviceController.DisplayName != "Remote Desktop Services")
return false;
if (serviceController.Status != ServiceControllerStatus.Running)
return false;
return true;
}) != null;
}
Console.WriteLine("IsRemoteDesktopServiceRunning: " + IsRemoteDesktopServiceRunning());
Or if you want to actually check if it's just enabled, check the StartType property for ServiceStartMode.Disabled:
if (serviceController.StartType == ServiceStartMode.Disabled)
return false;

Related

Best way to check if ubuntu service has stopped in c#

I want to get an alert when a service (grafana or influxdb) in an Azure virtual machine (Ubuntu 16.04) has stopped. I'd like to use c# to connect to the VM and check the status of grafana and influxdb services. Can anyone share a code sample that implements this?
Both services provide health endpoints that can be used to check their status from a remote server. There's no need to open a remote shell connection. In fact, it would be impossible to monitor large server farms if one had to SSH to each one.
In the simplest case, and ignoring networking issues, one can simply hit the health endpoints to check the status of both services. A rough implementation could look like this :
public async Task<bool> CheckBoth()
{
var client = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
};
const string grafanaHealthUrl = "https://myGrafanaURL/api/health";
const string influxPingUrl = "https://myInfluxURL/ping";
var (grafanaOK, grafanaError) = await CheckAsync(client, grafanaHealthUrl,
HttpStatusCode.OK, "Grafana error");
var (influxOK, influxError) = await CheckAsync(client, influxPingUrl,
HttpStatusCode.NoContent,"InfluxDB error");
if (!influxOK || !grafanaOK)
{
//Do something with the errors
return false;
}
return true;
}
public async Task<(bool ok, string result)> CheckAsync(HttpClient client,
string healthUrl,
HttpStatusCode expected,
string errorMessage)
{
try
{
var status = await client.GetAsync(healthUrl);
if (status.StatusCode != expected)
{
//Failure message, get it and log it
var statusBody = await status.Content.ReadAsStringAsync();
//Possibly log it ....
return (ok: false, result: $"{errorMessage}: {statusBody}");
}
}
catch (TaskCanceledException)
{
return (ok: false, result: $"{errorMessage}: Timeout");
}
return (ok: true, "");
}
Perhaps a better solution would be to use Azure Monitor to ping the health URLs periodically and send an alert if they are down.
Here is something you can use to connect to Azure linux using SSH in c#
using (var client = new SshClient("my-vm.cloudapp.net", 22, "username", "password​"))
{
client.Connect();
Console.WriteLine("it worked!");
client.Disconnect();
Console.ReadLine();
}
Usually SSH server only allow public key auth or other two factor auth.
Change your /etc/ssh/sshd_configuncomment #PasswordAuthentication yes
# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes
Later you can poll for installed services.
Also for an alternative solution, you can deploy a rest api in your linux VM to check the status of your service and the call it from C# httpclient for the status.
Hope it helps

C# Detect Remote Assistance connection

I have an program in production environment where I like to have a window to open, when a remote assistance are started on the pc, so the person connecting to the pc have some more options. But i can't find anything if this is possible? If so any idea how to detect it?
This can be done but I find it tricky and I generally avoid this. See How to detect RDC from C#.net for more info.
To start RDP listens on port 3389 so something like this should work.
int port = 3389;
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(#"SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp", false))
{
if (key != null)
{
object value = key.GetValue("PortNumber");
if (value != null) port = Convert.ToInt32(value);
}
}
But the port number can be configured so this isn't the best way.
Then there is Pinvoke and Cassia. with Cassia you could do something like:
public bool IsComputerUsedByTS()
{
var tsMgr = new TerminalServicesManager();
var localSvr = tsMgr.GetLocalServer();
var sessions = localSvr.GetSessions();
foreach(var session in sessions)
{
if(session.ConnectionState == ConnectionState.Active ||
session.ConnectionState == ConnectionState.Connected) //Add more states you want to check for as needed
{
return true;
}
}
return false;
}
And last but not least:
System.Windows.Forms.SystemInformation.TerminalServerSession
This uses a forms import but is a very simple solution. If you run your program in a remote desktop environment, this returns true.

Create SharePoint Remote Event Receiver from C# code

I have a sharepoint site with some OOB lists (documents and tasks).
I want to catch list changes in my program.
I tried to create WCF service and Remote Event Reciver (RER) via CSOM for this service, but no messages were catched by the WCF service.
The WCF service and RER are created in simple C# application (console application).
Class for WCF service
public class RemoteEventService : Microsoft.SharePoint.Client.EventReceivers.IRemoteEventService
{
public void ProcessOneWayEvent(SPRemoteEventProperties properties)
{
// some code here
}
public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
{
SPRemoteEventResult result = null;
ClientContext context = null;
// some code here
return result;
}
}
WCF-service creation
using (ServiceHost host = new ServiceHost(typeof(RemoteEventService)))
{
host.Open();
host.Description.Behaviors.Find<ServiceAuthorizationBehavior>().ImpersonateCallerForAllOperations = true;
Console.WriteLine("Started service at " + host.BaseAddresses[0].ToString());
Console.WriteLine("Press <enter> to terminate the Application");
Console.ReadKey(true);
}
Remote Event receiver creation
// check that RER doesn't exist
EventReceiverDefinitionCreationInformation receiverAdded =
new EventReceiverDefinitionCreationInformation();
receiverAdded.EventType = EventReceiverType.ItemAdded;
receiverAdded.ReceiverUrl = SERVICE_URL;
receiverAdded.ReceiverName = "TestDocReceiverAdded";
receiverAdded.Synchronization = EventReceiverSynchronization.Asynchronous;
docList.EventReceivers.Add(receiverAdded);
context.ExecuteQuery();
The RER was created (it is available in debug check on next run of my application) but WCF-service didn't catch any messages.
I have checked that WCF-serivce is available from network where Shapoint Site is hosted.
Im not sure if the user (that is used to connect to sharepoint in my app) have enough permissions to manage sharepoint OOB lists.
Is it posiable to add RER to sharepoint OOB list from NOT sharepoint-app?
If no what is the best way to catch list changes in my program?

Check internet Connection on phone

I wanted to check whether my phone can connect to Internet or not. I have seen several questions already. One of those is Question . It says to use NetworkInterface.GetIsNetworkAvailable() this and i tried it. I have disconnected my PC from internet and Also turned off the DataConnection of the emulator but NetworkInterface.GetIsNetworkAvailable() this always returning true. But simultaneouly i also check for NetworkInterfaceType.None and interestingly it is coming null.
Can anybody explain where i am missing info ?
Attempt : -
public static void CheckNetworkAvailability()
{
// this is coming true even when i disconnected my pc from internet.
// i also make the dataconnection off of the emulator
var fg = NetworkInterface.GetIsNetworkAvailable();
var ni = NetworkInterface.NetworkInterfaceType;
// this part is coming none
if (ni == NetworkInterfaceType.None)
IsConnected = false;
}
any help is appreciated :)
I am using following code to check if the device has access to internet with if it is connected to wifi or data connection..
public void UpdateNetworkInformation()
{
// Get current Internet Connection Profile.
ConnectionProfile internetConnectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
//air plan mode is on...
if (internetConnectionProfile == null)
{
Is_Connected = false;
return;
}
//if true, internet is accessible.
this.Is_InternetAvailable = internetConnectionProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
// Check the connection details.
else if (internetConnectionProfile.NetworkAdapter.IanaInterfaceType != 71)// Connection is not a Wi-Fi connection.
{
Is_Roaming = internetConnectionProfile.GetConnectionCost().Roaming;
/// user is Low on Data package only send low data.
Is_LowOnData = internetConnectionProfile.GetConnectionCost().ApproachingDataLimit;
//User is over limit do not send data
Is_OverDataLimit = internetConnectionProfile.GetConnectionCost().OverDataLimit;
}
else //Connection is a Wi-Fi connection. Data restrictions are not necessary.
{
Is_Wifi_Connected = true;
}
}
Edit:
And for simple internet connection you can use below code.
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
Hope this helps!
The emulator always returns NetworkInterface.GetIsNetworkAvailable() as true, even if you emulate network conditions as having no network.
I faced this problem myself and the only truly way of testing this behaviour is to deploy the application to a physical device running Windows Phone and test it with the data turned off.
NetworkInterface.GetIsNetworkAvailable() checks the network connection and not the internet connection. If you are in any kind of network, then it will return true whether internet is present or not.
You can check the internet connection as following:
using System.Net
private bool IsOnline()
{
try
{
IPHostEntry iPHostEntry = Dns.GetHostEntry("www.wikipedia.com");
return true;
}
catch (SocketException ex)
{
return false;
}
}

Ping to server for external connectivity

I have a c# application that has a module for checks the server connection. The relevant code is like the following:
private void PingCheck(string hostName)
{
using (var p = new Ping())
{
try
{
var pr = p.Send(hostName, 2000);
if (pr.Status != IPStatus.Success)
{
log.ErrorFormat("Ping error! Host = {0}, Ping status = {1}", hostName, pr.Status.ToString());
}
}
catch (Exception exc)
{
log.Error("Ping error!", exc);
}
}
}
We have deployed this application to our server that is inside the same network as the target machine. That's why this method checks internal connectivity. Is there any way to check server external connectivity? Because sometimes server connection is available in our network although connection from external network is down. How can I achieve this?
No, there is not, since you are on the server itself.
Either ping some resource outside to check connectivity, or use the NetworkInterface.GetIsNetworkAvailable() method to check whether there is an active connection.

Categories