Change textbox value from event handler for object in codebehind page - asp.net

I have an object, let's call it objK that has an event Message that accepts a string. I have a event handler in my code behind page called HandleObjKMessage(string s). that method looks like this currently :
void HandleObjKMessage(string s)
{
TextBox1.ReadOnly = false;
TextBox1.Text += s+ Environment.NewLine;
UpdateP.Update();
}
objK is an object from an external .dll(assembly) that is running an iterative process that I need to be keeping the user update from. That is the purpose of using an event.
Am i barking up the wrong tree? I'm typically a winforms guy and this is frustrating the hell out of me.
Thanks.

I might have misunderstood you, but you have an object that you instantiate, and then add an event handler to this object's event, and when the event fires you want the user to get the updated data?
If this is the case, it is not possible. This is simply because the web does not have state. There is no persistent connection between the server and the client.
When a request is received for your page, the server will create an instance of your page class, and run through the life-cycle (init, load etc.) Once the page has been rendered into HTML markup, the server disposes the instance of the page, and thus your attached event handler.
You can read more about the WebForms Page Lifecycle at MSDN
If you really want to go all the way and actually push the notification to your user, you could use SignalR, but this adds quite some complexity.

Related

what is the main point to enter in asp.net?

Like in java the entry point is public static void main(String[] args). What is the entry point in ASP.NET using C#? Usually, I see the page load method, is that the entrance point?
Does asp.net follows some different criteria?
You need to take a look at the ASP.NET life-cycle:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
There is no "main point" in asp.net. What you would think of as "main" in asp.net is code that's already written for you. Instead, you inherit a base class ("Page"). As part of this, you can (but don't have to) implement several event handlers. Through the process of building a page, Asp.Net will raise these events for you to handle. The process of running through these events in order is called the page lifecycle.
For your case, there are several options depending on what you want the main method to do:
Handle the Application_Start event in the Global.asax file
The Page_PreInit event (the very first event in the page life cycle)
The Page_Load event (the most common event handled in the page life cycle)
You said something wrong.
public static void main() is a Java method too, used as entry point for console applications the exact way C# does.
You might want to compare servlets/JSP and ASP.NET, don't you?
Servlets vs IHttpHandler
They are, conceptually, the same thing. They are also both interfaces. Their configuration is different (WEB.xml VS Web.config or .ashx file), but their entry points are "almost" the same.
Servlet:
Init()
Service()
Destroy()
IHttphandler:
ProcessRequest() <<--- does all the things
IsReusable {get;} <<--- optional
JSP vs ASP.NET pages
If you define a constructor, or override the InitializeFramework() method, then you have a starting point (or, at least, a breakpoint to put at the almost-very-beginning of the execution), but not an entry point.
Page class implements IHttpHandler, if you allow me some Java syntax in .NET world, but you don't see anything. You might want to go deeper into page life cycle as linked by other users. Basically explaining, Page encapsulates its complete life cycle in events, that resemble clock ticks when you work with VHDL components.
Execution is not concurrent as it seems, but since you can't know the exact order in which controls will raise the same event, you can go as the VHDL example in which you can't read the value of a registry before the next clock tick.
There are several events: here are the most important in their execution order
Init: page is initialized, GET, POST and cookie data are available. If you override, then you should initialize your webapp context (ie setup db connections)
Load (PreLoad and LoadComplete too): page loads the UI data and restores, if needs to, the state of controls displayed on the page. If you set up DB connections in init, you shouldn't use them before PreLoad to be sure you don't get an exception. The same applies to sequence PreLoad->Load->LoadComplete.
DataBind: data-bound controls load data from database, file or whatever (ie. tables get the data to display)
Validation: if you use validators, their business logic is processed to determine whether the page is valid or not. No further explaining here
Postback processing: if you click a button, then its server-side code is executed
PreRender (and PreRenderComplete): the page is getting ready for being rendered into HTML. Usually stores internal data into a collection named ViewState which I won't explain any further here. Usually you would finalize some data-related operations and/or decide whether to render or not some controls on the page according to the page's state. For example, if you have a CAPTCHA and the user solved the puzzle, you won't render it again
Render: not actually a programmatic event, but the page gets rendered to HTML
Dispose: resources get freed, as occurs with Destroy in Java

