Service {ServiceName} was not found on computer '.' - c#

I have a Windows service that runs on my local PC. My operating system is windows 7. I want to Start my service via C# code without going through "Computer Management > Services".
When I run the code below it gives me the following Exception:
"Service {ServiceName} was not found on computer '.'."
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
I've been through many posts regarding this scenario and all mention that this is a security feature of Windows 7. Is there a way to run this service without middling the Admin Groups?

You're probably running into a UAC problem. You need to add a manifest file to your app the indicates the app must be run as an administrator. This will cause Windows to prompt for elevation when your program runs. Here's an article that walks you through the issue/solution:
http://www.codeproject.com/Articles/17968/Making-Your-Application-UAC-Aware
And a related stackoverflow post:
How do I force my .NET application to run as administrator?

It can be about ur framework couldnt selected. U can select it then refresh ur IIS.

Related

stop windows service programmatically c# throwing exception

I have a windows service which should stop after some particular date time.
I am able to stop the service programmatically using:
try
{
ServiceController service = new ServiceController(servicename);
//or
//ServiceController service = new ServiceController(servicename,computer name);
service.Stop();
}
catch(Exception ex)
{
}
finally
{
ServiceController service = new ServiceController(servicename);
service.Stop();
}
But it throws an exception and does not stop if we remove the finally part.
It stopped only after I used the finally statement but obviously the exception persists.
Exception message:
Cannot open "Service Name" service on computer '.'
detailed exception:
Cannot open Service Control Manager on computer 'computer name'. This operation might require other privileges.
I did refer but it does not help also it is not addresses my problem:
Stackoverflow Question
How can I stop the service programmatically without this exception
Right click on the program and choose "Run As Administrator". If you are debugging it, ensure the IDE ( ie Visual Studio I suppose ) is opened with "Run as Administrator".
When I had this problem I went to the machine in question, and tried to stop the service manually though the interface, and received this pop-up:
I was able to stop the service by finding the task in Task Manager and ending that task. Not sure what exactly hung up the service but this works if you have access to the machine and task manager.
I was able to start the service and use the ServiceController code without any issues after.

start sql server engine permission

