Uploadify & ASP.NET Error Handling #2038 - asp.net

I'm using Uploadify within my ASP.NET 4 project. I'm using an HttpHandler to receive the posted file and process it into a directory. The upload is working fine. However, I wanted to handle any errors I could within my HttpHandler, and I am finding it impossible.
I have the processing of the file wrapped in a try catch, but I am never able to return an error message. I always receive the IO Error: Error #2038
try
{
UploadFiles(context.Request.Files);
}
catch(Exception ex)
{
context.Response.Write(ex.Message);
}
Is it not possible to return custom errors back to the client when using SWFUpload/Uploadify?

Take alook at here
uploadify error handling
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
}

Related

Retrofit: detect if web authentication needed

I'm using Retrofit (with RxJava) to download a text file.
#Streaming
#GET
Observable<ResponseBody> download(#Url String file);
Everything works fine except when user is using a public wifi that need web authentication. In this case download is still successful and what I receive is a file contains HTML of that authentication web page. How do I check and raise error in this case? I tried with Interceptor, NetworkInterceptor (Okhttp), disable redirect (Retrofit) but no luck because no exception is thrown.
Either checksum your file and check it when you get it, or check the Content-type:
#Streaming
#GET
Observable<Response<ResponseBody>> download(#Url String file);
download("http://...")
.map(response -> {
if(!"application/my-content-type".equals(
response.headers("Content-Type")) {
throw new RuntimeException("Bad download");
}
return resource.body();
})

Generic Handler Jquery Post error

I am getting this error (at the bottom) when I try to run this code using a generic handler
Jquery Code
$.post("CheckUserName.ashx?username=Aaron902",
function (result) {
$('#username_availability_result').html('Name already exist!');
if (result == "exists") {
$('#username_availability_result').html('Name already exist!');
}
else {
$('#username_availability_result').html('Still available');
}
});
Handler Code
public void ProcessRequest(HttpContext context)
{
string user_name = context.Request.QueryString["username"];
string output = "here";
output = CheckUserNameAvailability(user_name);
context.Response.Write(output);
context.Response.End();
}
Server Error in '/' Application.
Parser Error Description: An error occurred during the parsing of a
resource required to service this request. Please review the
following specific parse error details and modify your source file
appropriately.
Parser Error Message: Could not create type 'Dating.CheckUserName'.
Source Error: Line 1: <%# WebHandler Language="C#"
CodeBehind="CheckUserName.ashx.cs" class="Dating.CheckUserName" %>
Source File: /CheckUserName.ashx Line: 1
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.237
I found a fix to my issue although I am not sure why it works this way and not the original way. All I did was remove the code behind file and put all the code that was there into the ashx file instead of having it in the ashx.cs file.
Of course I removed the directive CodeBehind="CheckUserName.ashx.cs"

ASP.Net Page for file upload stops processing in middle of log statement

We have a very simple ASP.Net page for uploading a file to our webserver. The page has no controls - a client uses it to automatically send us a file each night.
On occasion, the file seems to not get to us, but the client reports that they have sent it.
We added some logging statements to the page, and discovered something quite odd. The page ceases to execute right in the middle of a log statement. No exceptions, just up and dies.
Here is the code-behind:
protected void Page_Load(object sender, EventArgs e) {
try {
// record that request came in at all
log.Debug("Update Inventory page requested through HTTP {2} on {0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), IsPostBack ? "POST" : "GET");
// make sure directory exists
string basePath = Server.MapPath("~/admin/uploads/");
log.Debug("Saving to folder {0}", basePath);
if (!Directory.Exists(basePath)) {
log.Debug("Creating folder {0}", basePath);
Directory.CreateDirectory(basePath);
}
// generate a unique file name
string fileName = DateTime.Now.Ticks.ToString() + ".dat";
string path = basePath + fileName;
log.Debug("Filename to save is {0}", fileName);
// record initial bytes of stream/file
StreamReader reader = new StreamReader(stream);
string fileContents = reader.ReadToEnd();
log.Debug("File received by GET is " + fileContents.Length + " characters long and begins with: "
+ Environment.NewLine + fileContents.Substring(0, Math.Min(fileContents.Length, 1000)));
// write out file
File.WriteAllText(path, fileContents);
log.Debug("Update Inventory page processing finished.");
// trap for and record any and all exceptions
}
catch (Exception ex) {
log.Debug(ex);
}
}
The processing seems to die in the middle of the log statement that outputs the length and first portion of the fileContents variable. The logging that occurs when the process fails looks like this:
2010-08-02 02:46:01.7342|DEBUG|UpdateInventory|Update Inventory page requested through HTTP GET on 8/2/2010 2:46:01 AM
2010-08-02 02:46:01.7655|DEBUG|UpdateInventory|Saving to folder c:\hosting\sites\musicgoround.com\wwwroot\admin\uploads\
2010-08-02 02:46:01.7811|DEBUG|UpdateInventory|Filename to save is 634163139617811250.dat
2010-08-02 02:48:02.3905|DEBUG|UpdateInventory|
I really don't understand what to make of this.
I assume if there was a error in the transmission of the file that either an exception would be thrown from the reader.ReadToEnd() line. And if not an exception, I would expect the page processing to continue but that I may only receive part of the file (in which case it should log something).
The logging statement is only accessing a string variable, and it's inside a try-catch. NLog is the logging component we use, and we access that through the facade provided by the Simple Logging Facade project on Codeplex. So, we trust the logging component to be more or less bulletproof - we certainly don't see anything in our usage of it here that should be causing problems.
So, what's the deal? Why on earth could this page just up and stop processing like this?
The fact that we get a half-finished logging statement seems to point towards an error being swallowed in the logging system - but that just seems so unlikely - and we have NLog's internal logging on and it is not reporting any problems.
The most likely candidate is that this line:
2010-08-02 02:48:02.3905|DEBUG|UpdateInventory|
Is caused by this:
log.Debug(ex);
I.e. it is throwing an exception, but the logger is not recording anything useful. Why don't you try switching about the log levels a bit, e.g. change the exception logging level to error:
log.Error(ex);
That way you can see if it is actually throwing an exception and it is just the logger not recording the exception string properly.

Getting "401 Unauthorized" error consistently with jquery call to webmethod

I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
Your insight is appreciated!
Call to js function the invokes the jquery call
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
Here are some other potentially useful tidbits that may impact your diagnosis:
Webmethods in codebehind
Using Sitecore CMS (Does not seem to intefere, never know)
IIS7
.NET 3.5
jQuery 1.3.2
I look forward to your insights and direction--thank you!
Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.
The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search
What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
Post more settings if the problem is not resolved. Hope this helps.

500 Internal Server Error when using HttpWebRequest, how can I get to the real error?

I'm trying to improve the information provided in response to an error handled within an app.
This is the code:
Try
httpRequestObj = HttpWebRequest.Create(strRequest)
httpRequestObj.Method = "GET"
httpRequestObj.UseDefaultCredentials = True
* httpResponse = httpRequestObj.GetResponse
Using reader As StreamReader = New StreamReader(httpResponse.GetResponseStream())
strXML = reader.ReadToEnd()
End Using
Catch ex As WebException
'do something with ex
End Try
The webexception is thrown on the * line
Currently all I see in the Exception is "The remote server returned an error: (500) Internal Server Error". I've looked at the exception in debug but the info I need isn't there- I guess the response would need to be read in to see that info but it never gets that far.
If I take the request and paste it into my browser directly I can see the error details in XML format that is returned from the API I'm calling, info like:
<Error>
<description>info I want to get to here</description>
<detail />
<code>info I want to get to here</code>
<source />
<category>info I want to get to here</category>
<file>info I want to get to here</file>
<line>info I want to get to here</line>
<pad />
</Error>
Is there any way I can change this code so that I can get past the 500 error and see the actual response, I'd like to be able to parse this xml to find out the real problem for the failure.
Note: the Exception does have an ex.Response (System.Net.HttpWebResponse), but I can't see the info I need in there, only a load of Header info.
You can get the error response from the exception....
try
{
....
} catch(Exception e) {
if (e is WebException && ((WebException)e).Status==WebExceptionStatus.ProtocolError)
{
WebResponse errResp = ((WebException)e).Response;
using(Stream respStream = errResp.GetResponseStream())
{
// read the error response
}
}
}
System.Net.WebResponse response = null;
try
{
response = wreq.GetResponse();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
string error = new System.IO.StreamReader(e.Response.GetResponseStream()).ReadToEnd();
}
}
catch (Exception e)
{
}
as simple as this, You will get entire response in the string error.
Try to use Fiddler. It's debuging proxy, which will show you all data sending between client and server. You'll be able to see all headers and context as well.

Resources