Application throws an error when launched from task scheduler - excel

I have a custom application which uses Microsoft.Office.Interop.Excel.Application to open and save excel file. I have a batch which fires the app with all the required parameters. That batch completes the task successfully when run manually but when I tried to schedule the same in task scheduler I got the following error msg logged from ma app:
Microsoft Office Excel cannot access the file
'E:\tasks\extractSPdocs\downloads\Last_Minute_IT_DATA_DUMP_201404250000.xls'.
There are several possible reasons:
The file name or path does not exist. The file is being used by
another program. The workbook you are trying to save has the same
name as a currently open workbook.
I know the error is thrown from the following code section:
try
{
excelfile = new Microsoft.Office.Interop.Excel.Application();
excelfile.DisplayAlerts = false;
var wb = excelfile.Workbooks.Open(dirpath + "\\" + csvname);
wb.SaveAs(dirpath + "\\" + csvname.Substring(0, csvname.LastIndexOf('.')), Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);
csvname = csvname.Substring(0, csvname.LastIndexOf('.')) + ".xlsx";
csvext = ".xlsx";
}
The task is created with the same account I am using (local admin).
It is set to run with highest privileges and to start in the batch file directory.
The OS is Windows Server 2008.
I do not know why this is failing but suspect this has something to do with the context in which the scheduler launches my application which then subsequently launches Excel. Can anybody suggest a solution?

I have found a solution here http://justgeeks.blogspot.co.uk/2012/10/troubleshooting-microsoft-excel-cannot.html
the trick is you have to craete this folder:
C:\Windows\SysWOW64\config\systemprofile\Desktop
I must admit I do not quite understand why this folder is required for excel to open files when launched by task scheduler but it works.

Actually I haven't tried the answer by #Maju but this Superuser question has a solution which worked for me: you have to config DCOM. I set the identity to run Excel to the identity which I'm using in the Task Scheduler.
https://superuser.com/questions/579900/why-cant-excel-open-a-file-when-run-from-task-scheduler

I added the following directory c:\windows\syswow64\config\systemprofile\desktop

Related

(-2147024891, 'Access is denied.', None, None)

I am developing a Django (v 3.2.6) application (Python 3.9.1.) which needs to write into an Excel file using pywin32.com.
On the client side it works fine, but when I put in production using IIS (v 10) on a Windows 11 server, I get the error above.
I have a routine that reads in a file input by the user and writes to the project directory:
if request.method == 'POST':
# Create a form instance and populate it with the file from the request (binding):
form = Name1_uploadForm(request.POST, request.FILES)
if form.is_valid():
# Create variable for uploaded file
uploaded_excel_file = form.cleaned_data['excel_file']
# Write it to BASE_DIR
with open(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name), 'wb+') as destination:
for chunk in uploaded_excel_file.chunks():
destination.write(chunk)
# Allow the write process to conclude
time.sleep(12)
# Close the file
destination.close()
# Call conversion function
Name1_extraction(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name))
# redirect to a new URL:
return HttpResponseRedirect(reverse('index') )
else:
form = Name1_uploadForm()
This calls another function (below) that should open that same file:
def Name1_extraction(uploaded_excel_file):
const = win32.constants
# Need to run CoInitialize to use win32com.client
pythoncom.CoInitialize()
# Open Name1 excel with Win32com
excelFile = win32.gencache.EnsureDispatch('Excel.Application')
The complete error is the following:
enter image description here
enter image description here
enter image description here
The error occurs when the following line of code is executed:
excelFile = win32.gencache.EnsureDispatch('Excel.Application')
The application pool is IIS AppPool\DefaultAppPool.
DefaultAppPool has been granted full access to folders C:\Windows\SysWOW64\config\systemprofile\Desktop and C:\Windows\System32\config\systemprofile\Desktop
With these actions I would not expect to see any errors
Thank you for any help provided.
Microsoft does not recommend or support server-side Automation of Office, and Microsoft strongly recommends that developers look for alternatives to Automation of Office when they need to develop server-side solutions.
Due to limitations in the design of Office, changing the Office configuration alone is not sufficient to resolve all issues. Microsoft strongly recommends some alternatives that don't require a server-side installation of Office and can perform most common tasks more efficiently and faster than Automation.
Most server-side automation tasks involve document creation or editing. Office 2007 supports the new Open XML file format, which allows developers to create, edit, read, and transform file content on the server side. This is the recommended and supported method of handling changes to Office files from the service.
How to use the Open XML SDK 2.5 for Office, please refer to the Microsoft documentation:
https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk
Considerations for server-side Automation of Office, please refer to this Microsoft blog:
https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2
I've had a similar problem:
I had a Python program with the xlwings library and I created a .bat file.
When I launched it by hand it worked perfectly, but with Windows 10 Scheduler I received an error "(-2147024891, 'Access denied.', None, None)".
I carried out the automatic correction of the Excel file which can be done by going to Excel > File > Info > Verify document.
My problem was that the Windows Scheduler didn't accept comments in the .xlsm file.
I deleted all the comments and then the Windows Scheduler started

