ASP.NET MVC Redirect to file:// - asp.net-mvc

I have string data in the form
http://site.com/location
file://server/folder/
I am showing the data as links so clicking on the link takes you to the appropriate web site or file location. Clicking on a link built from 'http://...' data works fine but I get an 'unable to display web page' message when I click on a link built from 'file://' data.
I'm building the link using Html.ActionLink, passing the data as a parameter to a HandleLink method on the controller. The HandleLink method just does Redirect(data). I know the data is coming in correctly because I can copy the incoming value in the debugger and paste in in the address bar of my browser and that works as expected.
How can I make the 'file://' links work correctly?
EDIT: I botched the first question I asked here -- I hope they have a badge for that. The 'file://...' data items are to a folder, not a specific file. Does that make any difference?

As mentioned above, you can't use file:\ to get files on a remote server however you can serve the files using something like the following:
public FileContentResult GetFile(int fileID)
{
string fileName = GetFileNameFromID(fileID); //Retruns path and filename on server
string contentType = "text/csv"; //or other appropriate type
return new FilePathResult(fileName, contentType);
}
Much more info here

Related

Web page without real files corresponding to URLs?

geniuses!
I need to make a demo page acting like DBpedia (http://dbpedia.org).
Two pages from different URLs,
http://dbpedia.org/page/Barack_Obama and
http://dbpedia.org/page/Lionel_Messi,
show different content.
I cannot really think DBpedia has million pages for all individual entities (E.g., Barack Obama and Lionel Messi).
How can I handle such URL request?
I know a bit about GET request but example URLs above do not seem like to use GET method.
Thank you in advance!
ps. Please teach me the process. Something like:
1. A user enters URL on a browser.
2. ...
When visiting http://dbpedia.org/page/Barack_Obama, your browser does send a GET request, e.g.:
GET /page/Barack_Obama HTTP/1.1
Host: dbpedia.org
The server (dbpedia.org) receives this GET request and then decides what to do. From the outside, you can’t know (for sure) how the server does something. The two common cases are:
Static web page: a file gets served that exists somewhere on the server. The URL path is often mapped to the server’s file system, but that’s not necessarily the case.
Dynamic web page: a file gets served that is generated on the fly. The content often comes from a database, but that’s not necessarily the case.
After trying some solutions, I'm now using Spring Web MVC framework.
Maybe Dynamic web page solution mentioned in unor's answer.
#Controller
public class SimpleDisplayController {
#RequestMapping("/page/{symbolicName:[!-z]+}")
public String displayEntity(HttpServletRequest hsr, Model model) {
String reqPath = (String) hsr.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String entityLb = reqPath.substring(reqPath.lastIndexOf("/"));
model.addAttribute("label", entityLb);
return "entity";
}
}
I could get request using regex as you can see at the 4th line: #RequestMapping("/page/{symbolicName:[!-z]+}").
The function above returns the string 'entity' which is the name of a HTML file serving as a template.
The following code is a body part of the example HTML template.
<body>
<p th:text="'About entity ' + ${label} + '...'" />
</body>
Since I add an attribute with the key 'label' in the controller above, the template can process ${label}.
In the example HTML template, th:text is a snytax of Thymeleaf (Java library to make an XML/XHTML/HTML5 template) which is supported by Spring.

MVC Controller.File returns blank pdf

I lost a lot of time on this issue so i will go straight to topic.
I am receiving empty pdf with correct number of (blank)pages. My action is:
public FileResult DownloadDoc()
{
//Authorization
//initialising filename
//getting content
return File(Convert.FromBase64String(content), "application/pdf", filename);
}
Content is Base64 string and it is correct. I know because when i use system.io.file.writeallbytes to make document i'm getting correct one.
I also tried to return file over Response and result is the same.
There are no (I hope) razor syntax errors.
This part of code used to work, and he stopped despite no one made no change. Maybe IIS was restarted.
If anyone can tell me what else to try ... tnx
p.s. I am looking for way without saving doc on server side.
Sorry,
an error was in javascript that saves file after returning from the server.
If you have similar issues check inner properties of the Blob object!

How to download image from url and display in view

I am trying to download an image and displaying it in a view in rails.
The reason why I want to download it is because the url contains some api-keys which I am not very fond of giving away.
The solution I have tried thus far is the following:
#Model.rb file
def getUrlMethod
someUrlToAPNGfile = "whatever.png"
file = Tempfile.new(['imageprependname', '.png'], :encoding => "ascii-8bit")
file.write(open(data).read)
return "#{Rails.application.config.action_mailer.default_url_options[:host]}#{file.path}"
end
#This seems to be downloading the image just fine. However the url that is returned does not point to a legal place
Under development I get this URL for the picture: localhost:3000/var/folders/18/94qgts592sq_yq45fnthpzxh0000gn/T/imageprependname20130827-97433-10esqxh.png
That image link does not point anywhere useful.
My theories to what might be wrong is:
The tempfile is deleted before the user can request it
The url points to the wrong place
The url is not a legal route in the routes file
A am currently not aware of any way to fix either of these. Any help?
By the way: I do not need to store the picture after I have displayed it, as it will be changing constantly from the source.
I can think of two options:
First, embed the image directly in the HTML documents, see
http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/
http://webcodertools.com/imagetobase64converter
Second, in the HTML documents, write the image tag as usual:
<img src="/remote_images/show/whatever.png" alt="whatever" />
Then you create a RemoteImages controller to process the requests for images. In the action show, the images will be downloaded and returned with send_data.
You don't have to manage temporary files with both of these options.
You can save the file anywhere in the public folder of the rails application. The right path would be something like this #{Rails.root}/public/myimages/<image_name>.png and then you can refer to it with a URL like this http://localhost:3000/myimages/<image_name>.png. Hope this will help.

Passing values from C# to VBA code?

I am pretty new to VBA, sorry if this is simple question or already answered... I tried by searching on MSDN but did not get any thing to implement this.
I am in need of sending a string (Host name in URL, e.g. xyzserver:4500/Home/GetExcelData) to VBA code before downloading the Excel to User.
I am calling MVC action method from Excel VBA code, getting some data and displaying in Excel.
My problem is Host name (xyzserver:4500) is different in different servers, I need to update the URL dynamically based on the server URL that the user is accessing from.
Basically i need to send server name to VBA code to update the URL in module. Is there any way to send and maintain values from C# (MVC Action) to VBA?
Session/ Application Cache kind of things are available in VBA?
Thanks in advance
You can pass a parameter from c# to VBA in this manner:
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook wb = app.Workbooks.Open("your file here which contains the macro");
string url = "blah blah";
app.Run("name of macro here", url);
If you want to edit the vba code programmatically, then you would need to reference the VBIDE. Have a look at Chip Pearson's excellent website: http://www.cpearson.com/Excel/vbe.aspx

Correct practices for where to put images and static files in an ASP.NET MVC application?

There is a directory in the standard ASP.NET template "Content" where most people seem to be putting in images and css files etc.
For instance stackoverflow's logo:
(source: stackoverflow.com)
actually is refered to with a server path containing 'content' in the URL (just do View Source for any SO page and you'll see this). So they obviously are storing images in "content/images/...".
src="/Content/Img/stackoverflow-logo-250.png"
Edit: Sometime in the last 10 years they changed the path - but this is what it used to be.
I dont particularly like this. My HTML ends up with /content all over it, and its slightly harder to migrate existing pages that just have /image. Fortunately my stylesheet doesnt end up with content all over it, as long as I save it in content\site.css.
An alternative is to put an images directory in the root, but then you get images at the same level as Controllers and Views which is pretty horrible.
I'd wondered about trying to add a redirection rule like this :
routes.RedirectRoute(
"images rule",
"Images/{*}",
"Content/Images/{1}"); // this is NOT valid code - I made it up
But that code doesnt work because I just made it up. I could use a third party redirection/rewriting plug-in but I want to keep everything 'pure' within the MVC model.
What has anyone else found in this area? Or is everyone just happy with an extra ("/content".length) bytes in their source for every image they serve.
To be honest, I don't think its really something to worry about... "/Content" is going to make a pretty minimal contribution to your page size. If you still want to do it, here are some options:
Option 1, if you are running on your own server, is to check out the IIS URL Rewrite module: http://learn.iis.net/page.aspx/460/using-url-rewrite-module/
Option 2 is to use either RedirectResult, or ContentResult, to achieve the same effect in the MVC framework
First, map a "catchall" route under "Images/" to a controller action, like so
routes.MapRoute("ImageContent",
"Images/{*relativePath}",
new { controller = "Content", action = "Image" })
Make sure it is above your standard "{controller}/{action}/{id}" route. Then, in ContentController (or wherever you decide to put it):
public ActionResult Image() {
string imagePath = RouteData.Values["relativePath"]
// imagePath now contains the relative path to the image!
// i.e. http://mysite.com/Images/Foo/Bar/Baz.png => imagePath = "Foo/Bar/Baz.png"
// Either Redirect, or load the file from Content/Images/{imagePath} and transmit it
}
I did a quick test, and it seemed to work. Let me know in the comments if you have any problems!
It's usually better to put images under a different sub domain. The reason for this is browsers limit the number of connections per URL. So if you use http://static.mysiste.com now the browser can open more concurrent connections due to it being in a different URL.

Resources