AccessViolation exception with TAPI and Windows Service - c#

I will try to make this as short and sweet as I possibly can.
I have created an application that is used by my company to call about 2000 different phone numbers each day (used to contact very old devices we have deployed around the US), When I run the application as a Windows Application (written using C# and JulMar ITAPI3 wrapper) the application seems to run rock solid with no issues which tells me at least my code is mostly right....
The problem I am encountering is when I run the same code as a Windows Service (create new project and simply call into the phone dialing library like the windows app does) The service will run for some period of time (varies each time) and then will finally crash. I look at the event log and see that it is an AccessViolation (0xc0000005) in the application. I have a try catch around my call into the tapi wrapper where the exception is happening but the catch never gets hit, I am assuming that it just crashes the app before it can get back to that point.
So in a nutshell, Tapi application works great when run as Windows Application but when run as a Windows Service (running under local system) eventually fails with AccessViolation error that is not caught by the try catch around the "offending" function call.
Any thoughts?
This is running on Windows Server 2008 if that helps any.
EDIT 1:
I have tried running this service as several different types of user accounts including local user account, domain account, local system. All of them error out. I have posted a snippet from the event log for one of the failures below.
Application: EaglePolloutWindowsService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
at <Module>.ATL.CComPtrBase<IUnknown>.{dtor}(ATL.CComPtrBase<IUnknown>*)
at JulMar.Tapi3.Internal.TapiBase.Compare(IUnknown*)
at JulMar.Tapi3.TTapi.FindInterface[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](IUnknown*)
at JulMar.Tapi3.TCall.CreateCallAppearance(JulMar.Tapi3.TAddress, IUnknown*)
at JulMar.Tapi3.TAddress.CreateCall(System.String, JulMar.Tapi3.LINEADDRESSTYPES, JulMar.Tapi3.TAPIMEDIATYPES)
at EaglePhoneLibrary.Logic.Outgoing.EaglePollout.CreateNewCall(EaglePhoneLibrary.Entities.ConnectionEntity)
at EaglePhoneLibrary.Logic.Outgoing.EaglePollout.CallTower(EaglePhoneLibrary.Entities.ConnectionEntity)
at EaglePhoneLibrary.Logic.Outgoing.EaglePollout.ContinueIteration()
at EaglePhoneLibrary.Logic.Outgoing.EaglePollout.ContinuePollout(EaglePhoneLibrary.Entities.ConnectionEntity)
at EaglePhoneLibrary.Logic.Outgoing.EaglePollout+<>c__DisplayClass52.<CallTower>b__4e(System.Threading.Tasks.Task)
at System.Threading.Tasks.Task+<>c__DisplayClassb.<ContinueWith>b__a(System.Object)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
at System.Threading.Tasks.Task.ExecutionContextCallback(System.Object)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef)
at System.Threading.Tasks.Task.ExecuteEntry(Boolean)
at System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Thanks to everyone for their help so far and in the future.
Edit 2: I have given up trying to resolve this issue. My best guess is that it stems from an issue with how JulMar is handling some of the COM objects being created in the wrapper. I convinced my company to pay for a license for TraySoft AddTapi .NET and it is working just fine now....
Thanks everyone.

When we had TAPI applications running as a service, we always had them run as a specific user rather than LocalSystem due to TAPI's use of user-specific phone settings (dialing rules, etc).
It could be that TAPI is trying to access one of these settings but is unable to because the user profile for LocalSystem hasn't been configured.

Related

C# COM application crash debugging