Call executable on IIS 10 with exit code -1073741819

I want to call an executable file from a web application hosted within IIS 10.
When I run my application locally with IIS Express everything works fine, but after deploying on the production server, I only get the exit code -1073741819.
On the product server I gave full rights for the user of the application pool in the folder, where the exe file is located, but that did not work as well.
Do I have to set other, special rights to the user?
This is my code ...
ProcessStartInfo procStartInfo = new ProcessStartInfo(libreExecutable.FullName, argument);
procStartInfo.CreateNoWindow = true;
procStartInfo.UseShellExecute = false;
procStartInfo.WorkingDirectory = workingDirectory;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
// This is empty with code -1073741819
process.StandardError.ReadToEnd();
-1073741819 is 0xC0000005, that means ERROR_ACCESS_DENIED. IIS doesn't have permission to call the .exe file.
I gave full rights for the user of the application pool in the folder
I don't know how you do. But it is better to add IIS APPPOOL\pool name in folder security property and set it full control permission.
If it still report this error, please try to change the application pool identity. Administrator has the highest authority, try to change identity to administrator.

Unable to use SelectPDF after deployment to IIS

I have a function that generates a PDF from a HTML page like this:
HtmlToPdf converter = new HtmlToPdf();
PdfDocument doc = converter.ConvertUrl(url);
var PdfArray = doc.Save();
doc.Close();
This works perfectly when I run it in VS 2017, However when I deploy to IIS it throws the following exception: "Conversion failure error 5."
According to my Googling this is related to the IIS not having the correct access to write. However I have as an attempt given that application access to every operation.
All suggestions would be greatly appreciated.
From the troubleshooting page on SelectPdf website:
https://selectpdf.com/docs/Troubleshooting.htm#item3
The error code is this:
ERROR_ACCESS_DENIED
5 (0x5)
Access is denied.
Enable execute permissions on Select.Html.dep.
You need to go to the bin folder of your deployment to IIS and set execute permissions for the Select.Html.dep file. If you do not know the app pool user, in the first place, just set permissions for Everyone to see if it works.

Access denied upon doing a GetDirectories() but Dir in Powershell works

I have a problem I hope someone might help me with.
I've created a custom action page where I among other things will scan a directory on a remote server for a set of directories, and inside those directories I am searching for a set of files.
However, when I execute the code on the production server I get an Access denied exception.
If I use the same code on my testserver (accessing the same remote server) it works just fine.
If I use powershell or explorer on the production server I can access the remote directory and files with no problems.
I am using the same account in all scenarios (if I print out Page.User.Identity.Name and SPContext.Current.Web.CurrentUser.LoginName they are the same and equal to the account I use on the test server and the one I am logged on with on the production server when accessing the remote server from command line or explorer).
The code looks like this:
string user = SPContext.Current.Web.CurrentUser.LoginName.Remove(0,7);
string user_path = "\\\\srv\\share1\\subdir\\dir\\" + user;
// The line below will raise an exception on the production server.
foreach (string board_path in Directory.GetDirectories(user_path, "Board*")) {
foreach (string board_file in Directory.GetFiles(board_path, "Board*.xml")) {
.
.
}
}
I cant figure out why the code runs on the testserver but not on the production machine. I am using SharePoint 2010 Standard.
Thanks in advance for any kind of help I can get.
/Fredrik
The problem was solved by using SPSecurity.RunWithElevatedPrivileges()!
/Fredrik

WMI/PowerShell Bug: why is CreateSite creating *two* sites all of the sudden?

I have a simple PowerShell script that uses WMI to create a web site on a Vista box. Yes, I know PowerShell has an IIS provider for working with IIS 7, but this script must also support IIS 6.0, so that rules that out.
Anyway, the script was working just fine, but all of the sudden (and I mean that literally, I made zero code changes to the script) it started creating a second, broken site for every call to the CreateNewSite method. Below is the script. Anyone have any ideas?
$path = "C:\My Path\WebSite"
$site = "TestSite"
$hostHeader = "demo.blah.com"
$service = Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsWebService"
$bindingClass = [wmiclass]'root\MicrosoftIISv2:ServerBinding'
$bindings = $bindingClass.CreateInstance()
$bindings.IP = ""
$bindings.Port = "80"
$bindings.Hostname = $hostHeader
$result = $service.CreateNewSite($site, $bindings, $path)
The above script was just creating a site named 'TestSite', but now it's also creating a site called 'SITE_1786339847' (the number changes, but it's always similar to that). I have stepped through the script executing one line at a time, and neither site is created until the CreateNewSite method is invoked. Is WMI just buggy?
Whoops, answered my own question. I checked the raw IIS 7.0 configuration file and found an orphaned virtual directory that was associated to a site with the ID 1786339847. When I removed that virtual directory from the configuration file, the script started working correctly again.
In case anyone runs into something similar, grab the site ID for the bad site from IIS Manager before deleting it, then open up C:\Windows\system32\inetsrv\config\applicationHost.config. Scan the file for that ID and look for any orphaned references to it. Be sure you have a backup first.

Resources