(-2147024891, 'Access is denied.', None, None) - python-3.x

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

Related

Run-time error '52': Bad file name or number (SharePoint link vs Windows path)

When I try to assign a SharePoint link to flnameI I get a "Run-time error '52': Bad file name or number" on the yellow highlighte line in the image I attached
e.g. when flnameI = https://cogsandwheels.sharepoint.com/sites/accountsdept/test.xlsx
But when flnameI is equal to a windows explorer path like C:\Users\John.test.xlsx I get no issues.
How do I cater for a SharePoint link in this example?
flnameI = ActiveWorkbook.Path + "\" + folder + "\" + txtAgentFile.value
If Len(Dir(flnameI)) = 0 Then
MsgBox ("FATAL ERROR - file not found - " + flnameI)
End
End If
You are attempting to open a file from a SharePoint Online location as compared to a local file system. When you're opening the local path, Windows automatically authenticate you in the background and it "just works". When you're trying to go after cloud hosted content such as this document in SharePoint Online, you will firstly need to authenticate against M365 and secondly use something like REST, CSOM or Graph APIs to get the file. If you choose REST (since its the future anyway), Sunil wrote a great article about accessing SharePoint REST calls using OAuth here:
https://www.advaiya.com/access-sharepoint-rest-api-using-oauth/
The SharePoint REST APIs are documented here by Microsoft:
https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-rest-endpoints
Lastly, if your taste prefers Graph (which to be fair is just an API wrapper for REST calls anyway), then Microsoft has documented that for you here:
https://learn.microsoft.com/en-us/graph/api/resources/sharepoint?view=graph-rest-1.0

Auto load Office Centralized deployed custom Add-in using upload XML manifest file

I have created a customized add-in to PowerPoint and I deployed that through Centralized Deployment using upload manifest file in the Office 365 admin center.
I want this add-in to be loaded automatically when the user opens a document, for this I was used Open XML SDK to configure Office documents to automatically open a specified add-in
https://github.com/OfficeDev/Office-OOXML-EmbedAddin
But currently, I am not able to load it automatically. I am getting an error "Add-in Warning This add-in is no longer available."
.
I have mentioned two lines of code used in the program , here we used two ids for webextension and WebExtensionStoreReference.
please advice on these two lines to what parameter and values I want to use correctly
We.WebExtension webExtension1 = new We.WebExtension(){ Id = "{52811C31-4593-43B8-A697-EB873422D156}" };
We.WebExtensionStoreReference webExtensionStoreReference1 = new We.WebExtensionStoreReference() { Id = "af8fa5ba-4010-4bcc-9e03-a91ddadf6dd3", Version = "1.0.0.0", Store = "EXCatalog", StoreType = "EXCatalog" };
please help if anyone knows about this....!!

How to Logout from GMail using Python

I am trying to build a desktop Python3 application that will login to GMail and perform a few tasks. I have used the quickstart.py sample code given in the Google Developers Guide and it works perfectly. My application logs in and retrieves data.
However, after the program executes and terminates, the browser remains logged into GMail, unless the user specifically opens GMail on his browser and actually logsout. This is a security hazard as the user may forget to logout.
I am looking for way in which my python program will automatically log the user out before the program terminates. Will be grateful if someone can guide me on how this can be done.
The gmail API creates a file on CWD named "token.pickle" if you delete the file then logging in again with your program will require authentication.
So you can write a short program like this :
import os
files = os.listdir(".") # path to where credentials is stored
for file in files:
if file == 'token.pickle':
choice = input("""
Do you want to delete {}
1) yes.
2) no """.format(file))
if str(choice) == '1':
os.remove(file)
break
print("Done")
this is absurdly simple and i got the idea from here.
import webbrowser
webbrowser.open('https://mail.google.com/mail/u/0/?logout&hl=en', new=2)
As an updated answer for #Michael Gregory's solution, the file now is called: token_gmail_v1.pickle
so you it's now:
os.remove("./token_gmail_v1.pickle") # or -> os.remove("./*.pickle")
# as long as it's the only .pickle file
# in your working directory since this method is a dangerous one.
Instead of
os.remove("./token.pickle")
Side note: You can use it to check if the user is connected as well.
import os.path
isConnected= os.path.isfile("./token_gmail_v1.pickle")

How to handle data import and export from a Windows Universal app

I am developing a Windows Universal app that collects results of races. It saves each race result in a sql-lite database in an application folder so the user can view previous results. I have further requirements, however, for saving and opening race results.
I need to be able to export the results of a race as a CSV file so that they can be opened by a third-party application that might be running on a separate machine on a different operating system.
I need to be able to export the results as an HTML file that can be uploaded/included in the user's own web site.
I need the user to be able to print the results (which I was thinking could just be done by printing the HTML file from a browser)
I would like the user to be able to choose to import the results of a race created by my own legacy application in my own format.
It seems, however, that we are restricted in a Windows Universal app to saving files to just very specific folders under very specific circumstances if we have requested that app capability. Therefore I am getting access denied errors both saving and reading files using the FileOpenPicker and FileSavePicker.
I think I probably need to view the export and import of results in a different way, but after a lot of searching I have not been able to come up with the right and recommended solution to this. So the question is how should I be handling the import and export of results? Should I be using the user's documents folder, or their OneDrive? Do I need to create a web application for my app so that the user can store results in the cloud and download them from there?
CSV and HTML are both text files with some encoding. So your question is about how to read/write files with JS.
Here is example how to create html page with FileSavePicker:
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
savePicker.fileTypeChoices.insert("Web page", [".html"]);
savePicker.suggestedFileName = "New page";
savePicker.pickSaveFileAsync().then(function (file)
{
if (file) {
var _WriteThis="<!DOCTYPE html>" + "\r\n";
_WriteThis = _WriteThis + "<html><head><title>Web page title</title>" + "\r\n";
// .....
Windows.Storage.FileIO.writeTextAsync(file, _WriteThis, Windows.Storage.Streams.UnicodeEncoding.utf8);
}
});
This example doesn't required any special rules and you can save file anywhere on you PC HDD or USD stick without setting capabilities in manifest (except system folders)
Same way you can save in csv format

Application throws an error when launched from task scheduler

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

Resources