Open file directly from SharePoint path with CSOM - c#

I have a SharePoint server and I want to open files directly from the Server with SharePoint CSOM.
User clicks button --> the file (Excel, Word, ...) opens at the client machine with the standard software.
Directly means, that if I change something to the file and click save, that the file is directly saved on the SharePoint server (or if I click e.g. 'Save as' in Excel the suggested path is 'https://sharpoint.url.com/folder').
Actually I have:
using Microsoft.SharePoint.Client;
var clientContext = new ClientContext("https://sharpoint.url.com");
string relativePath = "/folder/file.xls";
clientContext.Credentials = CredentialCache.DefaultCredentials;
var file = clientContext.Web.GetFileByServerRelativeUrl(relativePath);
clientContext.Load(file);
clientContext.ExecuteQuery();
What do I have to do now, if I want to open the file directly (no download)?

I assume you ask how to access the file's stream instead of downloading it to a local folder.
You can use the File.OpenBinaryDirect method to get access to its ETag and stream, eg :
using(var fileInfo=File.OpenBinaryDirect(clientContext,"/folder/file.xls"))
using(var reader=new StreamReader(fileInfo.Stream))
{
//Do whatever you want with the data
}
BTW you shouldn't use the old xls files. The format is deprecated for over 10 years. The current Excel format, xlsx, is a zipped package of XML files that's better supported by SharePoint itself, doesn't require Excel to generate or read.
For example, if you wanted to read cell values from an xlsx file, you could use the popular EPPlus library to read directly from the stream:
using(var fileInfo=File.OpenBinaryDirect(clientContext,"/folder/file.xlsx"))
using(var package=new ExcelPackage(fileInfo.Stream))
{
var sheet=package.Workbook.Worksheets[0];
var value=ws.Cells["A1"].Value;
//...
}
UPDATE
It seems the question isn't related to programming after all. All that's needed to save or open a SharePoint document is clicking on the document's link. What happens then depends on the Open Documents in Client Applications setting at the site and document library level.
This affects the headers the server sends to the browser when the user clicks on a document link. The browser may still refuse to open the registered application and display the Save dialog.
If that doesn't work, you should check why instead of writing code. It's probably a configuration error or a browser setting. Solving it is easier than creating workarounds, pushing them to all client machines. And then keeping track of all the patches, where they are deployed and deploying new ones.
Apart from that, the Office applications know about SharePoint and document libraries since 2003. They can browse them, display SharePoint properties for the document, show collaborators etc.
As I mentioned in the question comments, a lot of what people think as "SharePoint Developoment" is nothing more that configuration, administration and end user features.
MSDN docs don't help either - they actually cause harm by not covering SP administration or explaining the features and how they are used. You'll find that in Technet. For years, people created webparts in code to change how grids looked because MSDN didn't explain how eg the DataViewWebPart worked or how you could style a grid from the UI.
In general, the best place for such questions is http://sharepoint.stackexchange.com. For example, check “Open in the client application” Vs “Use the server default (Open in the client application)” inside the document library advance settings