In ASP.Net, How do I run code after sending page

In ASP.Net, I want to run some code (logging, other cleanup) after the page has already been sent to the user. I don't want this code to interfere with the amount of time it takes the client to receive a response. I tried placing this code in the OnUnload part of the page, but through testing (using breakpoints, or busy waiting loops) the client does not actually display the page until the code in the OnUnload is finished executing. Even though the response object is no longer available at this point, and therefore I would assume that the buffered response has been sent to the client, the client still does not display the page until the OnUnload is finished executing. The only way that seems to work at the moment is to start a new thread to do the work, and allow the OnUnload to finish immediately. However, I don't know if this is safe or not. Will the server kill the thread if it executes too long after the page is already sent out? Is there a more correct way to accomplish this?
Kibbee,
Try overriding the Page.Render method and flushing the response like so:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.Render(writer)
Response.Flush() ' Sends all buffered output to the client
' Run some code after user gets their content
End Sub
I think at this point the response still isn't complete, but the user will get what the page has rendered before you finish running that final code.
HTH,
Mike
Unload is the last part of the ASP.NET page life cycle. See link below:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Is this something you could do with javascript or AJAX?
How about hooking into the page.Disposed event instead of the Unload event?
Depending on what you need to do an ISAPI filter can be created to do stuff at the end of the response.
You could try this solution - Best ASP.NET Background Service Implementation
Using a windows service and communicating with it through MSMQ might be a far more reliable solution and can scale up better. This will help you separate the concerns and let asp.net front end just focus on the user while the windows service focusses on the background tasks.
If you are moving to the cloud with azure, you can simply replace the asp.net front end with a web role and the windows service with a worker role and ur solution can scale seamlessly!
Here's a redneck way to do it. Have a second aspx page that does all your "clean up" post-rendering logic. Call that one 'cleanup.aspx' for example. Have your clean up code run in Page_Load of cleanup.aspx:
public partial class cleanup: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// do logging blah blah here....
}
}
In your main aspx page, have a JavaScript function that makes an AJAX call to 'cleanup.aspx'. Make the AJAX function fire after page load. I recommend jquery, if so your code will look like this:
$(function(){
yourAJAXYFunctionName();
});
function yourAJAXYFunctionName()() {
// ajax code here
//
$.ajax({
url: "cleanup.aspx",
});
}
This way, your first page's code runs, then the page is sent to the browser. As the page renders to the client, the 2nd ASPX page is called via AJAX, which really doesn't matter to cleanup.aspx, it doesn't care how its called and its page load event is executed. Your cleanup/logging code is then ran.
Caveats: client side JavaScript is required. But really who the hell doesn't have JS running anyway? Also, your cleanup.aspx page is totally abstracted from your main page, so if you want to use any object in cleanup.aspx that originated in your first page, then you'll have to store them in session or cookies, or you can pass them as parameters in the AJAX call. That will require dynamic manipulation of the AJAX script itself, but that's not too hard.
Better i think try try{Response.End()}catch{} runcode();

Javascript window.onunload fires off after Page_Load

