Activator.CreateInstance fails in Windows Service - c#

I have an issue with a Windows Service which throws a NullReference exception whenever I try to use
var myType = Activator.CreateInstance(typeof(MyType))
There is no problem whenever I run the exact same code in a console window - and after debugging the obvious "which user is running this code" I doubt that it is a mere fact of changing the user running the service as I've tried to run the service using the computer's Administrator account as well as LocalSystem. I'm suspecting a Windows Update fiddling with default user rights but that's a bit of a desperate guess I feel.
Remember: The type and assembly exist and works fine - otherwise I wouldn't be able to run the code in a console window. It is only when running in the context of a Windows Service I get an error.
The question is: Can I in any way impersonate i.e. LocalSystem in a unittest by creating a GenericPrincipal (how would that GenericPrincipal look)?

You could always run a visual studio instance as LocalSystem. From the command line, enter the following:
at <time in near future> /interactive <path to devenv.exe>
Then wait for that time to roll around and VS should open up, but will be running under the LocalSystem account.
I'd personally not suspect the user account, and instead suspect that it's something to do with being interactive - does the constructor or class constructor for MyType have some implicit dependency on the desktop?
(Edit - oops, should be time before /interactive, corrected command line).
e.g.
at 11:48 /interactive "c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"

I know its a simple answer but have you tried putting it in a try catch block then writing out the exception to see if it is Permission based or otherwise.

Related

Custom Actions Installer for Windows Service

I have a windows service which I silent install using msiexec.exe and I am passing the username and password for the "Set Service Login"
The Service is successfully installing but upon Starting the service I am receiving "error 1069: The service did not start due to logon problems"my logon account is administrator and I have tested that when I manually install using the same msi file and start the service it is starting successfully, I am stuck and need some ideas and guidance of what I am missing.
here is my overriden method from Installer Class.
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
var userName = Context.Parameters["USERNAME"];
var password = Context.Parameters["PASSWORD"];
if (!string.IsNullOrWhiteSpace(userName) && userName.ToLower() != "admin")
{
CustomInstallerParameters customParameters = new CustomInstallerParameters(Context);
SaveCustomParametersInStateSaverDictionary(stateSaver, customParameters);
}
else
{
Context.Parameters.Remove("USERNAME");
Context.Parameters.Remove("PASSWORD");
}
}
TIA.
It appears that you are using a Visual Studio setup project, and most likely also using one of the TextBoxes dialogs to collect the input.
You can't silently pass these parameters on the command line because Visual Studio generates custom actions to clear them (and I don't know why). In a silent install Windows runs just the InstallExecuteSequence, and if you look in there with (for example) Orca you'll see custom actions such as "CustomTextA_SetProperty_EDIT1" that clear the values. To state the obvious, the values you currently get will be blank, and you could verify this by logging the values somewhere.
So a starting point to getting this to work is to use Orca to delete those custom action calls in the InstallExecuteSequence table.
After that, there is a potential problem that the values won't make it to your custom action because they are not secured, so in the Property table you'd need to add those property names to the SecureCustomProperties list, semi-colon delimited (EDIT1;EDIT2 and so on).
Visual Studio setup projects aren't good at any of this, and something like WiX would be better because no code is required to install, start or stop services, or configure them with an account.
Most likely, different decade, same problem.... (SeServiceLogonRight)
http://iswix.com/2008/09/22/different-year-same-problem/
FWIW, I wasn't a big WiX user yet back then (I was merely dabbling at that point) but there are some real gems in the comments from my Matthew Rowan. He is correct... all of this gets WAY easier if you are using WiX.
For example you can follow this tutorial:
https://github.com/iswix-llc/iswix-tutorials
This creates a windows service running as SYSTEM. Add a reference to the WiXUtil extension and namespace and author a User element with the LogonAsService right set and your all set.
FWIW, my only concern with all this is that MSI needs property persistence if you don't want a repair to come by and corrupt the username and password. Property persistence is pretty easy to remember ( See: http://robmensching.com/blog/posts/2010/5/2/the-wix-toolsets-remember-property-pattern/ ) but the problem is providing enough encryption to not expose the account.
It's for the reason I typically suggest just running as NetworkService or SYSTEM and grant the computer object rights in a domain. An alternative is to have the installer create the service account and randomize the password on each repair so you don't have to persist it.