The C# console application running .NET 4.5.2 (app1) opens a COM application (app2) and does some work with that app2's API. So far all of the work is successful, but sometimes when app1 attempts to close app2, app2 hangs permanently.
If the process for app2 is ended with task manager then app1 reports access denied. Does that occur because the terminated process is no longer available or does it occur because it was blocking a thread in app1 and it was unable to report the error until the thread was allowed to continue?
The code used to terminate app2 is
private static void CloseSW(SldWorks swApp, Process sw_proces)
{
// Close with API call
if (Task.Run(() => { swApp.CloseAllDocuments(true); swApp.ExitApp(); }).Wait(TimeSpan.FromSeconds(20)))
return;
// Kill process if API call failed
if (Task.Run(() => { SWHelper.CloseSW(sw_proces); }).Wait(TimeSpan.FromSeconds(20)))
return;
// Unable to close SolidWorks, ignore error and continue
// This will eventually cause SolidWorks to crash and the crash handler will take over
}
This code should never take much more than 40 seconds to complete, but maybe the COM interop is causing some unexpected behaviour?
I am unable to reproduce this error on a development machine. What it the best way to trace the exact point of failure? It is possible that the failure is not in CloseSW but some point before this. Is there a better way to trace the error than to write each line to a log file?
It is also worth noting that this code works for 60 - 150 runs before it has any errors and both applications are closed between each run.
I have control of the remote environment so remote debugging is an option, but I've never set that up before.
Typically with COM interops causing issues is that IIS is having issues with the object using the current ISAPI.dll. Please verify that your permissions are configured within your assembly to work with your current version of IIS>
A few questions to help assist would be, which framework version are you using, which version of IIS and what is your Application Pool using for a framework.
HTH

Fusion Log Assembly Binder Error - Bind result: hr = 0x1. Incorrect function

I am trying to get to the bottom of a strange behavior on one machine. I have a trivial console application that will run interactively, but when I invoke it via WMI, it will start and exit immediately.
I enabled the Fusion log, since Procmon was unrevealing. I see the following error:
*** Assembly Binder Log Entry (31-01-2015 # 19:22:51) ***
The operation was successful.
Bind result: hr = 0x1. Incorrect function.
Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable C:\CMCBOOTSTRAP\Cmc.Installer.Agent.Console.exe
--- A detailed error log follows.
BEGIN : Native image bind.
END : Incorrect function. (Exception from HRESULT: 0x00000001 (S_FALSE))
What is the cause for "incorrect function"? What else can I look at to determine why this application effectively dies on startup via WMI?
And I mean trivial...
class Program
{
static void Main(string[] args)
{
Thread.Sleep(30000);
}
}
Environment is Windows Server 2012 R2 and .NET 4.5.
This is an entirely normal mishap, you got it from Fuslogvw.exe by selecting the "Native Images" radio button in the Log Categories setting. Readily reproducible on my own machine as well, I see many of them.
The actual error code is S_FALSE, a COM error code that means "it successfully failed". Which is why it says The operation was successful. Misinterpreted for the diagnostic message as "Function failed", that's the description for Windows error 1 and returned by the FormatMessage() winapi function.
The successful failure is entirely expected, you didn't run Ngen.exe on your console mode app yet so the native image for it is not available. Keep looking, this is not it. Change the Log Category back to "Default", native images are not your problem.
This error can also occur if you have a 64 bit dependency while your process or IIS runs on 32 bit.

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I have written a few C# apps that I have running via windows task scheduler. They are running successfully (as I can see from the log files that they are writing ) but windows task scheduler shows them returning a last run result of 0xE0434352. Is there something I need to do in my C# application so that it returns a success code to the windows task scheduler?
Another option is to simply use the Application log accessible via the Windows Event Viewer. The .Net error will be recorded to the Application log.
You can see these events here:
Event Viewer (Local) > Windows Logs > Application
When setup a job in new windows you have two fields "program/script" and "Start in(Optional)". Put program name in first and program location in second.
If you will not do that and your program start not in directory with exe, it will not find files that are located in it.
Hans Passant was correct, I added a handler for AppDomain.CurrentDomain.UnhandledException as described here http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx I was able to find the exception that was occurring and corrected it.
I was referencing a mapped drive and I found that the mapped drives are not always available to the user account that is running the scheduled task so I used \\IPADDRESS instead of MAPDRIVELETTER: and I am up and running.
In case it helps others, I got this error when the service the task was running at didn't have write permission to the executable location. It was attempting to write a log file there.
I had this issue and it was due to the .Net framework version. I had upgraded the build to framework 4.0 but this seemed to affect some comms dlls the application was using. I rolled back to framework 3.5 and it worked fine.
I got the same error but I have fixed it by changing the file reading path from "ConfigFile.xml" to AppDomain.CurrentDomain.BaseDirectory.ToString() + "ConfigFile.xml"
In my case, this error due to file path error because task manager starts program from "System32" as initial path but the folder we thought.
I was getting the same message message within dotNet Core 2.2 using MVC 5, however nothing was being logged to the Windows Event Viewer.
I found that I had changed the Project sdk from Microsoft.NET.Sdk.Web to Microsoft.NET.Sdk.Razor (seen within the projects.csproj file). I changed this back and it worked fine :)
In my case it was because I had message boxes. Once I commented that code out, it started working. I remembered that could be a problem when I looked at the event log as suggested in this thread. Thank you everyone!
I encountered this problem when working with COM objects. Under certain circumstances (my fault), I destroyed an external .EXE process, in a parallel thread, a variable tried to access the com interface app.method and a COM-level crash occurred. Task Scheduler noticed this and shut down the app. But if you run the app in the console and don't handle the exception, the app will continue to work ...
Please note that if you use unmanaged code or external objects (AD, Socket, COM ...), you need to monitor them!
Also message box in PowerShell. I converted PowerShell script to exe. When running as admin it's worked but in task schedule I received this error also.
There was an line in PowerShell script with write-output. After commented this line and compile new exe Task Schedule was completed successfully.
It is permission issue in my case the task scheduler has a user which doesn't have permission on the server in which the database is present.

