Upload file with meta data and checkin to sharpoint folder using Client Object Model - sharepoint-2010

Hi I'm trying to upload a file to sharepoint 2010 using the client api with meta data and also checkin the file after I'm done. Below is my code:
public void UploadDocument(SharePointFolder folder, String filename, Boolean overwrite)
{
var fileInfo = new FileInfo(filename);
var targetLocation = String.Format("{0}{1}{2}", folder.ServerRelativeUrl,
Path.AltDirectorySeparatorChar, fileInfo.Name);
using (var fs = new FileStream(filename, FileMode.Open))
{
SPFile.SaveBinaryDirect(mClientContext, targetLocation, fs, overwrite);
}
// doesn't work
SPFile newFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();
//check out to make sure not to create multiple versions
newFile.CheckOut();
// use OverwriteCheckIn type to make sure not to create multiple versions
newFile.CheckIn("test", CheckinType.OverwriteCheckIn);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();
//SPFile uploadFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
//uploadFile.CheckOut();
//uploadFile.CheckIn("SOME VERSION COMMENT I'D LIKE TO ADD", CheckinType.OverwriteCheckIn);
//mClientContext.ExecuteQuery();
}
I'm able to upload the file but I can't add any meta data and file is checked out. I want to add some meta data and checkin the file after I'm done.
My SharePointFolder class has the serverRelativeUrl of the folder path to upload to. Any help greatly appreciated.

You need a credential before the executeQuery(); and SaveBinaryDirect();
For example:
mClientContext.Credentials = new NetworkCredential("LoginID","LoginPW", "LoginDomain");
SPFile newFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();

Related

Where is the file path of IFormFile?

When I receive a file from C# to iformfile, how do I know the file path of that file?
If I don't know, how do I set the path?
public async Task<JObject> files(IFormFile files){
string filePath = "";
var fileStream = System.IO.File.OpenRead(filePath)
}
In this document, some instructions on IFormFile are introduced:
Files uploaded using the IFormFile technique are buffered in memory or on disk on the server before processing. Inside the action method, the IFormFile contents are accessible as a Stream.
So for IFormFile, you need to save it locally before using the local path.
For example:
// Uses Path.GetTempFileName to return a full path for a file, including the file name.
var filePath = Path.GetTempFileName();
using (var stream = System.IO.File.Create(filePath))
{
// The formFile is the method parameter which type is IFormFile
// Saves the files to the local file system using a file name generated by the app.
await formFile.CopyToAsync(stream);
}
After this, you can get the local file path, namely filePath.

Rename azure blob file and Download it

