Showing posts with label handler. Show all posts
Showing posts with label handler. Show all posts

Monday, March 26, 2012

Will Application_Error catch any unhandled exception during atlas postback ?

Looks like atlas postback unhandled exception is not comming to Application_Error handler.

Is this right ? or is there any way to redirect any atlas postback unhandled exception to "Application_Error" ?

Thanks,

Perhaps you can utilize the Error Template tag as well as OnPageError event to handle exceptions you encounter in your application.

<atlas:ScriptManager EnablePartialRendering="true"OnPageError="Page_ErrorHandler" runat="server">
<ErrorTemplate>
<div style='width: 450px; height: 300px; padding: 10px; border: solid 3px black; background: #ffd; text-align: left;'>
<h1>Server Error</h1>
<p>Oops looks like we're still working on some code. Administrators have been notified and this emerging issue will be fixed.</p>
<p><input id="okButton" type="button" value="OK" runat="server"/></p>
</div>
</ErrorTemplate>
</atlas:ScriptManager>

Here is the handler for the error.

Import System.Net.Mail

C#

protectedvoid Page_ErrorHandler(object sender, PageErrorEventArgs e)
{

MailMessage mail = new MailMessage();
mail.From = new MailAddress("me@.mycompany.com");
mail.To.Add(you@.yourcompany.com);

mail.Subject = "Error Occured My Application";
mail.Body = "Error Message: e.Error.Message<br /><br />Stack Trace: e.Error.StackTrace<br /><br />Source: e.Error.Source<br /><br />Help Link: e.Error.HelpLink";
mail.IsBodyHtml = true;
smtp.Credentials = new NetworkCredential("username", "secret");
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);

//Or perhaps insert it into a database. Or if you feel like it... perhaps the Windows Event Viewer

}

VB

SubPage_ErrorHandler (sender As Object, e As PageErrorEventArgs)

Dim mail As MailMessage = New MailMessage
mail.From = New MailAddress("me@.mycompany.com")
mail.To.Add("you@.yourcompany.com")
mail.Subject = "Error Occured My Application"
mail.Body = "Error Message: e.Error.Message<br /><br />Stack Trace: e.Error.StackTrace<br /><br />Source: e.Error.Source<br /><br />Help Link: e.Error.HelpLink"
mail.IsBodyHtml = True
smtp.Credentials = New NetworkCredential("username", "secret")
Dim smtp As SmtpClient = New SmtpClient("127.0.0.1")
smtp.Send(mail)

End Sub

You can also throw the credentials into the web.config inside the <System.Net> tag like so.

<system.net>
<mailSettings>
<smtpfrom="me@.mycompany.com">
<networkhost="127.0.0.1" port="25" userName="myUsername" password="secret" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>

Hopefully that will help a little bit.

JoeWeb


Proposed solution is great. But it requires to create Page_ErrorHandler in every Page whereScriptManager is present. It leads to duplication of code. And it very easy to miss it somewhere.

We're logging all unhandled exception in ASP.NET application onproduction environment and regulary analyze them. Errors that occur during Atlas post-back are not handled because Application_Error is not fired.

Is there any solution to exception handling during Atlas post-backs like Application_Error which is global for all application?

Thanks in advance


What about this? Implement your error handling method for the script manager event as static in a class, and onload of any page with the script manager, all you have to do is assign that static method to the event handler... then you won't be duplicating any code, and its only 1 line of code to add per page.


The ErrorTemplate is no longer supported with Ajax and these are two methods you can use..

In codebehind - I always pull in the scriptmanager so that I can ref it and manage it.

( on your page init)

SM = (ScriptManager)GetControl(skin,"SM");
SM.AsyncPostBackError +=new EventHandler<AsyncPostBackErrorEventArgs>(SM_AsyncPostBackError);

then new event...

void SM_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
SM.AsyncPostBackErrorMessage = e.Exception.Message;
bllLogging.RecordError("GridViewModal ScriptManager Error", e.Exception, Severity.Severe, "", "");
}

The BllLogging is my custom error recording routine I use to track error - replace with your own or re-throw it if you have a global exception handler...

In the example above - I use this in a base class which all of my other classes derive from so I only have to code it once...

Alternatively you can also do this on your pages or include in a mycustom.js

<ajax:ScriptManager ID="SM" EnablePartialRendering="true" ScriptMode="Auto" runat="server" />
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(OnEndRequest);

function OnEndRequest(sender,args)
{ // *** Check for errors

if (args.get_error() != undefined /* && args.get_error().httpStatusCode == '500' */)
{
//debugger;
var errorMessage = args.get_error().message
alert("Custom Error Handling:\r\n" + args.get_error().message);
args.set_errorHandled(true);
//var ErrorDisplay = $get("ErrorDisplay_Message");
//ErrorDisplay.innerHTML = "Custom Error Handling:\r\n" + args.get_error().message;
}

}
}
</script>

There also some additional things you can do with assigning custom errors and the likes and is well documented on their documentation site under scriptmanager references...

However, be careful when using the custom error feature - the code behind version does quite well logging actual messages but when in custom mode - whatever is provided as the error text is used (which hides the actual error message...)

window.onload event handler not firing on web page (AJAX BETA 2)

Any help on this one would be greatly appreciated. I'm new to Ajax and hopefully this will be a simple fix - i'm probably missing something obvious.

I have a simple website with a master page : SiteMaster.master. Inside here I've referenced the ScriptManager component
I've a simple content page which references the ScriptManagerProxy to include its own custom javascript - note no event handlers or listeners in here

The master page contains a number of controls that need to be resized immediately after the page loads and also when the page resizes

