C# connect with RDP to windows server 2012 - c#

I need to do the following things:
1) Сonnect to the server
2) Run the application E:\backup\backup.exe
3) copy E:\backup\log.txt in E:\backup\history\ 18.11.16 20-54-32.txt where the file name will be changed to the current time.
4) Disconnect from the server.
Tell me please, possible to do this the following on C #? And if its possible - preferably example or link to the necessary. Thanks.
using System;
//using Cassia;
using MSTSCLib;
namespace rdm
{
class Program
{
static void Main(string[] args)
{
var rdp = new MsRdpClient8NotSafeForScripting();
rdp.Server= "192.168.0.101"; //adress
rdp.Domain = "localdomain"; //domain
rdp.UserName = "test"; //login
rdp.AdvancedSettings8.ClearTextPassword = "123456";//password
try
{
rdp.Connect();
}
catch(Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine(rdp.Connected);
if (rdp.Connected != 0)
{
rdp.Disconnect();
}
Console.ReadKey(true);
}
}
}

Wow....what a lot of flak for a simple can it or can it not be done?
Dunkan...yes it can.
Visit here: C# Custom Remote Desktop Client using RDP 8.0

Related

Connecting the SignalR console client to the server on Azure

I want to deploy a server (on Azure) using SignalR.
And the console client, so that it accepts commands from the server.
The server code was taken from here: https://learn.microsoft.com/ru-ru/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr
Example of a console client from here:https://www.codeproject.com/Articles/804770/Implementing-SignalR-in-Desktop-Applications
using Microsoft.AspNet.SignalR.Client;
using System;
namespace SignalRClient
{
class Program
{
static void Main(string[] args)
{
IHubProxy _hub;
string url = #"https://signalrchatmsdn20210410135946.azurewebsites.net/";
//string url = #"http://localhost:62545";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("BetHub");
connection.Start().Wait();
_hub.On("ReceiveLength", x => Console.WriteLine(x));
string line = null;
while ((line = System.Console.ReadLine()) != null)
{
_hub.Invoke("DetermineLength", line).Wait();
}
Console.Read();
}
}
}
If I run the server locally, everything works (string url = #"http://localhost:62545";)
If I run the server on Azure, it works through the browser. But the console client throws an exception.
System.Net.WebException
jdweng absolutely right.
In my case, it was enough to change the deployment setting.
TLS\SSL settings => HTTPS Only: Off

ServerManager fails with 0x80040154 in c# Winforms app creating simple web application in IIS

I am writing a small app that installs IIS and configures a website before deploying the files to it.
On a freshly reset Windows 10, the first attempt always fails with the 0x80040154 COM+ component failure as documented in This question
I looked at the version I am using and it is the latest and correct one for .net standard (4.8) and not the one meant for .net core
When I press the button to rerun the function it always finishes correctly. I tried using a retry routine, and it fails on each retry, yet runs fine again when the button is pressed. The reason for this I assume is that the server manager object isn't disposed when it hits the catch block since its in a using statement.
I can work around that, but I really want to understand the issue and make a permanent fix.
My routine simply creates a website in IIS and creates an app pool to assign to it.
And it is running with elevated privileges
For reference:
Machine is Windows 10 latest from the downloadable media creator.
Microsoft.Web.Administrator version is 7.0.0.0
App is .net 4.8 standard windows forms
using (var serverManager = new ServerManager())
{
string iisrootdir = drive;
//Check for inetpub/wwwroot
if (!Directory.Exists(iisrootdir)) //Check for Drive D
{
iisrootdir = #"C:\";
}
string iiscmsdir = Path.Combine(iisrootdir, "webdir", "appdir");
if (!Directory.Exists(iiscmsdir))
Directory.CreateDirectory(iiscmsdir);
var settings = new ApplicationSettings();
settings.ReadFromFile();
settings.CMSPATH = iiscmsdir;
settings.SaveToFile();
try
{
string poolName = "DefaultAppPool";
if (serverManager.Sites.Count > 0)
{
Site myDefualtWebsite = serverManager.Sites[0];
if (myDefualtWebsite != null)
{
OnRaiseInstallEvent(new InstallEventArgs("CreateWebsite", ProcessState.Started,
"Remove Default Website"));
serverManager.Sites.Remove(myDefualtWebsite);
serverManager.CommitChanges();
}
}
if (!WebsiteExists("sitename"))
{
mySite.ServerAutoStart = true;
}
Site site = serverManager.Sites["sitename"];
if (!AppPoolExists(poolName))
{
serverManager.ApplicationPools.Add(poolName);
}
ApplicationPool apppool = serverManager.ApplicationPools[poolName];
apppool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
apppool.ManagedRuntimeVersion = "";
serverManager.Sites["sitename"].ApplicationDefaults.ApplicationPoolName = poolName;
foreach (var item in serverManager.Sites["sitename"].Applications)
{
item.ApplicationPoolName = poolName;
}
serverManager.CommitChanges();
apppool.Recycle();
serverManager.CommitChanges();
}
catch (Exception ex)
{
if (ex.Message.Contains("80040154") && errorCount < 4)
{
if (serverManager != null)
serverManager.Dispose();
errorCount++;
OnRaiseInstallEvent(new InstallEventArgs("CreateWebsite", ProcessState.Started,
"Error encountered with COM+ object, trying again: " + errorCount));
CreateWebsite(#"D:\");
}
else
{
if (serverManager != null)
serverManager.Dispose();
errorCount = 0;
OnRaiseErrorEvent(new InstallErrorEventArgs("CreateWebsite", ProcessState.Error, ex));
return false;
}
}
finally
{
serverManager?.Dispose();
}
Thanks for the help Guys. I found the problem.
DISM was running in its own thread. The Process object exited the moment it launched. My function was then attempting to configure IIS before it had finished installing.

Get Linux server time from windows service c#

Is there anyway I can get linux server time from windows service given linux server IP ? I tried to use Cliwrap (https://github.com/Tyrrrz/CliWrap) and wrote the following function but it is not working as well:
public string GetLinuxServerTime()
{
using (var cli = new Cli("bash.exe"))
{
// Execute
var output = cli.Execute("ssh user#10.104.12.114 date");
return "abc";
}
}
Kindly suggest some another way.

How to create a simple local web page using C# windows forms

I am looking to create a simple webpage using C# Windows Forms Application, or a C# Console application.
Running the application will begin hosting a web page at:
http://localhost:3070/somepage
I have read a little bit on MSDN about using endpoints, however being self-taught, this isn't making a ton of sense to me...
In short, this program, when running will display some text on a webpage at localhost:3070.
Sorry for such a vague question, however my hour(s) of searching for a decent tutorial haven't yielded any understandable results...
Thanks for your time!
🛑 2020 Update:
Original answer at the bottom.
Kestrel and Katana are now a thing and I would strongly recommend you look into those things as well as OWIN
Original Answer:
You will want to look into creating an HttpListener, you can add prefixes to the listener such as Listener.Prefixes.Add("http://+:3070/") which will bind it to the port your wanting.
A simple console app: Counting the requests made
using System;
using System.Net;
using System.Text;
namespace TestServer
{
class ServerMain
{
// To enable this so that it can be run in a non-administrator account:
// Open an Administrator command prompt.
// netsh http add urlacl http://+:8008/ user=Everyone listen=true
const string Prefix = "http://+:3070/";
static HttpListener Listener = null;
static int RequestNumber = 0;
static readonly DateTime StartupDate = DateTime.UtcNow;
static void Main(string[] args)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("HttpListener is not supported on this platform.");
return;
}
using (Listener = new HttpListener())
{
Listener.Prefixes.Add(Prefix);
Listener.Start();
// Begin waiting for requests.
Listener.BeginGetContext(GetContextCallback, null);
Console.WriteLine("Listening. Press Enter to stop.");
Console.ReadLine();
Listener.Stop();
}
}
static void GetContextCallback(IAsyncResult ar)
{
int req = ++RequestNumber;
// Get the context
var context = Listener.EndGetContext(ar);
// listen for the next request
Listener.BeginGetContext(GetContextCallback, null);
// get the request
var NowTime = DateTime.UtcNow;
Console.WriteLine("{0}: {1}", NowTime.ToString("R"), context.Request.RawUrl);
var responseString = string.Format("<html><body>Your request, \"{0}\", was received at {1}.<br/>It is request #{2:N0} since {3}.",
context.Request.RawUrl, NowTime.ToString("R"), req, StartupDate.ToString("R"));
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
// and send it
var response = context.Response;
response.ContentType = "text/html";
response.ContentLength64 = buffer.Length;
response.StatusCode = 200;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
}
}
And for extra credit, try adding it to the services on your computer!
Microsoft Relased an Open Source Project called OWIN it is simlar to Node but bottom line it allows you to host web applications in a console application:
You can find more information here:
https://github.com/duovia/duovia-http
http://owin.org/
http://katanaproject.codeplex.com/
But if you insist in creating your personal listener you can find some help here:
http://msdn.microsoft.com/en-us/library/system.net.httplistener(VS.80).aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/b7f476d1-3147-4b18-ba5e-0b3ce8f8a918/want-to-make-a-webserver-with-httplistener

Any way to turn the "internet off" in windows using c#?

I am looking for pointers towards APIs in c# that will allow me to control my Internet connection by turning the connection on and off.
I want to write a little console app that will allow me to turn my access on and off , allowing for productivity to skyrocket :) (as well as learning something in the process)
Thanks !!
If you're using Windows Vista you can use the built-in firewall to block any internet access.
The following code creates a firewall rule that blocks any outgoing connections on all of your network adapters:
using NetFwTypeLib; // Located in FirewallAPI.dll
...
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Used to block all internet access.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "Block Internet";
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
Then remove the rule when you want to allow internet access again:
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Remove("Block Internet");
This is a slight modification of some other code that I’ve used, so I can’t make any guarantees that it’ll work. Once again, keep in mind that you'll need Windows Vista (or later) and administrative privileges for this to work.
Link to the firewall API documentation.
This is what I am currently using (my idea, not an api):
System.Diagnostics;
void InternetConnection(string str)
{
ProcessStartInfo internet = new ProcessStartInfo()
{
FileName = "cmd.exe",
Arguments = "/C ipconfig /" + str,
WindowStyle = ProcessWindowStyle.Hidden
};
Process.Start(internet);
}
Disconnect from internet: InternetConnection("release");
Connect to internet: InternetConnection("renew");
Disconnecting will just remove the access to internet (it will show a caution icon in the wifi icon).
Connecting might take five seconds or more.
Out of topic:
In any cases you might want to check if you're connected or not (when you use the code above), I better suggest this:
System.Net.NetworkInformation;
public static bool CheckInternetConnection()
{
try
{
Ping myPing = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
return (reply.Status == IPStatus.Success);
}
catch (Exception)
{
return false;
}
}
There are actually a myriad of ways to turn off (Read: break) your internet access, but I think the simplest one would be to turn of the network interface that connects you to the internet.
Here is a link to get you started:
Identifying active network interface
Here's a sample program that does it using WMI management objects.
In the example, I'm targeting my wireless adapter by looking for network adapters that have "Wireless" in their name. You could figure out some substring that identifies the name of the adapter that you are targeting (you can get the names by doing ipconfig /all at a command line). Not passing a substring would cause this to go through all adapters, which is kinda severe. You'll need to add a reference to System.Management to your project.
using System;
using System.Management;
namespace ConsoleAdapterEnabler
{
public static class NetworkAdapterEnabler
{
public static ManagementObjectSearcher GetWMINetworkAdapters(String filterExpression = "")
{
String queryString = "SELECT * FROM Win32_NetworkAdapter";
if (filterExpression.Length > 0)
{
queryString += String.Format(" WHERE Name LIKE '%{0}%' ", filterExpression);
}
WqlObjectQuery query = new WqlObjectQuery(queryString);
ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(query);
return objectSearcher;
}
public static void EnableWMINetworkAdapters(String filterExpression = "")
{
foreach (ManagementObject adapter in GetWMINetworkAdapters(filterExpression).Get())
{
//only enable if not already enabled
if (((bool)adapter.Properties["NetEnabled"].Value) != true)
{
adapter.InvokeMethod("Enable", null);
}
}
}
public static void DisableWMINetworkAdapters(String filterExpression = "")
{
foreach (ManagementObject adapter in GetWMINetworkAdapters(filterExpression).Get())
{
//If enabled, then disable
if (((bool)adapter.Properties["NetEnabled"].Value)==true)
{
adapter.InvokeMethod("Disable", null);
}
}
}
}
class Program
{
public static int Main(string[] args)
{
NetworkAdapterEnabler.DisableWMINetworkAdapters("Wireless");
Console.WriteLine("Press any key to continue");
var key = Console.ReadKey();
NetworkAdapterEnabler.EnableWMINetworkAdapters("Wireless");
Console.WriteLine("Press any key to continue");
key = Console.ReadKey();
return 0;
}
}
}
public static void BlockingOfData()
{
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
}

Categories