I have created a windows application that start\stop windows service
now when i tried to start\stop sq-server engine from my application it throw an exception
when i run my Application as administrator it works
now i can run my application as administrator using app.manifest but the problem is that my client does not have permission as administrator
what type of permission my Application need and how to do that?
public static void start()
{
ServiceController sc = new ServiceController(ServiceName, ServerName);
sc.Start();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running);
}
public static void stop()
{
ServiceController sc = new ServiceController(ServiceName, ServerName);
sc.Stop();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
}
Your app is limited to the permissions of the person running it. If they don't have rights to do something, then neither will your application. You say that your client is not an administrator, so in order for your app to work for them an administrator will have to grant their login the permissions needed to start/stop services.
One of the following needs to happen:
The user needs to get admin rights
An admin needs to assign the user permissions to start/stop
services
Your program will need to be run under alternate credentials
For the 3rd option, this can be done at least a couple different ways:
Shift-right-click an application and it will give you a menu
option to run as another user. This option requires someone to be
there to enter their credentials every time you run the application
this way.
Add the ability for someone to enter their credentials into your
application and then impersonate them in your application when
starting/stopping services. This method would allow you to give
them the option to save their credentials for future use (not saying
that's a good idea though).

Not all info about process in Process.GetProcesses when run in service by Local Service account

I have this code:
[PermissionSet(SecurityAction.Assert, Name = "FullTrust")]
public List<WinInfo> GetWindows()
{
try
{
var isFullTrust = Assembly.GetExecutingAssembly().IsFullyTrusted;
if (isFullTrust)
{
return Process.GetProcesses().Where(z => !string.IsNullOrEmpty(z.MainWindowTitle))
.Select(z => new WinInfo
{
ProcessID = z.Id,
ProcessName = z.ProcessName,
WinID = z.MainWindowHandle,
WindowTitle = z.MainWindowTitle
}).ToList();
}
else
return null;
}
catch (Exception ex)
{
Trace.Write(ex.Message);
return null;
}
}
When I test in on my local computer under my current user (with admin rights) it works ok, displaying all the processes, that have windows. But when I call this code from a windows service, run under "Local Service" account, then the list is empty. I attached to the process, and through debug I found that "Process.GetProcesses()" returns all the processes, but all of them have MainWindowHandle as 0 and MainWindowTitle as empty, even when they do have windows. So what is wrong with my code?
Edit I edited code, so that it checks the assembly for full trust and have PemmissionSet that should grant the code the neccessary rights. Still the result is the same. When I debug, I can see, that "isFullTrust" is "True" and code executes with no exceptions. Still the list is empty, because none of the processes contains not-empty MainWindowTitle
According to this thread :
The problem you're seeing is because by default service don't have access to any interactive desktops. I don't recommend interacting with the desktop from a service (#1, there may not be any desktop, #2 there may be multiple desktops, #3 interacting with the desktop from service in Vista is not implemented) but, you can check the "Interace with desktop" in your services properties.
maybe you can try to create an hidden form?
Surely you need to run that under the user account! Why would applications with open windows be running under the local system account? That's for windows services etc
It could also be related to your process requiring full trust
From MSDN: The Process class has a LinkDemand and an
InheritenceDemand for FullTrust on it. This means that if your
assembly is not fully trusted, it will be unable to kick off new
Processes or get information about running processes
Maybe this is a question of priviliges.
According to this link LocalService has minimum privileges on the local computer.
you should use Local system Account

How to start a process from an IIS hosted WCF service?

I would like to run a process from an intranet client on the WCF service side. In my case a client asks a server to create a new process on the server's machine under the provided credentials. WCF service is hosted on IIS 7.5 and I start a process using this code
var processInfo = new ProcessStartInfo("C:\\Windows\\System32\\notepad.exe")
{
UserName = "some user",
Password = MakeSecureString("some password"),
UseShellExecute = false,
LoadUserProfile = true
};
Process process = Process.Start(processInfo);
This code works if I host WCF service as a self-hosted console application running under admin user and I see the notepad started under another user. It fails on IIS with no exception, but process is immediately terminated
process.HasExited = true;
process.ExitCode = -1073741502;
On IIS WCF application is running under the user with admin rights and has got full trust defined in web.config. I cannot use self hosted application as it doesn't support easy continuous delivery (like WebDeploy with IIS web farms).
Q: How can I start a process on a server side from WCF service hosted on IIS?
EDIT:
I stumbled upon this post, with similar issues and I tried all the methods there, including all possible variations for Process.Start and P/Invoke with CreateProcessWithLogonW and CreateProcessAsUser I also tried granting additional permissions to users. Non of this would work with the error messages identical to the ones the guy had posted.
Oleksii, the point is that if you host the WCF service in a console application, there is a windows session (a user logged in and Windows Explorer loaded) for that user and the notepad is opened and shown for that user, so you see it in the UI.
when you host your WCF service in IIS, being a server, IIS requires and allows no user interaction and works also if no user is logged in; in that context there is no UI to host your notepad or other UI enabled applications, you could execute a process for elaboration or other batch jobs but not render a windows UI application, because Windows Explorer is not loaded for you and there is no place to render your process's UI.
here is what I use to call GnuPGP to do encryption. How does your setup compare?
private int ExecuteCommand(string arguments, string passPhrase, int timeout)
{
Process processObject;
ProcessStartInfo pInfo = new ProcessStartInfo(_executablePath, arguments);
pInfo.CreateNoWindow = true;
pInfo.UseShellExecute = false;
pInfo.RedirectStandardInput = true;
pInfo.RedirectStandardOutput = true;
pInfo.RedirectStandardError = true;
processObject = Process.Start(pInfo);
if (!string.IsNullOrEmpty(passPhrase))
{
processObject.StandardInput.WriteLine(passPhrase);
processObject.StandardInput.Flush();
}
string result = processObject.StandardOutput.ReadToEnd();
string error = processObject.StandardError.ReadToEnd();
if (!processObject.WaitForExit(timeout))
{
throw new TimeoutException("GnuPG operation timeout. Waited " + timeout + " milliseconds ");
}
int exitcode = processObject.ExitCode;
Error = error;
Output = result;
return exitcode;
}
There's an apppool setting to make sure it loads the user profile.
loadUserProfile Optional Boolean attribute.
Specifies whether IIS loads the user profile for the application pool identity. Setting
this value to false causes IIS to revert to IIS 6.0 behavior. IIS 6.0 does not load the
user profile for an application pool identity.
The default value is false.
That along with being a domain user as the identity with enough permissions might work?? I know that at a minimum the user will need a user profile.
That said, it's a little bit of an odd architecture. It seems like a better arch would be to have a persistent process like a windows service that the site communicates with but I'm not sure what your constraints are.
Hope that helps.

Cannot open <MyService> service on computer '.'

I have a website created by C# which is to start a services in a server.
I created a services called MyService using this :
instsrv MyService %systemroot%\system32\srvany.exe
then I uses the following code to call it :
ServiceController service = new ServiceController("MyService");
try
{
service.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
but when I access the website and trigger this event, it prompt me
Cannot open <MyService> service on computer '.'
Is it because of the security or permission problem?? Any guide with clear steps is highly appreciated.
with iis (version 6 and higher), web apps are run using an application pool. EAch application pool can run with a specific user (the identity), which is, by default, NETWORK SERVICE. It's a very bad idea to add this user to local administrators.
Possible ways :
Grants the necessary privilege to start/stop the service to this user, setup an dedicated application pool to use this identity and ensure the account have read access to the asp/.net application path.
create a dedicated account too. within you application, connect to the service management using a username/password you store securely in the config (crypt the section). I'm not sure if you can specify a user/password with service control, but you can at least, use WMI or Process.Start with a net stop / net start command.
I have actually solve the problem of on top scenario.
The service in this case is "MyService" need to set the log on to Local System Account and check Allow service to interact with desktop
In the IIS Manager, create a Application Pool for the particular website. And load the website in to it.
The particular Application Pool Identitys need to predefined to Local Syatem
This is what is needed in the IIS and services.msc
On the other hand, there will still be errors about the MAC address.
So, we need a which can be generate by machineKey Generator.
The machineKey generated is needed to paste at the tag below.
Then copy the whole block of the quote below and paste it to the Web.config
<pages buffer="false"
enableViewState="false"
enableSessionState="false"
enableViewStateMac="false"
validateRequest="false"
enableEventValidation="false"
viewStateEncryptionMode ="Never"/>
<machineKey
validationKey="8FCCB821044C5174C551129400F278B5629C64EAC195046DA5FE608EF418913C1139636E13FE 9F8C35AD3C10C394CAC1D9CEBB8B6BDA018165E91136B1AADBE1"
decryptionKey="3F260119F4CC0A0DD8C6B4979C70644A0ED2DD19B3ADB00F85FB7C83634FC544"
validation="SHA1"
decryption="AES"
/>
And the problem will then be solved, maybe the situation you guys faced may be different but I hope it may help someone as I struggle in this quite a long time.
In addition, I uses this code so there will no conflict when start and stop the services created.
if (service.Status == ServiceControllerStatus.Stopped)
{
try
{
service.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
else
{
try
{
service.Stop();
service.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
Good Luck and thank you guys for helping.
ref:
http://www.csharp-examples.net/restart-windows-service/
http://forums.asp.net/t/906759.aspx/3/10
hi i had the same prob been giving permission to all group that i thought of include the cleaners and it didnt help finally i tried this line in my web config
<identity impersonate="true" userName="Domainname\admin" password="123" />
It might help someone with a related issue:
On my server, a powershell commandlet was failing with the same error message.
It was because, even if I was logged as the local admin, I needed to run the PowerShell environment as an administrator (right click, run as Administrator).

Categories

Resources