We can create Map Network Drive for SharePoint library, and open the file from the network location. Check article below:
http://support.sherweb.com/Faqs/Show/how-to-connect-to-a-sharepoint-site-using-webdav-sharepoint-2013
Or we can download the file from SharePoint and open it using the code below:
Application.Workbooks.Open(#"C:\Test\YourWorkbook.xlsx");
Reference: https://msdn.microsoft.com/en-us/library/b3k79a5x.aspx

Related

PDFTron: Powerpoint ConverToXod not working

In my ASP .Net application, I am using 'PDFTron 6.6.0.38591'.
We are using following code to convert Office documents to XOD:
string fileName = Path.GetFileName(pdfTronServiceRequest.FilePath);
fileName = ConstructConvertionFileName(fileName);
outFileName = Path.Combine(outputPath, fileName);
pdftron.PDF.Convert.ToXod(pdfTronServiceRequest.FilePath, outFileName);
response.Result = outFileName;
This code works well for filetypes like docx, xlsx, however for Powerpoint files, no response is returned(request timed out).
On checking the Task Manager window, we can see that a process for 'POWERPNT.exe' is started. However, this process never ends up itself(unlike that in case of word, excel upload).
Also, if I manually ends up this process, the conversion to XOD is successful and response is coming out correctly.
Also, please note that we are facing this issue only when we deploy the code on our test environments. Locally, PPT upload is working fine.
Let me know if you need any other information.
First, you should be running a licensed version of PowerPoint, not a trial/eval one. In particular, the account (including a Service/App Pool account) needs to have accepted the MS office licensing to make sure Office is a fully licensed product.
Also, is this happening with any ppt file or only certain ones? If certain ones, then try using one of the following two flags.
pdftron.PDF.Convert.Printer.SetMode(mode)
e_printer_only
e_interop_only
Finally, switch to the latest version. Which at the very least should provide a lot more debugging info in the exception message.

Microsoft Office Document shows Sharepoint URL instead of Local

Situation: OneDrive for Business syncs files from Sharepoint Site Document Library to local directory:
C:\Users\users\Sharepoint\Library\Test.pttx
However with PowerPoint InterOp the:
presentation.Path
Is:
https://company.sharepoint.com/Library/Shared%20Documents/
Which is the correct path for Sharepoint.
How can I access the local directory?
Update: I found a similar question on MSDN but no answer
According to this post, the synced folders can be looked up in this multi-string registry value:
HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common
\Internet\LocalSyncClientDiskLocation
Given that your local path and SharePoint URL look like
C:\Users\User\SharePoint\Library - Documents\Folder\SubFolder\Document.pptx and
https://***.sharepoint.com/Library/Shared%20Documents/Folder/SubFolder/Document.pptx,
you could try extracting the local part Folder/SubFolder/Document.pptx from the URL, add it to the local folder paths retrieved from the registry value and check for file existence.
If I understand correctly you want a way in Powerpoint (VSTO) to get the local path of the Sync'd directory? A method in the Powerpoint Object Model like presentation.GetLocalPath()?
I dont know why (in the MSDN link in your question) the MSFT CSG engineer said that it was impossible.
Sorry for the mistake, after the further investigation, it is
impossble. For the Word Application, the file is stored on the
OneDrive, and the "Offline" is cache mode for OneDrive, it is
transparent to Word Application (Word Application only know it is a
document on OneDrive), so when you check the location of the opened
document, the location is "http:/d.docs.live.net/xxxx/xx.docx" rather
than "C:\XXX\XXX".
This article shows you how you can Change the location where you sync SharePoint libraries on your computer. Obviously there isn't a method in the Powerpoint Interop Library but its definitely possible.
1) My first thought was to see if the OneDrive for Business sync app wizard saves any registry key or anything like that (using ProcessMonitor) but it probably stores the local directory in the cloud.
2) My second thought is a bit outside the box, just put a text file in https://company.sharepoint.com/Library/Shared%20Documents/LocalDrivePath.txt, then create an Extension method called presentation.GetLocalPath() and use the WebClient class to download the string.
Pseudo code:
public string GetLocalPath(this Microsoft.Office.Interop.PowerPoint.Presentation presentation)
{
WebClient client = new WebClient();
string localPath = client.DownloadString(presentation.Path + "LocalDrivePath.txt");
//Some good old protective programming to quickly identify the problem if the file doesn't exist
if (!string.IsNullOrEmpty(localPath)) throw new Exception("Issue: LocalDrivePath.txt not found in " + presentation.Path + Environment.Newline + "Please add the file for this Office Documents' sync'd (offline) local folder to be identified.");
return localPath;
}
Call it like so:
presentation.GetLocalPath();

Opening up PDFs and other documents from Silverlight out of browser

I'm having a little problem figuring out the best way to open up a file that I have stored in a database. The file is being stored as a byte array in a nvarbinary field in the database. Currently when I want to open up a file I use an ASP.NET webpage that I pass a variable to and write the file stream to the page. This works fine when using the in browser version of the Silverlight application, but when out of browser I cannot invoke a browser window to open because I don't have access to dom.
How can I open the bytearray from Silvelright without invoking a browser window? I'm able to pass the bytearray and file type to the Silverlight app no problem. I just don't know how to display it once I have it there..
Thanks!
If you are targeting windows (with full trust enabled, and not mac), you can do this out-of-browser by first writing the file to disk (either in isolated storage or in My Documents), then using a WScript.Shell COM object to have the OS open the file.
After you have saved the byte stream to a file and have the file location, you can do:
using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
{
shell.Run(fileLocation); //works similar to start -> run -> filename
}
If you want to leverage your existing ASP page, you can pass its URL to shell.Run and the OS will use the user's default browser to open that page.
On a mac, the best you could do is save the file to their user directory, and have them manually navigate there with finder and double-click it.

Remote Upload Sharepoint programatically using C#

