I have an interactive windows service which run on a Local System account and with Interact with desktop checkbox checked(this is mandatory for my project as my service needs to invoke .exe with UI ). I am getting an exception as Access denied while writing to network drive. I am passing the UNC path from config file. i tried giving full control access to anonymous user on the folder which i want to access but its still not working. i cannot run my windows service under Network service account or under any other account as suggested in some other posts because i want it interact with desktop check box checked. is there any way to achieve this?
Edit: UNC path of network drive: //server/ABC/pqr
my service should create .txt file in pqr folder. should have access to delete it afterwords too.
i have tried creating anonymous user for pqr folder and giving it full control but still i am getting access denied exception. as i mentioned before i cannot run it under any other account other than local system account because it will automatically disable interact with desktop option in the properties of that service. is there any way to make it run under Network Service Account and still keep it interactive(interact with desktop option checked in the properties of service)?
Try using the following nugget package named SimpleImpersonation
This way you could wrap the code you use to access your remote file location like this:
using (Impersonation.LogonUser(domain, username, password, logonType))
{
// do whatever you want as this user.
}
It worked for me. I used it to turn on and turn off a windows service remotely. Like this:
await Task.Factory.StartNew(() =>
{
using (
Impersonation.LogonUser(serviceInfo.Domain, serviceInfo.User, serviceInfo.Pswd,
Environment.MachineName.Equals(serviceInfo.ComputerName,
StringComparison.InvariantCultureIgnoreCase)
? LogonType.Network
: LogonType.Interactive))
{
var service = new ServiceController(serviceInfo.ServiceName, serviceInfo.ComputerName);
if (service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(60));
}
else
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(60));
}
}
});
(the snippet was taken from the project site)
I created a windows service which watches a directory. When a file is dumped into it, it takes the data and puts it into a database. Then this file is moved to another directory and deleted. It works fine in debug mode. But when i install it on my computer it stops after throwing the data into the database and the file in question is neither moved or deleted. I suspect a permission issue is involved. I tried to create a event log:
public Service1()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
So i have three questions.
(1) What could be causing my service to work as described in debug but fail when installed on my computer.(2) I have initiated a event log as shown above. But do i need to add other code to record the event of my service stopping. I presume this would be done in a 'override onShutdown' method.(3) Finally when my service stops, i want to look at the event log. But i do not know how to do this, is in administrative tools? stored as a file on some directory?
Here is edit to this post in lieu of the grateful advice given below.
try
{
File.Move(e.FullPath, finalString);
File.Delete(e.FullPath);
}
catch(Exception q)
{
EventLog.WriteEntry("MySource", q.ToString(), EventLogEntryType.Error);
using (StreamWriter w = new StreamWriter(ConfigurationManager.AppSettings["fmd"], true))
{
w.Write(DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss"));
w.Write(q.ToString());
}
}
As per suggestion i put a try-catch around the file move and delete plus i added a OnShutdown method:
protected override void OnShutdown()
{
using (StreamWriter w = new StreamWriter(ConfigurationManager.AppSettings["ond"], true))
{
w.Write("stop OnShutdown");
}
//EventLog.WriteEntry("MySource", message, EventLogEntryType.Error);
}
I do not know how to pass any system error message to the shutdown method, so any advice appreciated. When i installed my modified code as a service, it again stopped before moving or deleting the files. Neither of my two logs accessed by a stream recorded anything. Plus the event viewer showed nothing either?
You can write as following,
if (!EventLog.SourceExists("MySource"))
EventLog.CreateEventSource("MySource", "Application");
EventLog.WriteEntry("MySource", message, EventLogEntryType.Error);
to view the event log messages, Goto Administrator Tools -> Event Viewer and look for the source you have created. or Just simply type eventvwr in run window.
When Services installed, it works under SYSTEM User account where service might not have access to some resources. Please put logs and see where exactly the issue is.
If you service installed in your development machine, use attach to process option under DEBUG Menu in Visual Studio to find out.
What could be causing my service to work as described in debug but fail when installed on my computer?
Permissions. The service is likely running under LocalSystem or Network Service if you didn't provide a different identity.
I have initiated a event log as shown above. But do i need to add other code to record the event of my service stopping. I presume this would be done in a 'override onShutdown' method?
Yes, you're assumption is correct.
Finally when my service stops, i want to look at the event log. But i do not know how to do this, is in administrative tools?
Just hit Windows Key+R to get the Run dialog and type eventvwr.
Well i found the reason for all the commotion. I eventually found some logs in the event viewer. They were listed in Administrative events in custom logs. There were three error logs: .Net runtime; Application error & Service Control Manager. In '.Net Runtime' the stack showed a unhandled exception for system.windows.forms. I stupidly included a pop up box in my release version. But even when i commented this away; i got a error. So i went back and found other message boxes, primarily in try catch statements. Removed these and solved the issue.
I am having an issue with opening a document using Microsoft Word from ASP.NET MVC.
This works perfectly on my developer machine, but not when deployed to IIS.
Dim word = New Microsoft.Office.Interop.Word.Application
'This line is failing to return a document object
Dim letter = word.Documents.Add(letter_doc_path)
'This line then fails due to [letter] being null
letter.MailMerge.OpenDataSource(csvPath)
I have added permissions in "Component Services" (dcomcnfg) to the NETWORK SERVICE user which allows the creation of the Word object in the first place, but I am completely stuck as what to do with this one.
I have also tried suppressing Word dialogs with the following line just in case
word.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone
The issue isn't helped by not having an error (apart from the null object reference obviously) - maybe there's a way to query Word for a specific error message?
Word requires the normal.dot template file when opening any document, the problem was occurring because the IIS user didn't have anywhere to create the normal.dot so it was failing in the background.
This was fixed by setting the UserTemplate path for the newly created word instance (immediately after creating it).
The path must be writeable by the IIS user (NETWORK SERVICE in my case).
word.Options.DefaultFilePath(Microsoft.Office.Interop.Word.WdDefaultFilePath.wdUserTemplatesPath) = working_folder
So just for completeness, here's the original example with the winning line included:
Dim word = New Microsoft.Office.Interop.Word.Application
'this line fixed it
word.Options.DefaultFilePath(Microsoft.Office.Interop.Word.WdDefaultFilePath.wdUserTemplatesPath) = working_folder
Dim letter = word.Documents.Add(letter_doc_path)
I was having the same problem, and the settings that wheelibin suggested weren't enough to create documents using the NETWORK SERVICE account.
What I ended up doing is:
Create a user account for this
process to run under.
Login as the user and run Word (this
does various setup tasks in Word so
the application doesn't try putting
up modal dialogs when running as a
service).
Create a new application pool and set
the pool to run as the user account.
If you're using Windows
Authentication, and your server is
Windows 2003 (or 2000, presumably),
then this issue applies, and you
need to either change the SPN of the
server, which will break Windows
Authentication for any application
running under a different user
account, or you have to switch the
authentication provider over to NTLM
instead of Kerberos.
IIS 7 can use Kernel Mode Authentication to avoid the issue.
I am not sure how are you catching the errors.
Please take a look at the following pages if you find some clue from that.
Error while using Microsoft Office 2003 in web application
Error while calling MS-Word from ASP.NET
"There is insufficient memory or disk space. Save the document now" - Opening MS Word from ASP.NET
I have created a C# web service using visual studio to stop the windows service 'Simple Mail Transfer Protocol (SMTP)' called SMTPSVC.
The following is the web method to do it:
[WebMethod]
public string StopService()
{
String status = "";
try
{
ServiceController scAlerter = new ServiceController("SMTPSVC");
Console.WriteLine(scAlerter.DisplayName);
Console.WriteLine(scAlerter.CanStop);
scAlerter.Stop();
Console.WriteLine("Service stopped");
status = "STOPPED";
}
catch (Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
status = "Exception" + e.ToString();
}
return status;
}
I published this web service in my IIS 5.1 server. When I invoked the service it is throwing the following 'Access Denied' exception
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://y-square.org/">
ExceptionSystem.InvalidOperationException: Cannot open SMTPSVC service on
computer '.'. ---> System.ComponentModel.Win32Exception: Access is denied
--- End of inner exception stack trace --- at
System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)
at System.ServiceProcess.ServiceController.Stop() at Service.RestartService()
in c:\Inetpub\wwwroot\RestartService\App_Code\Service.cs:line 38
</string>
By default the service is using the user account IUSER_system-name and I have added this user account into system Administrators group and also added ASPNET user account in Administrator group.
I was able to stop/start this windows service from C# standalone program successfully.
Can you kindly let me know what is the problem? Any permission settings or IIS user access rights shall I need to change in order to run this?
Also let me know which user account this C# service would use to stop the Windows Service?
Your help is much appreciated.
Thanks in advance,
Yogi
The IUSER_machinename (IUSER for short, in the following) account is, for good reasons, a relatively limited account, with little more privilege than a guest account. It isn't allowed to start and stop Windows services, or even to interrogate them (to get their status etc).
When run in the context of a stand-alone exe, the logic above is successful because the underlying account is [probably] you who is likely a member of the Administrators group, or a rather powerful account at any rate.
The easy, but unrecommended way out of this situation, is to give the IUSER account more privileges. Just to try add this account to the Administrators group, bam!, it will work (but will also introduce some potentially dangerous security hole).
A better approach is to make the explicit list of the particular Windows services that will be allowed to managed by way of IIS, and to set their individual service security descriptor to so that the IUSER account (or another account/group created for the occasion) be allowed to start and/or stop them as desired.
The difficulty in implementing this approach is that, to my knowledge, there's no GUI or intuitive admin tool to inspect and alter the services' security descriptor: you need to use sd and "learn" the SDDL language. Here are a few pointers to do so
MSDN Best practices and guidance for writers of service discretionary access control lists
sc sdshow command
sc sdset command
I'm getting this error when I try to start a windows service I've created in C#:
My Code so far:
private ServiceHost host = null;
public RightAccessHost()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
host = new ServiceHost(typeof(RightAccessWcf));
host.Open();
}
protected override void OnStop()
{
if (host != null)
host.Close();
host = null;
}
Update #1
I solved the issue above by granting permissions to the account NETWORK SERVICE but now I have an another problem:
Update #2
Service cannot be started. System.InvalidOperationException: Service 'RightAccessManagementWcf.RightAccessWcf' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
at System.ServiceModel.Description.DispatcherBuilder.EnsureThereAreNonMexEndpoints(ServiceDescription description)
at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
at System.ServiceModel.ServiceHostBase.InitializeRuntime()
at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at RightAccessHosting.RightAccessHost.OnStart(String[] args) in C:\Users....
I realize this post is old, but there's no marked solution and I just wanted to throw in how I resolved this.
The first Error 5: Access Denied error was resolved by giving permissions to the output directory to the NETWORK SERVICE account.
The second Started and then stopped error seems to be a generic message when something faulted the service. Check the Event Viewer (specifically the 'Windows Logs > Application') for the real error message.
In my case, it was a bad service configuration setting in app.config.
Computer -> Manage -> Service -> [your service] properties.
Then the the tab with the account information. Play with those settings, like run the service with administrator account or so.
That did it for me.
EDIT:
What also can be the problem is that, most services are run as LOCAL SERVICE or LOCAL SYSTEM accounts. Now when you run C:/my-admin-dir/service.exe with those accounts but they are not allowed to execute anything in that directory, you will get error 5. So locate the executable of the service, RMB the directory -> Properties -> Security and make sure that the account the service is run with, is in the list of users that are alloewd to have full control over the directory.
This worked for me.
Right-click on top-level folder containing the service executable. Go to Properties
Go to "Security" Tab
Click "EDIT"
Click "ADD"
Enter the name "SYSTEM", click OK
Highlight SYSTEM user, and click ALLOW check-box next to "Full control"
Click OK twice
Make sure the Path to executable points to an actual executable (Right click service -> Properties -> General tab).
Via powershell (and sc.exe) you can install a service without pointing it to an actual executable... ahem.
I also got the same error , It resolved by
Right click on Service > Properties >Log On > log on as : Local System Account.
I was getting this error because I misread the accepted answer from here: Create Windows service from executable.
sc.exe create <new_service_name> binPath= "<path_to_the_service_executable>"
For <path_to_service_executable>, I was using the path of the executable's folder, e.g. C:\Folder.
It needs to be the path of the executable, e.g. C:\Folder\Executable.exe.
I got the solution:
1. Go to local service window(where all services found)
2. Just right click on your service name:
3. click on "properties"
4. go to "log on" tab
5. select "local system account"
6. click "ok"
now you can try to start the service.
In my case following was not checked.
if you are a having an access denied error code 5. then probably in your code your service is trying to interact with some files in the system like writing to a log file
open the services properties select log on tab and check option to allow service to interact with the desktop,
For me - the folder from which the service was to run, and the files in it, were encrypted using the Windows "Encrypt" option. Removing that and - voila!
This error happens when there is a error in your OnStart method. You cannot open a host directly in OnStart method because it will not actually open when it is called, but instead it will wait for the control. So you have to use a thread. This is my example.
public partial class Service1 : ServiceBase
{
ServiceHost host;
Thread hostThread;
public Service1()
{
InitializeComponent();
hostThread= new Thread(new ThreadStart(StartHosting));
}
protected override void OnStart(string[] args)
{
hostThread.Start();
}
protected void StartHosting()
{
host = new ServiceHost(typeof(WCFAuth.Service.AuthService));
host.Open();
}
protected override void OnStop()
{
if (host != null)
host.Close();
}
}
I had windows service hosted using OWIN and TopShelf.
I was not able to start it. Same error - "Access denied 5"
I ended up giving all the perms to my bin/Debug.
The issue was still not resolved.
So I had a look in the event logs and it turned out that the Microsoft.Owin.Host.HttpListener was not included in the class library containing the OWIN start up class.
So, please make sure you check the event log to identify the root cause before beginning to get into perms, etc.
In my case, I had to add 'Authenticated Users' in the list of 'Group or User Names' in the folder where the executable was installed.
One of the causes for this error is insufficient permissions (Authenticated Users) in your local folder.
To give permission for 'Authenticated Users'
Open the security tab in properties of your folder, Edit and Add 'Authenticated Users' group and Apply changes.
Once this was done I was able to run services even through network service account (before this I was only able to run with Local system account).
Right click on the service in service.msc and select property.
You will see a folder path under Path to executable like C:\Users\Me\Desktop\project\Tor\Tor\tor.exe
Navigate to C:\Users\Me\Desktop\project\Tor and right click on Tor.
Select property, security, edit and then add.
In the text field enter LOCAL SERVICE, click ok and then check the box FULL CONTROL
Click on add again then enter NETWORK SERVICE, click ok, check the box FULL CONTROL
Then click ok (at the bottom)
Your code may be running in the security context of a user that is not allowed to start a service.
Since you are using WCF, I am guessing that you are in the context of NETWORK SERVICE.
see: http://support.microsoft.com/kb/256299
I have monitored sppsvc.exe using process monitor and found out that it was trying to write to the HKEY_LOCAL_MACHINE\SYSTEM\WPA key. After giving permissions to NETWORK SERVICE on this key, I was able to start the service and Windows suddenly recognized that it was activated again.
Use LocalSystem Account instead of LocalService Account in Service Installer.
You can do this either from doing below change in design view of your service installer:
Properties of Service Process Installer -> Set Account to LocalSystem.
or by doing below change in in designer.cs file of your service installer:
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
Have a look at Process Utilities > Process monitor from http://www.sysinternals.com.
This is tool that allows you monitor what a process does. If you monitor this service process, you should see an access denied somewhere, and on what resource the access denied is given.
For the error 5, i did the opposite to the solution above.
"The first Error 5: Access Denied error was resolved by giving permissions to the output directory to the NETWORK SERVICE account."
I changed mine to local account, instead of network service account, and because i was logged in as administrator it worked
If you are getting this error on a server machine try give access to the folder you got the real windows service exe. You should go to the security tab and select the Local Service as user and should give full access. You should do the same for the exe too.
I accidentally set my service to run as Local service solution was to switch to Local System
After banging my had against my desk for a few hours trying to figure this out, somehow my "Main" method got emptied of it's code!
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new DMTestService()
};
ServiceBase.Run(ServicesToRun);
Other solutions I found:
Updating the .NET framework to 4.0
Making sure the service name inside the InitializeComponent() matches the installer service name property
private void InitializeComponent()
...
this.ServiceName = "DMTestService";
And a nice server restart doesn't hurt
Szhlopp
In may case system run out of free space on local disk.
I had this issue today on a service that I was developing, and none of the other suggestions on this question worked. In my case, I had a missing .dll dependency in the folder where the service ran from.
When I added the dependencies, the issue went away.
In my case I kept the project on desktop and to access the desktop we need to add permission to the folder so I simply moved my project folder to C:\ directory now its working like a charm.
I don't know if my answer would make sense to many, but I too faced the same issue and the solution was outrageously simple. All I had to do was to open the program which I used to run the code as an administrator. (right-click --> Run as Administrator).
That was all.
check windows event log for detailed error message. I resolved the same after checking event log.
All other answers talk about permissions issues - which make sense, given that's what the error message refers to.
However, in my case, it was caused by a simple exception in my service code (System.IndexOutOfRangeException, but it could be anything).
Hence, when this error occurs, one should look inside their log and look for exceptions.
I had this issue on a service that I was deploying, and none of the other suggestions on this question worked. In my case, it was because my .config (xml) wasn't valid. I made a copy and paste error when copying from qualif to prod.