Linking a .doc file on a mvc view page - asp.net-mvc

For something which seems so simple I can't find a solution, I have a word .doc file which I want to be linked on one of my pages so that a user can click on a link and open/download it (whichever is easier) and then read it on the machine with MS word.
Right now I have it in my content folder and tried to display it in both an and but no luck.
Is this an issue of IIS or just I'm going about this all wrong?
Present dir setup:-
Solution>Project>Content>File.doc
Solution>Project>Views>Home>NewRecord.cshtml
File location 1st followed by page I'm trying to display file on.

If I understand your problem correctly that you want to make User to Click and he/she will be promoted to download the .doc then.....
You can achieve with submit button which will be styled with CSS as LINK, then you perform the HTTP GET to the server within HTML form tag, Form will target the action on Server, which will return FileContentResult,
public FileContentResult GetWordDocument(string Id)
{
var contentDisposition = new ContentDisposition
{
FileName = "WordDoc.doc",
Inline = false;
};
FileContentResult documentResult= File(secureDoc.SecuredFileBytes,"application/msword", contentDisposition.FileName);
documentResult.ExecuteResult(this.ControllerContext);
return documentResult;
}
Content-Disposition:What are the differences between "inline" and "attachment"?
http://msdn.microsoft.com/en-us/library/system.web.mvc.filecontentresult(v=vs.108).aspx
Hope this will help to resolve.

Related

Clarification on what can be exported to excel on ipad

Trying to fix an old .asp site to work on an ipad. One of the features is the users ability to download their search results into an excel worksheet. The code uses:
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment;filename=results.xls"
Response.CharSet = "iso-8859-1"
When viewing the site on the ipad, when the link is click for the page with the code above it does nothing, just spins. Is it the fact that I am trying to export the data as excel, I have read in some posts how it is the encoding! Should I convert the code to export the results page as a csv file and then allow the user to open it in anything they want/have available? What's the best way to do it to hit the most devices...
Thanks
In the past i'd a same scenario so what i did:
FILE: DOWNLOAD.ASP
<%
' get the file to download
myFile = request.querystring("File")
myFullPath = "c:\name_folder\" & myFile ' example of full path and filename
' set headers
Response.ContentType = "application/octet-stream"
Response.AddHeader "Content-Disposition", "attachment; filename=" & myFile
' send the file using the stream as
Set adoStream = CreateObject("ADODB.Stream")
adoStream.Open()
adoStream.Type = 1
adoStream.LoadFromFile(myFullPath)
Response.BinaryWrite adoStream.Read()
adoStream.Close
Set adoStream = Nothing
%>
FILE: HTML
Download Excel file
This example is full working with Ipad using the native browser Safari.
The file Result.xls is downloaded and loaded in the Viewer whitout the capability to be edit.
My iPad users use the App QuickOffice to let the file be saved in a virtual folder, rename the file, delete, ... but they cant edit the file, that App is just for manage the files and isnt required for download the file.
If your user need also edit the XLS file on the iPad i suggest to use (for example) the Google App Document, it let the user to edit and manage the file directly in the browser.
Hope it help

Can't load images from Content folder on iis in asp mvc project

In visual studio virtual server this works. But when I put site on IIS it doesn't display images from content folder.
var imgPath = '/Content/Images/Icons/' + icon + '.png';
var imageContent = '#Server.MapPath(Url.Content("-1"))';
image = imageContent.replace('-1', imgPath);
I get errors in browser foreach image
http://localhost/Content/Images/Icons/carwash.png Failed to load resource: the server responded with a status of 404 (Not Found)
First thing is first, are you sure that all of your 'icons' are part of the solution and are actually being deployed to your web server? I have had a few instances where I would add a file to the solution directory and VS does not automatically include in it the solution, thus it never actually gets deployed...
If that is ok and the images are actually there, my next question would be, have you tried just using the #Url.Content helper in your view to determine if that is working as it should?
<img src="#Url.Content("~/Content/Images/Icons/SomeIcon.png")"/>
EDIT
Since you are trying to accomplish this in Javascript and the above tag works in HTML, you should be able to condense that code up there to the following code:
var image = '#Url.Content("~/Content/Images/Icons/")' + icon + '.png';
Go ahead and let MVC get the path to the Icon folder and append your file and extension to that. This should eliminate the need for string replacement and still be able to process the icon paths in JS.
var image will now be the complete relative path to the icon file you have passed to this function. You can use this string to update and img src tag or create an image or whatever.

Save current webpage in Watin

