File Path in WebClient - asp.net

In my asp.net application, I am writing a file in code behind. I then want to use this file as below into a Handler but I get an error 'Illegal characters in Path'. I can't understand why? Help please.
The value of files in below is "306963020170816111848_Generic_P.pdf" and the file definitely exists in the correct path
WebClient client = new WebClient();
client.DownloadString(#"Handlers/MyPrintPdf.ashx?PdfFile=" + Server.MapPath("~/Templates/MyFiles/" + files)); // error here
Changed to use
HttpUtility.UrlEncode(#"Handlers/MyPrintPdf.ashx?PdfFile=" + Server.MapPath("~/Templates/MyFiles/" + files));

You should use the Uri overload of your DownloadString method. These parameters must be url encoded.
EDIT:
HttpUtility.UrlEncode(url)should also work.

Related

Cannot download with right format an excel file F#

I have the following part of code:
let client = new WebClient()
let url = "https://..."
client.DownloadFile(Url, filename)
client.Dispose()
In which code i am performing a HttpGet method in which method i get a file excel with some data.
The method is executed correctly because i get my excel file.
The problem is that the content of my file excel is like this:
I think its because i don't pass ContentType:"application/vnd.ms-excel"
So anyone can help how can I pass that ContentType in my Client in F# ?
If you want to add HTTP headers to a request made using WebClient, use the Headers property:
let client = new WebClient()
let url = "https://..."
client.Headers.Add(HttpRequestHeader.Accept, "application/vnd.ms-excel")
client.DownloadFile(Url, filename)
In your case, I think you need the Accept header (Content-Type is what the response should contain to tell you what you got).
That said, I'm not sure if this is the problem you are actually having - as noted in the comments, your screenshot shows a different file, so it is hard to tell what's wrong with the file you get from the download (maybe it's just somewhere else? or maybe the encoding is wrong?)

FileResult not returning proper file type and file name

I have an ASP.NET MVC application with an ActionResult called GenerateReport. I'm trying to return a byte array to save an Excel file. Here are snippets:
var contentType = "application/vnd.ms-excel";
var fileName = "Statistics.xlsx";
...
var fileBytes = package.GetAsByteArray();
return File(fileBytes, contentType, fileName);
When I'm prompted to save the file, it sometimes (but not always) asks what I want to do with "GenerateReport". It's naming the file the same as the ActionResult and it's not giving it a file type. I will request to save it and it will say that it failed to save. I will select Retry and it will save fine. Then, if I rename it to an .xlsx, all of the data is there and correct. I'm using IE9 and Chrome and I haven't noticed it happen in Chrome. Unfortunately, it needs to work in IE9.
Does anyone know why it's not getting my content type and file name sometimes?
Check the response for Content-Encoding. It might be the same issue like here PHP File Serving Script: Unreliable Downloads?

How to call an ASP.NET WebMethod using PowerShell?

It seems like ASP.NET WebMethods are not "web servicey" enough to work with New-WebServiceProxy. Or maybe it is, and I haven't figured out how to initialize it?
So instead, I tried doing it manually, like so:
$wc = new-object System.Net.WebClient
$wc.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$url = "http://www.domenicdenicola.com/AboutMe/SleepLog/default.aspx/GetSpans"
$postData = "{`"starting`":`"\/Date(1254121200000)\/`",`"ending`":`"\/Date(1270018800000)\/`"}"
$result = $wc.UploadString($url, $postData)
But this gives me "The remote server returned an error: (500) Internal Server Error." So I must be doing something slightly wrong.
Any ideas on how to call my PageMethod from PowerShell, and not get an error?
Try the proxy approach again if indeed your are using a WebMethod. If so, the URL resource should have the extension .asmx but your's shows that you are using a standard ASP.NET page .aspx.
A proxy simplifies the use of a WebMethod quite a bit e.g.:
C:\PS>$URI = "http://www.webservicex.net/uszip.asmx?WSDL"
C:\PS> $zip = New-WebServiceProxy -uri $URI -na WebServiceProxy -class ZipClass
What sort of error are you getting when you try to use New-WebServiceProxy?
Domenic - I am not a big PowerShell user, but the salient issue here is:
"PageMethods" are ScriptMethods and do not expose a WSDL or any other discovery vector and as such you must POST with a content-type application/json with post data urlencoded e.g. starting=[.net datetime string urlencoded]&ending=..... JSON encoding the input is incorrect.
Try using (HttpWebRequest)WebRequest.Create...... instead of WebClient, from which you would have to derive a class to enable changing the content type.
For instance, you could use something like this script and simply add a content type argument (or just hardcode it), something like this?
....
$req = [System.Net.HttpWebRequest]::Create($url);
$req.ContentType = "application/json";
$res = $req.GetResponse();
....

syntax error with RegisterClientScriptInclude in codebehind file

I have to call javascript function from javascript file codebehind .aspx page . Presently I am using this syntax which is giving me an error.
this.Page.ClientScript.RegisterClientScriptInclude
("showalert('invalidusername','password')","/Public/JS/FailLogin.js");
You're calling the right method but as Guffa says, you're passing it invalid parameters.
Try something like this instead:
this.Page.ClientScript.RegisterClientScriptInclude("myKey",
"/Public/JS/FailLogin.js");
Or if you want inline script:
this.Page.ClientScript.RegisterClientScriptBlock(GetType(),
"myKey", "alert('whatever')");
Or to pass in some more dynamic script:
string name = "Joe";
string script = "alert('Your name is" + name + "')";
this.Page.ClientScript.RegisterClientScriptBlock(GetType(),
"myKey", script);
Please note that in the last example you most JavaScript encode the value of the "name" field. Depending on the version of .NET, one way to do it is this:
string encodedName = JavaScriptSerialize.Serialize(name);
And then pass the encoded name to the "script" variable.
You can even call both methods if you want to both include a JS file as well as run some code that depends on the newly included JS file (the script include should be rendered before the script block).

how can an .ASPX page get its file system path?

I have a page something.aspx, with associated codebehind something.aspx.cs. In that codebehind, I want to know the filesystem location of something.aspx. Is there any convenient way to get it?
Update: I got several excellent answers, which unfortunately didn't work because of something else crazy I'm doing. I'm encoding some additional information on the URL I pass in, so it looks like this:
http://server/path/something.aspx/info1/info2/info3.xml
The server deals with this OK (and I'm not using querystring parameters to work around some other code that I didn't write). But when I call Server.MapPath(Request.Url.ToString()) I get an error that the full URL with the 'info' segments isn't a valid virtual path.
// File path
string absoluteSystemPath = Server.MapPath("~/relative/path.aspx");
// Directory path
string dir = System.IO.Path.GetDirectoryName(absoluteSystemPath);
// Or simply
string dir2 = Server.MapPath("~/relative");
Request.PhysicalPath
Server.MapPath is among the most used way to do it.
string physicalPath = Server.MapPath(Request.Url);
Server.MapPath( Request.AppRelativeCurrentExecutionFilePath )

Resources