Application_start not working

I have written some code in the application_start() method in my global.asax file. It does not get called when I deploy my application on IIS server. The code is accessible when I run it in the .NET framework.
I've tried to restart the application many times, but it's still not working.
I've also tried the suggestion from the following link.
Application_Start not firing?
There are few things you need to know before you are trying to debug Appplication_Start. There are -
One : When the code executes and why it is almost impossible to debug by attaching to it.
The application start method is executed when the application pool starts and your website is being started up for the first time. If you deploy new deliverables to IIS, then IIS might restart it itself, but there is no guarantee that it will. So, deploying new codes does not guarantee that it will restart the pool and he execution of application start. You should restart your application pool to guarantee execution of application start.
While debugging IIS applications, Visual Studio attaches itself to a process something named w3wp.exe or similart (I forgot the actual executable name), which is the worker process and only available after, remember after, your application pool is up and your site is up. So, in other words, if you are seeing this in service list, then the application start has already been executed and attaching to it will not give you a chance to debug it. It is kind of a tug of war with time.
So, in other words, it is kind of impossible to debug application start unless you are very very quick.
Two, the solution 1 - With Dev Server
Launch your application in visual studio with Asp.net development server or IIS express, then you will be able to debug. But if you really want to debug on IIS, then check the next section
Two, the solution 2 - With IIS
There is a library in the name System.Diagnostics, Debuggerand it has a nice way to call debugger in code. You can read it here - http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break(v=vs.110).aspx
Modify you application start with this -
public void Application_Start(){
....... //other codes
Debugger.Break() or Debugger.Launch()
}
When this line executes, IIS will halt execution, and will show you a debugger selector window (similar to the one attached), keep your solution open in vs and select that vs from the list, will be able to debug as usual... :)
In case you are using windows 8 and the debugger does not launch, read this article to enable it -
http://blogs.msdn.com/b/mapo/archive/2013/11/07/debugger-launch-not-displaying-jit-debugger-selection-popup-on-windows-8-8-1.aspx
Three: A very important thing
I noticed that you said, you are adding db entries in Application_Start. You should keep in mind that, Application_Start does not have a HttpContext, ViewContext, So your db access code may fail for so many others reasons.
Make sure that the Global.asax file is actually deployed to the destination folder in the root. If the file is not present then the code behind you have written for Application_Start will never be called.
Also make sure the signature is correct
public class Global : System.Web.HttpApplication {
protected void Application_Start(object sender, EventArgs e) {/*do something here like logging so you know it was called*/}
}
If you are running Server 2008R2 (or earlier) and/or IIS 7.5, you might want to look into the Application Initialization module. This can be downloaded here:
www.iis.net/downloads/microsoft/application-initialization
With IIS versions prior to 8.0, the application start is not called until the first web request arrives. I'm reading your question as you want your application start to be fired before the first web request, yes?
Here is a fantastic guide to configuring this module (if it applies to you):
https://blogs.msdn.microsoft.com/benjaminperkins/2014/01/07/configure-the-iis-application-initialization-module/
The key takeaways is that you need to set your app pool to 'AlwaysRunning' instead of 'OnDemand'. You also need to set a preloadEnabled flag for your website. Once both of these are done, fire off an iisreset and you should see the results of your application start (look in the database since it's writing there).
Other answers are relevant as well, in that this is tough to debug and you're missing all the niceties you're used to such as a httpcontext in app start.
If you are running IIS 8.0 - you should still read the above link to configure preloading.
This did work for me:
Menu -> Build -> Clean Solution
Menu -> Build -> Rebuild Solution
Then, Application_Start() was fired only for the first time.
In my case in production environment App_global.asax.compiled was missing and all content of global.asax not fired.

Visual Studio 2012 debugging of remote process not working as expected

I am struggling with a rather difficult debugging challenge and hoping that someone might have some clues how to make this work.
Here's the scenario:
I have a C# Windows service that runs under a user account with admin privileges and launches a separate executable process under a user account that has standard user privileges. The two processes are designed to communicate using WCF.
Unfortunately, when the child process is launched, it crashes immediately, with nothing in the event log that suggests what happened. The parent process continues running without exceptions.
For information: these two applications work reliably together in a configuration whereby the parent process is a desktop application. I have also had success with the parent as a Windows service, but only when both processes run under the same user account with admin privileges.
I now need to reconfigure their relationship to restrict the privileges of the child process, but this is when the crash occurs.
In order to prove that what I am trying to do is feasible, I have created two stub applications and launched them successfully in the desired configuration. So, I can deduce that my real child app contains something that is incompatible with this configuration and which causes a crash even before the code starts executing. Unfortunately, since the child process is a based on some rather complex legacy code, it is not easy to isolate its elements until I eliminate the problem, so I really need a reliable means of stepping through it.
If I modify the code of the child process to launch debugging immediately on startup, it invites me to attach a debugger, but fails to complete the attachment, with a message that indicates that The Just-in-time debugger does not have permission to debug the process.
I have also seen this question and attempted to implement this proposed solution (which looks really promising) but it fails to work in my scenario. Instead of launching debugging prior to launching the application it appears to do nothing - niether the debugger nor the application are launched and the debugging invite dialog is not displayed. However, I have verified that this technique works in my environment (by using it to launch Notepad.exe) so there is clearly something about my application or the way that I am launching it that is causing the problem.
I am happy to experiment and to share more details about my test results, if anyone has any suggestions.
Many thanks for your ideas,
Tim
The fact that the debugger never starts for the child means the error should be occuring in the PARENT server process. If you properly set the Image File Execution Options (which is easiest to do using GFlags program using the free Windows Debugging Tools from Microsoft), then that means you never start creating the child. The simplest way to test this is by adding an Assert to your code, right before the create child process call, build your parent service in debug mode, install/register it as a service, and start it up. When the Assert pops up, attach to the process, and start debugging from there. You should then see the create process error occuring in the parent.
If you want to interactively debug both the parent service and the child process, you can do this using WinDbg and GFlags, but it will be complicated.
You will need WinDbg and GFlags. These tools are included free from Microsoft as part of the Debugging Tools for Windows. You can find that free software package here:
http://msdn.microsoft.com/en-us/windows/hardware/gg463009.aspx
Use GFlag to set the execution option for your PARENT SERVICE with the following debugger options:
"C:\Program Files (x86)\Windows Kits\8.0\Debuggers\x86\WinDbg.exe" -server tcp:port=5000:9000 -o -g
When Windows starts your parent service, it will do so under WinDbg. Because of the -o option, WinDbg will also manage the launched child process, allowing you to interactively DEBUG the child from start up. Because of the -g option, WinDbg will start the ParentService up and let it run, rather than stop it at load up as is normal debugging behavior. This will prevent Windows SCM from shutting it down and starting a new instance.
Because you are running a service, it will not have access to the desktop, so neither will its host WinDbg. You will have to attach ANOTHER debugger to the running instance of the WinDbg running your ParentService. You can do this using another WinDbg instance. To do that, start a second instance of WinDbg, and connect remotely by using the menu item "File|Connect To Remote Session...". At the dialog, put in:
tcp:Port=5000:9000,Server=[machinename]
Once you are connected, you will be able to work with your ParentService.exe, and when it creates the ChildProcess, the executing context will swap to it, and you will be able to debug it as well.
I've used this technique to debug a child process created by a windows service before. It isn't as easy as just debugging something in Visual Studio's built in debugger in its IDE, but it does work.
WinDbg has extensive documentation available for it, both from Microsoft and from other sources online. The URL I provided above includes links to WinDbg documentation.
I recommend using GFlags because it will make all the necessary edits to your Registry for running executables under a debugger of your choice. It also does much more, and is worth the time to learn about.
It is possible to set up breakpoints and set all sorts of options when WinDbg starts. I replace the -g option with the command line option:
-c "$$<c:\MyDebugCommands.txt"
This instructs WinDbg to run a command, and the command is to run a WinDbg script named "MyDebugCommands.txt". I populate MyDebugCommands.txt file with all the set up changes I need (such as load symbol options), as well as setting the breakpoints I am interested in, with the final command in the file being -g
As I said, it isn't as easy as just using the VS IDE and its built in debugger, but it will let you interactively debug your parent service and its launched child process.
According to my tests based on your scenario above (parent process is service with admin rights, child is console without admin rights), I see the same debugging error as you when I artificially force the child process to throw a permission exception as soon as it starts. The error message in this instance might be misleading, as it's not clear that this is actually a debugger permission problem
It would be useful to know what type of application your child process is, because that will affect the debugging options that you have.
The first way I've tried to debug this is to intercept all unhandled exceptions in my child process (a console app). You can do this by adding the following code in the start-up procedure of your child app:
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(App_UnhandledException);
Then I added code to my App_UnhandledException procedure to log the exception. This worked for me, and I could see the reason for the permission error. The only caveat is that this won't intercept an exception where your app won't even load because of the permission problem. But this approach should at least reduce your search space in understanding the permission problem.
If the exceptioon is generated before your exception handler is reached, another possiblity is to use the assembly binding log viewer. This is a very useful tool.
FWIW you can step through your service code (but unfortunately not into your child process) by starting your service within Visual Studio. The code shown below in the switch case called DEBUG will let you start/debug your service within VS.
// This is the entry point
static void Main(string[] args)
{
// If parameter passed, act on it
if ( args.Length > 0 )
{
switch (args[0] )
{
// Debug the service as a normal app from within Visual Studio
case DEBUG:
MyService DebugService = new MyService();
DebugService.OnStart(null);
break;
// Install the service programatically
case INSTALL:
ManagedInstallerClass.InstallHelper(new string[] _
{ Assembly.GetExecutingAssembly().Location });
break;
// Un-install the service programatically
case UNINSTALL:
ManagedInstallerClass.InstallHelper(new string[] +
{ UNINSTALL, Assembly.GetExecutingAssembly().Location });
break;
// We don't understand this parameter!
default:
message = string.Concat(DEBUG, " to run service manually.", Environment.NewLine);
message += string.Concat(INSTALL, " to install service.", Environment.NewLine);
message += string.Concat(UNINSTALL, " to un-install service.", Environment.NewLine);
message += string.Concat("Do not understand the command-line parameter ", args[0]);
throw new System.NotImplementedException(message);
}
}
// If no parameter passed, just start the service normally
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
}
}
Have you tried running Visual Studio as Administrator and calling the Process.EnterDebugMode() method?
If I modify the code of the child process to launch debugging immediately on startup, it invites me to attach a debugger, but fails to complete the attachment, with a message that indicates that The Just-in-time debugger does not have permission to debug the process
Run secpol.msc as administrator and under 'Local Policies | User Rights Management' select 'Debug Programs'. Then add the 'Users' group to that. See if that fixes the permissions issue.
HTH

