How to access IIS through C# Console Application - c#

I am trying to access my server's IIS pool in order to recycle it through C# code.
This is my code:
static void Main(string[] args)
{
try
{
string sMachine = "MyHostName";
string sAppPool = "MyAppPoolName";
string sPath = "IIS://" + sMachine + "/W3SVC/AppPools/" + sAppPool;
Console.WriteLine(sPath);
DirectoryEntry w3svc = new DirectoryEntry(sPath, "MyUserName", "MyPassword");
w3svc.Invoke("Recycle", null);
Console.WriteLine("Application pool recycled");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
I changed the sMachine / sAppPool / UserName, Password, but in my code I send them with the real data.
When I run it on my VM I get a message
Error: Unknown Exception
I think it occurs because the permission so I run it with the administrator of the VM and run as administrator the exe file, but still I get the same error.
How could I access the IIS?
Thanks in advance.

Related

How to run C# exe in Windows server with given user name and password

I have written a WCF service API which will create process inside to convert something for my application, also this service deployed in IIS in windows server using windows authentication. I used below code to run c# .exe but not running. If I run below code without username and password .exe is running but as SYSTEM user. I want to run this exe with specified user name.
public byte[] InvokeShtToPdfConvertor(string userId, string connectionAlias)
{
try
{
using (Process shtToPdfProc = new Process())
{
shtToPdfProc.StartInfo.FileName = Constants.SHT_PDF_CONVERTOR_APP_PATH;
shtToPdfProc.StartInfo.Arguments = userId + " " + connectionAlias;
shtToPdfProc.StartInfo.Verb = "runas";
shtToPdfProc.StartInfo.UserName = _tempUserName;
shtToPdfProc.StartInfo.Domain = "cw01.contiwan.com";
shtToPdfProc.StartInfo.Password = ConvertToSecureString("ABCDFEDD");
shtToPdfProc.StartInfo.UseShellExecute = false;
shtToPdfProc.Start();
shtToPdfProc.WaitForExit();
}
}
catch (Exception ex)
{
throw new FaultException<MplCustomException>(new MplExceptionHandler().MplExceptionHandlerMethod(ex));
}
return GetPdfFilePath(userId);
}

SQL Server Compact edition 3.5 database acess is denied

I have developed a desktop application in C# with Microsoft SQL Server Compact Edition 3.5.
It works fine when I run .exe file from solution folder (bin\release or debug) but when I tried to deploy it by creating its setup it shows unhandled exception:
You don't have permission to access CustomersDB.sdf file.
Note there is no path error it is correct.
string lokasifile = Environment.CurrentDirectory + "\\CustomersDB.sdf";
string stringkoneksi = "Data Source = \"" + lokasifile + "\"";
SqlCeConnection koneksi = new SqlCeConnection(stringkoneksi);
koneksi.Open();
SecurityException
This is nothing but caller does not have the appropriate permission.
Environment.CurrentDirectory Property
try
{
//Call Path here you will get to what the exactly error is
}
catch (Exception ex)
{
if (ex is DirectoryNotFoundException|| ex is IOException|| ex is SecurityException)
{
//Your handling here
}
else
{
throw;
}
}

Programmatically login 10 users to remote desktop session

I am trying to create an application that will programmatically login 10 users using RDP. The purpose is to autologin these users so someone does not have to manually do it. The first server I tested against (Server 2012) worked just fine. However, I tried a Server 2008 R2 and it continues to prompt me for a password. Here is the code.
static void Main(string[] args)
{
var password = ConfigurationManager.AppSettings["Password"];
var machine = ConfigurationManager.AppSettings["MachineName"];
var userNameList = new List<string>(ConfigurationManager.AppSettings["UserName"].Split(new char[] { ';' }));
foreach(string name in userNameList)
{
Process rdpProcess = new Process();
rdpProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe");
rdpProcess.StartInfo.Arguments = "/generic:TERMSRV/" + machine + "/user:" + name + " /pass:" + password;
rdpProcess.Start();
rdpProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\mstsc.exe");
rdpProcess.StartInfo.Arguments = "/v " + machine;
rdpProcess.Start();
Thread.Sleep(3000);
}
}
I added the sleep as the connections were coming too fast and I was getting "connection is busy" errors.
Can anyone see anything I am doing wrong?
Don't really know why this was the case but my 2008 servers will not work with FQDN. IP works fine though. Whatever..

Trust Relationship between the Primary Domain and the Trusted Domain exception on SecurityIdentifier.Translate

In a script task within SSIS, I am running this block of code
SecurityIdentifier sid = new SecurityIdentifier(memberDN.Substring(0, memberDN.IndexOf(",")).Replace("CN=", ""));
try
{
NTAccount acct = sid. (NTAccount)sid.Translate(typeof(NTAccount));
LogonName = acct.Value;
}
catch (Exception ex)
{
Dts.Events.FireError(0, "Example script task", ex.Message + "\n" + ex.StackTrace + "\n Failed MemberDN:" + memberDN, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
This works fine on my local PC in dev environment, but when deployed to the server and run I get this error:
The trust relationship between the primary domain and trusted domain failed at SecurityIdentifier.TranslateToNTAccounts
Failed MemberDN: CN=S-1-5-21-2347892348791324etc.. CN=ForeignSecurityPrincipals,DC=mlol,DC=local
I'm not really sure how to proceed from here, and how to trace this error further.

Check if a process is running on a remote system using C#

I am trying to check if a process is running on a remote system. I am using the following code:
string procSearc = "notepad";
string remoteSystem = "remoteSystemName";
Process[] proce = System.Diagnostics.Process.GetProcessesByName(procSearch, remoteSystem);
However, when I try to run the code, I get the following error: "Couldn't connect to remote machine."
I am able to run pslist with the following command:
C:>pslist \remoteSystemName
So I know it is possible to get the information I need, but I need it in the code.
Another possibility would be to integrate pslist into C# and search the list to see if the process is there, but I have not found information on how to do this.
Use the System.ServiceProcess.ServiceController class for a service. You can use Status to check if it's running and the Stop() and Start() to control it.
ServiceController sc = new ServiceController();
sc.MachineName = remoteSystem;
sc.ServiceName = procSearc;
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
sc.Stop();
}
else
{
sc.Start();
}
Below is what I did to get this to work:
First I added a reference to System.ServiceProcess and added: using System.ServiceProcess;
string remoteSystem = "remoteSystemName";
string procSearch = "notepad";
Process[] proc = System.Diagnostics.Process.GetProcessesByName(procSearch, remoteSystem);
if (proc.Length > 0)
{
Console.WriteLine("Able to find: " + proc[0]);
}
else
{
Console.WriteLine("Unable to find: " + procSearch);
}
Does the inner Exception say "Access Denied"?
A similar question may help, it mentions needing to be in the Performance Monitor Users group.
GetProcessesByName() and Windows Server 2003 scheduled task
I figured when running the application by itself I would get an exception window, because exceptions were not handled within my code...
There I saw the reason in the stacktrace: access denied. The reason was that the user running the program that was calling the .NET method to get the process list was not part of the "Performance Monitor Users" group of the remote machine.
After that I got another exception saying that the performance monitoring service was not running on the remote machine. So I started the corresponding service at the remote computer and voila it worked!
This was using a Windows 7 client trying to get the process list of a Windows 2008 Server.
Killing the remote process
I found that the Process.Kill() method does not work when the Process.MachineName has been set, so here is a solution for killing the process remotely, hope it helps others.
The extension method to create the method: KillRemoteProcess
public static class ProcessExtensions
{
public static void KillRemoteProcess(this Process p, string user, string password)
{
new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "TaskKill.exe",
Arguments = string.Format("/pid {0} /s {1} /u {2} /p {3}", p.Id, p.MachineName, user, password),
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true
}
}.Start();
}
}
And ofcourse the method to find the processes and consume the KillRemoteProcess
public static void KillProcessesRemote()
{
string targetProcessName = "myProcess"; //Do not put 'process.exe' here just 'process'
string targetMachine = "remotMachine"; //Target machine
string username = "myUser"; //Username
string password = "myPassword"; //Password
Parallel.ForEach<Process>( //Kill all processes found
source: System.Diagnostics.Process.GetProcessesByName(targetProcessName, targetMachine),
body: process => {
process.KillRemoteProcess(username, password);
});
}
You may try impersonate to the user that have access to the remote server.
https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsimpersonationcontext?redirectedfrom=MSDN&view=netframework-4.7.2
After Impersonation, you will no longer hit the error.
Also, you have to make sure there is trust between domain, else impersonation will not work.
LogonUser works only for my domain

Categories