I have few files in azure blobs that are stored with unique file names and when the client wants to download, i want to rename to a friendly name.
I'm still using 2014 azure storage dlls in my project and i'm not planning to update them anytime soon. So i can't use built-in ContentDeposition and rename it.
I tried using following code in my controller:
var blob = blobStorage.GetBlobRef("https://mysite.blob.core.windows.net/my-container/WERF3234435FFF_ERFas23E.doc");
MemoryStream memStream = new MemoryStream();
blob.DownloadToStream(memStream);
Response.ContentType = blob.Properties.ContentType;
Response.AddHeader("Content-Disposition", "Attachment; filename=abcd_New.doc");
Response.AddHeader("Content-Length", blob.Properties.Length.ToString());
Response.BinaryWrite(memStream.ToArray());
but its not downloading the file.
I also tried using this:
MemoryStream memStream = new MemoryStream();
blob.DownloadToStream(memStream);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = blob.Properties.ContentType;
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename=" + friendlyName.doc);
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", blob.Properties.Length.ToString());
System.Web.HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
System.Web.HttpContext.Current.Response.End();
I have my business logic in a separate solution and getting the blob reference from there to my main solution.
Am i missing something?
When we're talking about ASP.NET MVC, I'm missing the Controller/Action in your code? You're not supposed to write to the HttpContext yourself when doing ASP.NET MVC. You have ActionResults for that.
public ActionResult Download()
{
// ...
var bytes = memStream.ToArray();
return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "abcd_New.doc");
}
The browser will decide whether to open the file download or open it directly within the browser window. If you want to control that, you will need the following piece of code before you call the return File(... method:
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = "abcd_New.doc",
Inline = false // true will try to open in Browser, false will download
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
We need to flush our response after wrote a file to response. I use the code which you provided. After adding following code, I can see the file can be download from server.
Response.BinaryWrite(memStream.ToArray());
Response.Flush();
Response.End();

Stream pdfs from url and add it to Zip

I have a mvc 4.5 application where I show a grid. The first column of the grid is a document name. The document name is an hyper link to the actual document that is hosted on our site and is available via a url. The documents can be pdf or doc or ppt. I can access these documents only via url and I do not have access to the actual physical document on our server.
I am providing users an option to select one or many of these documents from the grid and then they can download them. What I am trying to achieve is read each of the selected documents via the url and write it to a zip file and make the zip file downloadable. So users will be downloading one file instead of multiple files.
I have tried to stream the documents via url in memory and then add it to the zip file using ZipArchive Library from Microsoft. This is not working for me.
I was able to add documents that was on disk to zip file using Zip Archive and it works great. But I do not have access to the physical document as I can access the documents only through URL. My next option is to download each of these documents into a temp location on server and then add it to zip file using Zip Archive.But I am trying to avoid downloading files into a temp location
Please suggest how I can achieve reading documents via url in memory and adding each of these document to zip file and make zip file downloadable.
Any help will be appreciated.
Thank you Cbroe for commenting. I figured the answer. The problem was I was reading the pdf from the url and convert it to a memory stream and then was trying to add the memory stream to ZipArchive which was not working but instead I extracted the byte array out of the memory stream and then added it to the zip archive and it worked.
Here is the code snippet that might be useful for some one. My first contribution to Stack OverFlow.
public FileResult DownloadZip()
{
MemoryStream memoryStream = new MemoryStream();
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var demoFile = archive.CreateEntry("Pdf123.pdf");
var convertedStream = ConvertTobyte("http://www.example.com/Pdf123.pdf");
using (var entryStream = demoFile.Open())
{
entryStream.Write(convertedStream, 0, convertedStream.Length);
}
demoFile = archive.CreateEntry("Pdf456.pdf");
convertedStream = ConvertTobyte("http://www.example.com/Pdf456.pdf");
using (var entryStream = demoFile.Open())
{
entryStream.Write(convertedStream, 0, convertedStream.Length);
}
}
//This option is to write the zip to your local disk
using (var fileStream = new FileStream(#"C:\Temp\test.zip", FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
//This option is to donload the zip via browser
memoryStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(memoryStream, "application/zip")
{
FileDownloadName = "Archive.zip"
};
}
private static byte[] ConvertTobyte(string fileUrl)
{
byte[] imageData = null;
using (var wc = new System.Net.WebClient())
imageData = wc.DownloadData(fileUrl);
return imageData;
}

How do I open a file when clicking an ActionLink?

How do I open an existing file on the server when a user clicks an actionlink? The following code works for downloading a file but I want to open a new browser window, or tab, and display the file contents.
public ActionResult Download()
{
return File(#"~\Files\output.txt", "application/text", "blahblahblah.txt");
}
You must add "inline" for a new tab.
byte[] fileBytes = System.IO.File.ReadAllBytes(contentDetailInfo.ContentFilePath);
Response.AppendHeader("Content-Disposition", "inline; filename=" + contentDetailInfo.ContentFileName);
return File(fileBytes, contentDetailInfo.ContentFileMimeType);
The way you're using the File() method is to specify a file name in the third argument, which results in a content-disposition header being sent to the client. This header is what tells a web browser that the response is a file to be saved (and suggests a name to save it). A browser can override this behavior, but that's not controllable from the server.
One thing you can try is to not specify a file name:
return File(#"~\Files\output.txt", "application/text");
The response is still a file, and ultimately it's still up to the browser what to do with it. (Again, not controllable from the server.) Technically there's no such thing as a "file" in HTTP, it's just headers and content in the response. By omitting a suggested file name, the framework in this case may omit the content-disposition header, which is your desired outcome. It's worth testing the result in your browser to see if the header is actually omitted.
Use a target of blank on your link to open it in a new window or tab:
Download File
However, forcing the browser to display the contents is out of your control, as it entirely depends on how the user has configured their browser to deal with files that are application/text.
If you are dealing with text, you can create a view and populate the text on that view, which is then returned to the user as a regular HTML page.
please try this and replace your controller name and action name in html action link
public ActionResult ShowFileInNewTab()
{
using (var client = new WebClient()) //this is to open new webclient with specifice file
{
var buffer = client.DownloadData("~\Files\output.txt");
return File(buffer, "application/text");
}
}
OR
public ActionResult ShowFileInNewTab()
{
var buffer = "~\Files\output.txt"; //bytes form this
return File(buffer, "application/text");
}
this is action link which show in new blank tab
<%=Html.ActionLink("Open File in New Tab", "ShowFileInNewTab","ControllerName", new { target = "_blank" })%>
I canĀ“t vote your answered as is useful, follow dow. Thanks very much !
public FileResult Downloads(string file)
{
string diretorio = Server.MapPath("~/Docs");
var ext = ".pdf";
file = file + extensao;
var arquivo = Path.Combine(diretorio, file);
var contentType = "application/pdf";
using (var client = new WebClient())
{
var buffer = client.DownloadData(arquivo);
return File(buffer, contentType);
}
}

How to Read a pre-built Text File in a Windows Phone Application

I've been trying to read a pre-built file with Car Maintenance tips, there's one in each line of my "Tips.txt" file. I've tried to follow around 4 or 5 different approaches but It's not working, it compiles but I get an exception. Here's what I've got:
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader sr = new StreamReader(store.OpenFile("Tips.txt", FileMode.Open, FileAccess.Read)))
{
string line;
while ((line = sr.ReadLine()) != null)
{
(App.Current as App).MyTips.Insert(new DoubleNode(line));
}
}
}
I'm getting this "Operation not permitted on IsolatedStorageFileStream", from the info inside the 2nd using statement. I tried with the build action of my "Tips.txt" set to resource, and content, yet I get the same result.
Thanks in advance.
Since you've added it to your project directory, you can't read it using Isolated Storage methods. There are various ways you can load the file. One way would be to set the text file's build type to Resource, then read it in as a stream:
//Replace 'MyProject' with the name of your XAP/Project
Stream txtStream = Application.GetResourceStream(new Uri("/MyProject;component/myTextFile.txt",
UriKind.Relative)).Stream;
using(StreamReader sr = new StreamReader(txtStream))
{
//your code
}