Windows service can't write to %LOCALAPPDATA%

I have built an app that works only when not run as a Windows service. Well, the service runs, but it doesn't do what it should. The service uses the Local Service account. So to kick off debugging, I thought I'd start with something simple: have it create a directory when it starts:
Directory.CreateDirectory(
Environment.SpecialFolder.LocalApplicationData + "\\MyService");
When I started the service, it stopped almost immediately and Windows reported that fact. When I commented out the above statement, recompiled and re-installed, the service ran without stopping.
Obviously the above line throws an exception of some sort. I have no way of logging the error because I can't write to the file system. Any ideas why Local Service can't create a directory in its own %LOCALAPPDATA%?
You should use GetFolderPath with LocalApplicationData like so:
string folderName = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
"MyService");
Directory.CreateDirectory(folderName)
I think this might be because there is no special folder. When running as the local service account you are running under that user, not the logged in user. so you are requesting a special folder that probably wont exist, as I don't think the local service has a profile. (I may be wrong) - I was wrong :p
Just in case anyone pops by:
C:\Windows\ServiceProfiles\LocalService
is the local service profile folder, so it will end up in there.
If you want to debug it surround that line with a try catch, and then write the error to a file:
try
{
Directory.CreateDirectory(Environment.SpecialFolder.LocalApplicationData + "\\MyService");
}
catch (Exception ex)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\MyServicelog.txt",true);
file.WriteLine(ex.Message);
file.Close();
}
At least then you can see whats causing the error
Martyn
I suggest you write the exception details to the event log. All user accounts have permission to write to the event log as long as the log and source names have already been created by an administrator (which you can do simply by running the app as yourself first).
As to the root cause of the error, it may be because LocalService doesn't normally get a full set of profile folders created by default. I'm not sure whether this is by design, or simply what I have observed on various machines.