<asp:ScriptManagerID="smDefaultMaster"runat="server"EnablePartialRendering="true"ScriptMode="Release">
<Scripts>
<asp:ScriptReferencePath="~/Scripts/siteMaster.js"/>
</Scripts>
</asp:ScriptManager>


In the siteMaster.js I have 2 functions defined and I add handlers for these as per the new Sys.Dom.UI.AddHandler Methods in Beta 2. For some reason the pageLoaded event is never raised. The resize event works fine. Am i doing things correctly or am i messing something up.

function

pageLoaded () {
alert ("Load");
}

function pageLoaded () {
alert ("Resize");
}

$addHandler (window,'load', pageLoaded);
$addHandler (window,'resize', pageResized);

In the docs onthis page, you can read this:

During ordinary page processing in the browser, thewindow.onload DOM event is raised when the page loads initially. Similarly, thewindow.onunload DOM event is raised when the page is refreshed or when the user navigates away from the page.

However,these events are not raised during asynchronous postbacks. To help youmanage these types of events for asynchronous postbacks, thePageRequestManager manages a set of events that are similar towindow.load and other DOM events, but that also occur for asynchronous postbacks. For each asynchronous postback, all page events in thePageRequestManager class are raised and any attached event handlers are called.

Maybe it does help you.

Greets,
Nils Gruson

Wish: ClientSide EventHandling By Reference

Hello to all!

I have discovered that event handling in the client side is done by copying the function into the event handler list array and not by referencing it. That is very bad I think. I wish for the next release of the MS Ajax Library an event handling by reference. Below is some code to make clear, what I am meaning.

1 Type.registerNamespace('Demo');23 Demo.Class1 = function () {4this.className ='this is class one';5 _evtHandler =new Sys.EventHandlerList();6 }7 Demo.Class1.prototype = {8 addDoSomethingEventHandler: function (handler) {9 _evtHandler.addHandler('onDoSomething', handler);10 },11 removeDoSomethingEventHandler: function (handler) {12 _evtHandler.removeHandler('onDoSomething', handler);13 },14 doSomething: function () {15 alert('I am doing something.');16 var f = _evtHandler.getHandler('onDoSomething');17if(f) {18 f();19 }20 },21 dispose: function() {22 alert('I am disposing now (' +this.className +')');23 }24 }25 Demo.Class1.registerClass('Demo.Class1',null, Sys.IDisposable);2627 Demo.Class2 = function (id) {28this.className ='this is class two.';29this._id = id30 }31 Demo.Class2.prototype = {32 methodOne: function () {33 alert('ID: ' +this._id +'\nMethod One knows that something is done.');34 },35 methodTwo: function () {36 alert('ID: ' +this._id +'\nMethod Two knows that something is done.');37 },38 methodThree: function () {39 alert('ID: ' +this._id +'\nMethod Three knows that something is done.');40 },41 dispose: function () {42 alert('I am disposing now (' +this.className +')');43 }44 }45 Demo.Class2.registerClass('Demo.Class2',null, Sys.IDisposable);4647 var obj1 =new Demo.Class1();48 var obj2 =new Demo.Class2('obj2');49 var obj3 =new Demo.Class2('obj3');5051 obj1.addDoSomethingEventHandler(obj2.methodOne);52 obj1.addDoSomethingEventHandler(obj2.methodTwo);53 obj1.addDoSomethingEventHandler(obj3.methodOne);54 obj1.doSomething();55 obj2.methodOne = function () {56 alert('Someone has overwritten me.');57 };58 obj1.removeDoSomethingEventHandler(obj2.methodOne);59 obj1.doSomething();60 obj2.methodOne();61 obj3.methodThree();

First observaion is that becauseobj2.methodOne() has been over written id couldn't removed from the event handler list. The second one is that the variablesthis._id are undefined when calling the functions by raising the event. Calling the methods directly from an instance does work, see line 61.

I need some workaround to save an instance, too, not only a copy of its methods in order their instance variables are not undefined. Any Ideas are welcome.

Yavuz

First of all your code seems to be buggy.

obj1.addDoSomethingEventHandler(obj2.methodOne);

When the methodOne is invoked the this pointer will not be obj2.

Here is the fix.

var fn = Function.createDelegate(obj2, obj2.methodOne);

obj1.addDoSomethingEventHandler(fn);

Now you can remove the handler using

obj1.removeDoSomethingEventHandler(fn);

This is unaffected whether or not you set obj2.methodOne to something else.


Hello Rama!

That was not a bug. It was a question how to solve this problemSmile Thank you for your answer.

Now the function is copied into the delegate. Ifobj2.methodOne() is changed, the changed method isn't invoked. But thats another story I think. It's a situation which occurs rarely i think where you have to change a method at run-time.

I could not find a documentation about theFunction.createDelegate() method. Have I to go through the debug.js-files?

Yavuz


Looks like it has been not documented yet. The doc writers missed it. There are two function Function.createCallback and Function.createDelegate, they are widely used in ASP.NET AJAX. You can look at the source as it is easy to understand utility.

I will do it. Thank you.

Saturday, March 24, 2012

working from code behind with responsexml

I am working in the generic handler file

Can anybody help me working with responsexml

Hi,

responseXML is what you use to manipulate the response from the server on the client. It's not available on server side directly.

But you have full control on what will be returned to the client side in the ProcessRequest method. For example, the following handler returns a string "Hello World" which is the content of responseXML.

<%@. WebHandler Language="C#" Class="Handler" %
using System;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}

public bool IsReusable {
get {
return false;
}
}

}