Is it possible to remotely upload files using a Windows Application (C#) to Sharepoint Server?
Thank you.
Yes, although you may need some of the SharePoint assemblies on the "remote" machine in order to achieve what you need.
Uploading files using Client Object Model in SharePoint 2010 is a pretty good starting point for SharePoint 2010.
In case you are using the 2007 version (WSS 3.0), you can find a great summary of different ways to upload files on this link: http://vspug.com/smc750/2009/05/19/uploading-content-into-sharepoint-let-me-count-the-ways/
You must be very careful if your farm is 32bit, in that case it is very easy to use up all the available memory in the w3wp.exe process if you're uploading large files or many files in parallel, especially if the farm is a busy one. In that case you might want to use the RPC interface described in the link above, since this is the only one where you can upload files in chunks. With all other ways the entire file being uploaded must first be loaded in the w3wp's memory before it's committed to the SharePoint list item.
For ways that involve SharePoint object model, you might want to write your own web service facade to enable the clients that do not have SharePoint dlls to upload files (+ metadata if you need it).
You can use the client object model in sp2010, rather than talking to the web services directly.
Taken from my upload profile picture applications:
http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709
using (ClientContext context = new ClientContext(siteurl)) {
context.AuthenticationMode = ClientAuthenticationMode.Default;
List list = context.Web.Lists.GetByTitle(listname);
context.Load(list);
context.Load(list.RootFolder);
context.ExecuteQuery();
string url = siteurl.CombineUrl(list.RootFolder.ServerRelativeUrl).CombineUrl(listfolder).CombineUrl(name);
FileCreationInformation fci = new FileCreationInformation();
fci.Content = data;
fci.Overwrite = true;
fci.Url = url;
Microsoft.SharePoint.Client.File file = list.RootFolder.Files.Add(fci);
context.ExecuteQuery();
}
I wrote a tool available as a NuGet package in Visual Studio called SharePoint.DesignFactory.ContentFiles. With this tool you can manage all files with metadata to be uploaded to the SharePoint content database. You can use this for SharePoint 2007 (currently have to work on the SharePoint machine itself) or for SharePoint 2010 and Office 365. In this case you can work from a machine without SharePoint installed. See http://weblogs.asp.net/soever/archive/tags/SharePoint.DesignFactory.ContentFiles/default.aspx for blogposts on the tooling.

IIS Permissions for Saving Word Documents

Our ASP.NET/C# lets users edit and manage Word (OpenXML) documents that are hosted on a server. I am using client-side VBScript functions to handle some of the editing functions including saving the document to a folder on the server. For the save functionality, I am using the following function call :
Document.SaveAs "http://server/savefolder/savefile.docx"
I have given "Full Control" permissions on savefolder to both the NETWORK SERVICE and the IUSR_MACHINE users. Yet the above call fails. The error number returned is 5096. The error message is some gibberish that doesn't make any sense.
The server is Windows 2003 and the IIS version is 6.0. I have installed the OpenXML SDK 2.0 CTP on the server.
I can successfully read and print documents.
Does anyone tell me what I am doing wrong? or what additional settings need to be in place?
BTW, the error message ("gibberish" from my post) is:
"EOALPHABETICARABICARABICABJADARABICALPHABAHTTEXTCAPSCARDTEXTCHARFORMATCHI"
No, I am not making this up!
In my case, that error 5096 with description "EOALPHABETICARABICARABICABJADARABICALPHABAHTTEXTCAPSCARDTEXTCHARFORMATCHI"
occurred when using VBA code in Access to drive a Word mail-merge. The cause was trying to save a document with the same name (including path) as an open document.
Error line:
objApp.ActiveDocument.SaveAs saveAsName
where objApp is the object variable representing the Word application and saveAsName is the string variable storing the name I am trying to save the file as e.g. "C:\temp\testdoc.docx".
IF a file with the same name exists but is not open, the above code overwrites it silently.
Turns out WebDAV is not turned on by default in IIS 6.0. Once I turned it on, I was able to save the documents just fine.
Thanks for all your answers!
Just a guess... if the vbscript is running on the client, the code is probably running under the user's account, not under the server's IIS account. So unless you give write access to that user, vbscript probably won't work for this.
Since you're using ASP.NET, you could try writing a web service that takes in Word document data and saves it to the server for you.
I'd try running Fiddler on the client while trying to save the document to get a sense of what's really going on. I wonder if maybe it's trying to do an HTTP PUT (as opposed to a POST).
Have you given write access to the folder in IIS manager?
Is the save folder you're using outside of the websites root directory, i.e. 'hidden' from the internet?
Just to add to SI's information...
I also get this I get the 5096 - EOALPHABETICARABICARABICABJADARABICALPHABAHTTEXTCAPSCARDTEXTCHARFORMATCHI error when my code tries to save a MS Word document with the same name and to the same location as a Word document that is already open in another instance of Word.
Although not entirely relevant to this thread, I hope it may help someone else who stumbles upon this thread!
Regards,
Duane,
this question is old but still active ?
You save the file with a http://... url, i think you should save it with a file URL as
Document.SaveAs "\\server\savefolder\savefile.docx"
Grtz

Categories

Resources