I have noticed that window.onunload event fires off AFTER page_load event which makes no sense.
This behaviour is creating an issue for me - in my unonload I clear the session, so if the Page_Load first BEFORE onunload, there are errors on the page displayed.
I would expect the javascript onunload to fire BEFORE Page_Load....is that the correct assumption?
TO CLARIFY:
Let's assume I am on page test.aspx, then I click on the link that goes to the same page (say I click on a menu), what I observe is that Page_Load fires first, then onunload fires off.
Makes no sense at all.
It's a browser-specific behaviour. Chrome and FF will send a GET requst BEFORE onunload is fired, IE8 will execute onunload first. Not sure, how the other browser handle it. Better not rely on this functionality.
Have you considered using a common base class for your pages, and clearing the session in there if the request isn't a postback (I assume that you're using session for postbacks)?
public class BasePage : System.Web.UI.WebControls.Page {
protected override OnPreInit (EventArgs e) {
// Get in nice and early, however you could use OnInit if you prefer
if (!Page.IsPostBack) {
Session.Clear();
}
}
Then your pages that need to clear session can be declared as:
public class SpecialPage : BasePage {
// Your page logic goes here.
// Note that if you need to do work in OnPreInit here you should call
// base.OnPreInit(e) first.
}
I would guess that window.unload is actually firing only when you're going to have to RENDER the new page you navigated to (aka the old DOM is being torn down in place of some new HTML). The browser doesn't know what to render until the response comes back from the server with the HTML to display. That HTML isn't generated until the page lifecycle completes, which includes Page_Load. Hence the page_load before the window.unload?
In any case, if you can clear the session during window.unload, why not just clear it in response to some user interaction and be a bit more explicit about it?
Edit: Could you also try window.onbeforeunload?
The onunload event does fire before the request for the new page is fired off to the server, so it definitely fires before the Page_Load method runs on the server.
The problem is most likely that you are sending another request to the server from the onunload event. As the IIS only handles one request at a time from each user, this request will be queued and executed after the request for the new page.
You can write an utility function which will handle removing of the session variables and then call that function in the respective menu click events. That should be simpler to use since window unload will fire after page load only.
It sounds like you are using the Session to save temporary variables that change from page to page. I would say the Session is not really suitable for this kind of scenario. A better solution would be to use the Httpcontext's Item collection which is scoped only on a per request basis. It's works just the same as the Session when storing data.
Context.Items["myvariable"] = "some data";
As it's only scoped on a per request basis, there is no need to use javascript to clear the items you have stored on each page request.

Why does Application_BeginRequest() fire twice when refreshing browser?

I'm observing some really confusing behavior with the Application_BeginRequest event in my Global.asax file (in an ASP.NET MVC app). When running through the debugger, if I Refresh my browser (IE7), this event fires twice. If I click a link or otherwise manually request a page, it fires once - as expected.
Why does a refresh cause BeginRequest to fire twice?
I'm observing this with a brand new MVC project with the following addeded to Global.asax.cs
protected void Application_BeginRequest() {
//executed twice
}
For context, I'm trying to add a new object to the HttpContext.Current.Items collection during this event, so it will persist through the entire request process. Obviously, I don't want this to happen twice for a single refreshed request!
Are you sure it's really 2 request to the same URL? I would think that the second is probably some dynamic JS, CSS or image file. Try to find out either with Fiddler or by looking at HttpContext.Current.Request.Uri in the debugger
Something that surprised me a while back was that if you have an img tag in your html that doesn't have a proper image path, some browsers will make a request to the original page. Here is a related blog post.
I'm not sure why this is occuring but I find it's easier to create a BaseController class and have all my controllers inherit from it. Alter the constructor to add your item to the HttpContext.
Do you have a reference in your HTML to something that also passes the ASP.NET pipeline, like a dynamically generated image or something like that?

Do I need to unsubscribe from (manually subscribed to) events in asp.net?

Do the same best practis rules regarding subscribing/unsubscribing to events apply in asp.net?
I know it might seem like a silly question, but when I think about it, I have never really seen any code where people first subscribe to an event on a page and then unsubscribe later on in the web request.
Example 1:
On a page, in the Page_Load method, I subscribe to a updating event on a ListView. Should I unsubscribe from that event later on, for example in the OnPreRenderComplete method?
Example 2:
In the passive view patter, a view (Page control/Usercontrol) will raise an event whenever it needs the presenter to do anything. So the presenter needs to subscribe to events on the view, but do it also need to unsubscribe from the events again?
Best regards, Egil.
The page instance and all of its components will "go out of scope" when request completes, e.g. they become eligible for GC. So your ListView will go out of scope along with the Page/user controls on it. You don't need to unsubscribe (unless you subscribe to an event that belongs to some kind of singleton that survives every request and use one of the methods of the page as the event handler, for example).
The same thing is valid for the presenter (again as long as this presenter is used solely with one page and goes out of scope after that).
Generally, no. Events are supposed to be dumped automatically when the page unloads. SUPPOSED to be. I've run into a bug before (in .NET 1.1) where that wasn't the case.
I won't bother unsubscribing, unless I notice a problem with the page (like, a method being called 20 times from a phantom in the call stack: that's usually a sign of something not being unsubscribed properly).

Resources