Opening FileTable Files in c# / .net 4 - asp.net

I have a Filetable containing many different document types (.doc;.pdf;.xls etc).
I am writing a small web (C# / .net 4) search app. Search works great using fulltext index with filetable to find content.
But I'm struggling to find a way in my app to have the search results as links which can launch the document in question? And just handle the different file types? (Assume client has Word/adobe/excel installed etc)
Grateful for any advice.

You will need to write a custom page handler to stream the bytes to the client with the proper HTTP headers. You will need to decide whether to support inline viewing (open in the browser - Content-Disposition: inline) versus external viewing using an attachment (e.g. Content-Disposition: attachment).
Response.AddHeader("Content-Disposition", "attachment; filename=example.pdf");
If you are using ASP.NET MVC - you can leverage the FileResult to streamline this process, but creating your own handler wouldn't be too much different.
public FileResult Download()
{
byte[] fileBytes = ...; // from FileTable
string fileName = "example.txt";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
The best approach to handling various MIME types (PDF, DOC, XLS) is to statically define the supported file types or dynamically read IIS and assign the appropriate Content-Type HTTP header.
Response.ContentType = "application/pdf";

Related

Asp.Net 6.0 Redirect user to a URL containing json content and start download

I have a scenario where the user passes a fileName to download.
We don't download the file on the server and stream back to the user because of bandwidth restrictions
We get the file path to download, and redirect to the location where the json file would be hosted
[Route("[controller]/DownloadJsonFile")]
public async Task DownloadJsonFile(string fileName)
{
//Get the file name
string fileToDownload = "https://hostedfilelocation/....test.json"
Response.Redirect(fileToDownload);
}
Currently, this method ends up rendering the Json content on the browser.
Is there a way so that the browser can start automatically downloading the file?
That way it wouldn't take super long to render the file on the browser.
P.S. If the file is of type zip or gzip, it is not rendered on the browser but rather is automatically downloaded.
The application is a .Net 6 Asp.Net MVC application
I have tried the below code but the behavior is the same but it renders json on the browser instead of downloading it.
string fileToDownload = "https://hostedfilelocation/....test.json"
HttpResponse response = HttpContext.Response;
response.Clear();
response.ContentType = "application/octet-stream";
response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
Response.Redirect(fileToDownload);
The approaches mentioned in this blog post are all mentioning rendering the file in an iframe but I want the download happen on the client side.
Download File via browser redirect
If you want to download it directly, add the download attribute:
<a class='download-file-link' target='_blank' href='DownloadJsonFile' download="somefilename">

.Net 5 Custom Response Cache

Our old .Net framework APIs utilized the Strathweb.CacheOutput.WebApi2 which took care of server-side caching and set the appropriate client side headers in order to implement a form of output caching.
In that scheme, during project startup the following was injected to create a cache key. There is more custom code for our implementation that is appended to the key but this is enough to start the conversation. This method used the RedisOutputCache.
public class CacheKeyWithHeadersGenerator : DefaultCacheKeyGenerator
{
public override string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType,
bool excludeQueryString = false)
{
const string itemSeparator = "-";
const string paramSeparator = "=";
var cacheKey = base.MakeCacheKey(context, mediaType, excludeQueryString);
var requestHeader = context.Request.GetHeaders();
cacheKey += $"{itemSeparator}isdr{paramSeparator}{requestHeader.IsDR}";
Similar functionality is needed as we migrate to .Net 5, but I would like to know my options as there does not appear to be much in that covers this. In order for this to work, the rule that the presence of an Authorization header must be overridden.
Can anyone point me in the right direction? Should I be using Distributed Caching instead?
Edit 1
This question may be a bit hard to understand. I am attempting to cache at the client side using a custom cache key to contain the userid and other information contained in the Authorization header (as Strathweb did) in .Net 5 web api. In other words, data would be both client cached and server cached by utilizing a custom cache key in addition to what is sent via the query.

Avoiding Protected view when opening streamed Excel documents

We have an ASP.NET application which dynamically generates Excel documents and streams them to the client, using Response.WriteFile, see code below. Note that the document is deleted once the file has been written to the client. Thus, no documents are ever left on the server.
However, my client's users has now all upgraded to Office 2010, and now the documents will open in "Protected View". In order to edit the document, the user has to click "Enable editing" first. This is considered unacceptable for the users.
The reason that this happens is that streamed documents are placed in the Temporary Internet files, and this is considered a "potentially unsafe location". And documents in such locations are opened in protected view. I am just hoping there is some way to work around this.
Theoretically, I could place the document in a folder which is accessible from the client, and redirect to the document.
This solution is not an option, however. Firstly, since the document would be left on the server, it could be accessible for other users, which is a problem since the documents may contain confidential data.
There are other reasons why this is not a vialable option.
An other theoretical workaround would be to ask all users to disable the setting "Enable protected view for files located in potentially unsafe locations". Naturally, this is not an option either.
So, in short, is there anyway to avoid the documents to be opened in "Protected view" while using the streaming technique described below?
Response.Buffer = true;
Response.Clear();
Response.AddHeader("Pragma", "no-cache");
Response.Expires = 0;
Response.AddHeader("Content-Type", contentType);
Response.AddHeader("Content-Disposition", "attachment; filename=" + proposedFilename);
Response.WriteFile(dstFullPathName);
Response.Flush();
Response.Close();
File.Delete(dstFullPathName);
HttpContext.Current.ApplicationInstance.CompleteRequest();

receive xml file as a parameter to a .net web service

My company is currently looking into bringing a new piece of third party software in for online ordering. The software does not handle pricing so they are requesting the pricing information from a web service. Their software is passing an XML file as a parameter, and expecting an XML file as a response. I would think that returning an XML file would be pretty straight forward, but I cannot think of a way to receive an XML file as a parameter. Has anyone done this, or am I missing something really obvious?
Possibly obvious - an XML "file" can be represented by a String.
Edit to Answer Comment
The string is the XML file, so all you need to do is deserialize it into the classes created from the XSD:
Dim xmlString As String = GetStringFromVendor()
Dim xmlClass As New CoolXMLClass
Dim serializer As New Xml.Serialization.XmlSerializer(GetType(CoolXMLClass))
xmlClass = serializer.Deserialize(New StringReader(xmlString))

Posting base64 encoded files to an asp.net 1.1 page

We are making an automated patching application and would like to post files on production server through asp.net page (or maybe a web service), since we can only access production server via http. The page should accept files and store them to appropriate location. The path to files will be declared in external XML file.
So, is it possible posting a base64 encoded files within body tag and HOW? maybe even any better approach?
If you plan to use Base64 encoding.
Take a look at
System.Convert.ToBase64String()
System.Convert.FromBase64String()
System.Convert.ToBase64CharArray()
System.Convert.FromBase64CharArray()
See Using XML CDATA nodes to send files via a Web Service
why not create a webservice which accepts an object like:
class postfile
{
public byte[] fileByte;
public string fileName;
}
Then add a web reference in your client app.
.net will serialize the object for you.
You will need to secure this using wse security and might require the service use impersonation to write the file on the server.

Resources