C# console app that does Excel Interop - failing when running as scheduled Task -System.UnauthorizedAccessException

As the title states, I have a C# console app which uses interop to open Excel and create a new workbook. The code works fine when running the console app via command line. However this exception is thrown when running the console app via a scheduled task:
System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005
It is thrown from the following call:
_xlApp = new Excel.Application()
The scheduled task is setup to use my credentials (I am an administrator). Based on other forums I have made sure I have granted full control to my account at Component Services --> Computers --> My Computer --> DCom Config --> Microsoft Excel Application, but no luck.
I'm on Windows 7 Enterprise 64 bit. Not sure what the next step should be, any help is appreciated
The error 80070005 is a COM Access Denied error.
Are you sure that your credentials have the ability to instantiate the Interop Library?
Check this link and follow some of the debug steps.
(I know you said you did the DCOMConfig thing already, but there are more test scenarios in this link and hopefully something here will help you)
I ended up writing a windows service to call out to a library containing the Excel generation code. That fixed the error. However there was another COM exception when calling the workbook.Save() method. No matter what I tried that error would not go away. I read another post which stated that this was a security precaution and therefore by design.
However, calling workbook.SaveAs() will produce the same result and works fine when called from a windows service.
Thanks for the input funkymushroom. Hopefully this post will be helpful to someone else struggling with Excel Interop automation.
I had the similar issue, I have resolved the issue by performing the following steps.
DCOM Configuration
Click Start -> Run
Enter DCOMCNFG and press OK. This will open the DCOMCNFG window.
Browse down the tree to Console Root -> Component Services -> Computers -> My Computer
right-click on "My Computer" and select properties
Select the "Default Properties" tab
Enable Distributed COM on this computer - Option is checked
Default Authentication Level - Set to Connect
Default Impersonation Level - Set to Identify
Select the "COM Security" tab
Click on Access Permissions ' Edit Default
a. Add "Anonymous", "Everyone", "Interactive", "Network", "System" with Local and Remote access permissions set.
Click on Launch and Activation Permissions ' Edit Default
a. Add "Anonymous", "Everyone", "Interactive", "Network", "System" with Local and Remote access permissions set.
Click on OK
Close the DCOMCNFG window
Later I got an exception while opening the Excel. So please make sure that the following paths are available on the server.
C:\Windows\SysWOW64\config\systemprofile\Desktop
C:\Windows\SysWOW64\config\systemprofile\AppData\Roaming\Microsoft
C:\Windows\SysWOW64\config\systemprofile\AppData\Local\Microsoft
This might help guys like me.
I also had this problem - it turned out that on the scheduled task I needed to tick the box "Run with highest privileges" on the General tab of the task set-up. This resolved the problem - it was so simple! Hope it helps someone else too.

Categories

Resources