C# SEHException when trying to access personal folder

Using C#, I'm getting a SEHEXception whenever I try to get the path to my personal folder via
Environment.GetFolderPath(Environment.SpecialFolder.Personal)
The detailed exception is:
System.Runtime.InteropServices.SEHException was unhandled
Message=External component has thrown an exception.
Source=mscorlib
ErrorCode=-2147467259
StackTrace:
at Microsoft.Win32.Win32Native.SHGetFolderPath(IntPtr hwndOwner, Int32 nFolder,
IntPtr hToken, Int32 dwFlags, StringBuilder lpszPath)
at System.Environment.GetFolderPath(SpecialFolder folder,
SpecialFolderOption option)
at System.Environment.GetFolderPath(SpecialFolder folder)
[...]
There's no InnerException.
Does anybody have an idea what's wrong? The problem does not occur when I try to get the system path, for example. I'm using Windows XP SP3 and Visual Studio 2010.
Also, I had a friend with vista and VS2005 try to do this on his machine and he doesn't get this Exception.
This is just a hunch, but by any chance are you running this code from an MTA thread?
I know that some Windows Shell API calls will fail if they are not running in STA. Truth be told, I have only ever encountered this problem when I was doing PInvoke stuff, but this call to the native SHGetFolderPath function in your stack trace tells me it just might be it.
So... to test my theory, can you try calling Environment.GetFolderPath(Environment.SpecialFolder.Personal) from Main in a simple console application and see if this call succeeds?
If it succeeds in a simple dummy application, then maybe MTA is the cause of failure in your app.
If it fails in a simple dummy application, your machine is probably messed up, or maybe just the user's profile. I would try creating a new user on the machine, logon to his account and try from there.
Edit:
Trying some more directions:
Look directly at HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders in Regedit and check if everything looks normal.
Check Event Viewer if other things are corrupted on the machine.
Restart the machine...? :)
Reinstall .NET Framework

System.Diagnostics.Process.Start() cannot start process when called from Windows service

I am trying to start an external process from a .NET Windows service. In the past I have used the Process.Start() overload that takes the executable path and a command line string. This works. But now I would like to start the process and have it run in the context of a particular user. So I call this version of Start()
public static Process Start(
string fileName,
string userName,
SecureString password,
string domain)
However, when I call the method, the application I am trying to run generates an unhandled exception:
The application failed to initialize properly (0xc0000142). Click on OK to terminate the application.
I have tried to start different applications and they all generate the same exception. I have run the code outside of the Windows service and the application starts correctly.
So is there a way to get this to work in a Windows service?
Maybe the user has to have, "logon as a service" security right. This is done with the "local security policy" application. And/or "logon as a batch job".
This is very similar to this question here. The answer is usually due to security issues with the desktop and window station in which the process is being run. See this article for an explanation and some sample code.
This is just a shot in the dark, but perhaps you can try to run the Windows Service in Interactive mode. If that works, though, this can't be done in Windows Vista (because of Session 0 Isolation).
Use Filemon and see if it is trying to open a config file and not finding it. I once had this error due to a malformed config.

Categories