I'm trying to save the full content of the current static web page, using the code from Show IE "Save As" dialog using Watin
So here it is:
IE ie = new IE("http://localhost");
// more code
//I expect out.html is the output file
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler("out.html");
//I expect this line to popup the save as dialog box, but nothing happens
ie.AddDialogHandler(fileDownloadHandler);
//the program is blocked at this line, as it can't click anywhere
ie.Link("startDownloadLinkId").Click();
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(15);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
I also tried the code below, but it doesn't save all the page:
System.IO.StreamWriter file = new System.IO.StreamWriter("output.html");
file.Write(ie.Html);
Again, I need to save the webpage from Watin, and the result to be the same as saving it manually.
Thanks!
Here is how I do it:
File.WriteAllText("myfile.html",
(myIE.InternetExplorer as SHDocVw.InternetExplorer).Document.documentElement.outerHtml);
Assumes myIE is a WatiN IE element, of course.
If you're ever having difficulty finding how to do something with WatiN, I often find it helpful to google how to do it with an "Internet Explorer COM object". WatiN wraps the object, but it is exposed and able to be accessed!
Cheers!
Try to parse the html with html agility pack and save it, there are additional abilities that you can use...
using HtmlAgilityPack;
var htmldoc = new HtmlDocument();
htmldoc.LoadHtml(ie.Html);
htmldoc.Save(stream);
Link to agility pack

Open XML SDK: opening a Word template and saving to a different file-name

This one very simple thing I can't find the right technique. What I want is to open a .dotx template, make some changes and save as the same name but .docx extension. I can save a WordprocessingDocument but only to the place it's loaded from. I've tried manually constructing a new document using the WordprocessingDocument with changes made but nothing's worked so far, I tried MainDocumentPart.Document.WriteTo(XmlWriter.Create(targetPath)); and just got an empty file.
What's the right way here? Is a .dotx file special at all or just another document as far as the SDK is concerned - should i simply copy the template to the destination and then open that and make changes, and save? I did have some concerns if my app is called from two clients at once, if it can open the same .dotx file twice... in this case creating a copy would be sensible anyway... but for my own curiosity I still want to know how to do "Save As".
I would suggest just using File.IO to copy the dotx file to a docx file and make your changes there, if that works for your situation. There's also a ChangeDocumentType function you'll have to call to prevent an error in the new docx file.
File.Copy(#"\path\to\template.dotx", #"\path\to\template.docx");
using(WordprocessingDocument newdoc = WordprocessingDocument.Open(#"\path\to\template.docx", true))
{
newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);
//manipulate document....
}
While M_R_H's answer is correct, there is a faster, less IO-intensive method:
Read the template or document into a MemoryStream.
Within a using statement:
open the template or document on the MemoryStream.
If you opened a template (.dotx) and you want to store it as a document (.docx), you must change the document type to WordprocessingDocumentType.Document. Otherwise, Word will complain when you try to open the document.
Manipulate your document.
Write the contents of the MemoryStream to a file.
For the first step, we can use the following method, which reads a file into a MemoryStream:
public static MemoryStream ReadAllBytesToMemoryStream(string path)
{
byte[] buffer = File.ReadAllBytes(path);
var destStream = new MemoryStream(buffer.Length);
destStream.Write(buffer, 0, buffer.Length);
destStream.Seek(0, SeekOrigin.Begin);
return destStream;
}
Then, we can use that in the following way (replicating as much of M_R_H's code as possible):
// Step #1 (note the using declaration)
using MemoryStream stream = ReadAllBytesToMemoryStream(#"\path\to\template.dotx");
// Step #2
using (WordprocessingDocument newdoc = WordprocessingDocument.Open(stream, true)
{
// You must do the following to turn a template into a document.
newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);
// Manipulate document (completely in memory now) ...
}
// Step #3
File.WriteAllBytes(#"\path\to\template.docx", stream.GetBuffer());
See this post for a comparison of methods for cloning (or duplicating) Word documents or templates.

Open pdf in browser plugin

How do I (in my controller) send a pdf that opens in the browser. I have tried this but it only downloads the file (both ie and firefox) without asking.
public ActionResult GetIt()
{
var filename = #"C:\path\to\pdf\test.pdf";
// Edit start
ControllerContext.HttpContext.Response.AddHeader("Content-Disposition", String.Format("inline;filename=\"{0}\"", "test.pdf"));
// Edit stop
return File(filename, "application/pdf", Server.HtmlEncode(filename));
}
After adding the edit above it works as it should, thanks.
You need to set the Content disposition HTTP header to inline to indicate to the browser that it should try to use a PDF plugin if it is available.
Something like: Content-Disposition: inline; filename=test.pdf
Note that you cannot force the use of the plugin, it is a decision made by the browser.
This (in addition to the other headers) does the trick for me in a plain .net web app:
Response.AddHeader("Content-Disposition", String.Format("inline;filename=""{0}""", FileName))
I'm not familiar with MVC, but hopefully this helps.
I think this relies on how the client handles PDF files. If it has setup to let Adobe Reader open the files in the browser plugin it will do that, but maybe you have set it up to download the file rather than opening it.
In any case, there is no way of controlling how PDF files will be opened on the user's machine.

Resources