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

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

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

How to Upload images from local folder to Sitecore

`webClient.UploadFile("http://www.myurl.com/~/media/DCF92BB74CDA4D558EEF2D3C30216E30.ashx", #"E:\filesImage\Item.png");
I'm trying to upload images to sitecore using webclient.uploadfile() method by sending my sitecore address and the path of my local images.But I'm not able to upload it.I have to do this without any API's and Sitecore Instances.
The upload process would be the same as with any ASP.net application. However, once the file has been uploaded you need to create a media item programtically. You can do this from an actual file in the file system, or from a memory stream.
The process involves using a MediaCreator object and using its CreateFromFile method.
This blog post outlines the whole process:
Adding a file to the Sitecore Media Library programatically
If you're thinking simply about optimizing your developer workflow you could use the Sitecore PowerShell Extensions using the Remoting API as described in this this blog post
If you want to use web service way than you can use number of ways which are as follows:
a) Sitecore Rocks WebService (If you are allowed to install that or it is already available).
b) Sitecore Razl Service(It is third party which need license).
c) Sitecore Powershell Remoting (This needs Sitecore PowerShell extensions to be installed on Sitecore Server).
d) You can also use Sitecore Service which you can find under sitecore\shell\WebService\Service.asmx (But this is legacy of new SitecoreItemWebAPI)
e) Last is my enhanced SitecoreItemWebAPI (This also need SitecoreItemWebApi 1.2 as a pre-requisite).
But in end except option d you need to install some or other thing in order to upload the image using HTTP, you should also know the valid credentials to use any of above stated methods.
If your customers upload the image on the website, you need to create the item in your master database. (needs access and write right on the master database) depend on your security you might consider not build it with custom code.
But using the Sitecore webforms for marketers module With out of the box file upload. Create a form with upload field and using the WFFM webservices.
If you dont want to use Sitecore API, then you can do the following:
Write a code that uploads images into this folder : [root]/upload/
You might need to create folder structure that represent how the images are stored in Sitecore, eg: your images uploaded into [root]/upload/Import/ will be stored in /sitecore/media library/Import
Sitecore will automatically upload these images into Media library
Hope this helps
Option: You can use Item Web API for it. No reference to any Sitecore dll is needed. You will only need access to the host and be able to enable the Item Web API.
References:
Upload the files using it: http://www.sitecoreinsight.com/how-create-media-items-using-sitecore-item-web-api/
Enable Item Web Api: http://sdn.sitecore.net/upload/sdn5/modules/sitecore%20item%20web%20api/sitecore_item_web_api_developer_guide_sc66-71-a4.pdf#search=%22item%22
I guess that is pretty much what you need, but as Jay S mentioned, if you put more details on your question helps on finding the best option to your particular case.
private void CreateImageIteminSitecore()
{
filePath = #"C:\Sitecore\Website\ImageTemp\Pic.jpg;
using (new SecurityDisabler())
{
Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
options.FileBased = true;
options.AlternateText = Path.GetFileNameWithoutExtension(filePath);
options.Destination = "/sitecore/media library/Downloads/";
options.Database = masterDb;
options.Versioned = false; // Do not make a versioned template
options.KeepExisting = false;
Sitecore.Data.Items.MediaItem mediaitemImage = new Sitecore.Resources.Media.MediaCreator().CreateFromFile(filePath, options);
Item ImageItem = masterDb.GetItem(mediaitemImage.ID.ToString());
ImageItem.Editing.BeginEdit();
ImageItem.Name = Path.GetFileNameWithoutExtension(filePath);
ImageItem.Editing.EndEdit();
}
}

Issue while Instantiating SharePoint 2010 method in MSCRM 2011 plug-in

This is regarding SharePoint 2010 Integration with MSCRM 2011.
While creating a record in CRM, trying to create a Custom Document location for that record and a similar folder in sharepoint, So that when user clicks on document link in the entity record it does not prompt user to create folder in Sharpoint (Trying to avoid sharepoint noise for better user experience)
I have implemented through post create asynchronous plug-in. (I did this through console program working fine). Build the plugenter code here-in and deployed to CRM.
When creating a record it error out with a message like "An internal server 500 error - Could not load the assembly with public key token etc…blab bla bla…”
But when I am debugging the plug-in it failed at the first line of command where I am instantiating sharePoint method Create client context of sharepoint, it says [System.Security.SecurityException]={“That assembly does not allow partially trusted callers”.}
As per google, per this issue it should be having one attribute “Allow partial users” in assembly info file. As per my understanding, this should be done in because the request goes from CRM plug-in to SharePoint dll. I mean share point dlls are not allowing request from my assembly. How can we change that?
I have referenced Microsoft.SharePoint.client.dll and Microsoft.SharePoint.Client.Runtime.dll
What is the alternate to overcome this issue?
Appreciate if some one can help me ..Thanks In advance.
Here is my code for SharePoint
ClientContext clientContext = new ClientContext(siteUrl)
CredentialCache cc = new CredentialCache();
Cc.Add(new Uri(siteUrl), "NTLM", CredentialCache.DefaultNetworkCredentials);
clientContext.Credentials = cc;
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
Web web = clientContext.Web;
SP.List list = web.Lists.GetByTitle(listName);
ListItemCreationInformation newItem = new ListItemCreationInformation();
newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
newItem.FolderUrl = siteUrl + "/" + folderlogicalName;
if (!relativePath.Equals(string.Empty))
newItem.FolderUrl += "/" + relativePath;
newItem.LeafName = newfolderName;
SP.ListItem item = list.AddItem(newItem);
item.Update();
clientContext.ExecuteQuery();
Where I am passing the siteurl, folderlogicalname,relativepath and new foldername as parameters.
This works fine from my Console application. But when converted to CRM plug-in it gives the above specified issue
I've seen a similar issue before.
CRM plugins run inside a sandbox, so all assemblies and .NET libraries used must allow partial trust callers (since the CRM sandbox runs under partial trust). It works in the console because you are executing the code as a full trust user in that context.
This issue is not necessarily your code, but could be a dependency or a .NET library itself does not allow partial trust callers - in your case it sounds like the Sharepoint library is the culprit (but a stack trace of the error should reveal exactly where the cause is).
Since you don't have access to the source library causing the problem, to overcome the error you will likely have to create a wrapper. However, the problem is the wrapper cannot directly reference the problem library or you will get the same issue. So to get around this, you may have to create a web service which acts as your wrapper and then call the web service in your CRM plugin. This way the full trust code is executed by the web service (which is full trust) and then returns the result to your calling CRM plugin.
Here is more info on the error.
Thanks Jason. This works for me.
I Would like to add additional few points to the answer.
1. I have added the sharepoint dlls to the bin folder of CRM 2011 site.
2. Also deployed the same dlls in the folder whereever Async job is running to make my Async plug-in to work.
Thanks once again for the cooperation

How do I modify the Site Collection in SharePoint 2013?

When I try to open a form published from InfoPath I now get this error:
"The following location is not accessible, because it is in a different site collection:
https//portal/sites/forms/Daily%20Activity/Forms/template.xsn?SaveLocation=https//portal.alamedacountyfire.org/sites/forms/Daily%20Activity/&Source=https//portal.alamedacountyfire.org/sites/forms/Daily%2520Activity/Forms/AllItems.aspx&ClientInstalled=false&OpenIn=Browser&NoRedirect=true&XsnLocation=https//PORTAL/sites/forms/Daily%20Activity/Forms/template.xsn."
Correlation ID:12c0ab9c-caff-80a8-f1b4-64d81dcfa6ea
Following are some options that you can try:
1) Save the form template (.xsn) as the source files in the publish options. Look at the manifest file in notepad and see if you can find a reference to the incorrect location. If so, correct it and Republish the form.
2) Clear the InfoPath cache on that machine. Start->Run "infopath /cache clearall"
3) See if the site collection has a managed path, if so, give the proper url while publishing. The XSN might be getting deployed on the root site and throws error since the intended list does'nt exist.
I found this worked for me. Got the answer from another post.
"I had a similar problem and found it was due to the request management service routing from my web application host header to the server name.
There was a routing rule in my request management settings. I just disabled routing and the problem went away. I used the following powershell to disable it. "
$w = Get-SPWebApplication "http://webapphostname"
$r = $w | Get-SPRequestManagementSettings
$r.RoutingEnabled = $false
$r.Update()
You may want to configure it rather than disable it. Here’s a good resource to get you started:
http://www.harbar.net/articles/sp2013rm1.aspx

How to Download Documents from a a Sharepoint Document Library using Workflow Foundation?

I have some Test, Security, Project Management and some other word documents in TFS2010 source control under Documents folder. Does anybody know how to access them in order to download and copy to a local path?
Those files are not physically under $/... folder, though they have a Sharepoint web server path like: "http://myServer/sites/MyProyect/Test/Tests_P13_F00120.doc". I have tried to use DownloadFiles activity without success due to it needs a path which starts with $/. Any suggestion please?
DownloadFiles is not an activity you can make use of, it's meant to deal with files residing in Source control.
Instead, you need to establish a connection to the Sharepoint Copy service of your TFS, which resides at http://<Site>/_vti_bin/Copy.asmx. We did this by adding a Service Reference in our build solution.
We then implemented a build activity that does basically the opposite of what you are after: during TFS build it uploads documents into Sharepoint.
The instantiation looks like this:
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
EndpointAddress endpointAddress = new EndpointAddress("http://<Site>/_vti_bin/Copy.asmx");
CopySoapClient copyService = new CopySoapClient(binding,endpointAddress);
This copy service exposes a GetItem method, this is the one you should probably be invoking.
I 'm not aware if this GetItem is capable of supporting a http://myServer/sites/MyProject/Test/*.doc kind of thing

Resources