This code is giving an error 'Object reference not set to an instance of an object'.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
_Default obj = new _Default();
Thread thread = new Thread(new ThreadStart(obj.ThreadStart));
thread.Start();
}
public void ThreadStart()
{
show();
}
private void show()
{
lblget.Text = "hi";
}
No need to create an instance of _Default.
protected void Page_Load(object sender, EventArgs e)
{
Thread thread = new Thread(show);
thread.Start();
}
private void show()
{
lblget.Text = "hi";
}
Read these article - Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code and PageAsyncTask.
Related
I am working on an application that was built out over a long time by copying and pasting code into individual pages that makes more sense as a user control.. I think.
Basically it allows the page to load/save/reset to defaults some page specific settings, so each page has code behind defines its own functions to handle those events.
I'm trying to build a user control that allows the page to pass in the handlers to the user control but haven't figured out how to do that successfully. I'm trying to just pass the functions that are already being used.
New User Control
public partial class uc_SaveCriteriaControl : System.Web.UI.UserControl
{
public Action SelectedCriteriaChanged { get; set; }
public Action ResetFunction { get; set; }
public Action SaveFunction { get; set; }
protected void SelectionUpdated(object sender, EventArgs e)
{
SelectedCriteriaChanged();
}
protected void Reset(object sender, EventArgs e)
{
ResetFunction();
}
protected void Save(object sender, EventArgs e)
{
SaveFunction();
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
Attempt to use it
<uc3:CriteriaControl runat="server" SaveFunction="imgbtnSaveParam1_Click" ResetFunction="imgbtnResetParams_Click" SelectedCriteriaChanged="MyParams_SelectedIndexChanged" />
This is what an existing button looks like
<asp:Button CssClass="btn h-100" ID="imgbtnSaveParams" runat="server" OnClick="imgbtnSaveParam1_Click" Text="Save Criteria" Width="100%" />
It does't like passing the function name, which makes sense, but I'm not sure how you would do this.
Cannot create an object of type 'System.Action' from its string
representation 'imgbtnSaveParam1_Click' for the 'SaveFunction'
property.
Seems like I might need to use event handlers like so.
public partial class uc_SaveCriteriaControl : System.Web.UI.UserControl
{
public delegate void ResetHandler(object sender, EventArgs data);
public event ResetHandler ResetButtonClicked;
public delegate void SaveHandler(object sender, EventArgs data);
public event SaveHandler SaveButtonClicked;
public delegate void SelectionUpdatedHandler(object sender, EventArgs data);
public event SelectionUpdatedHandler SelectionIsUpdated;
protected void SelectionUpdated(object sender, EventArgs e)
{
if (SelectionIsUpdated != null)
SelectionIsUpdated(this, e);
}
protected void Reset(object sender, EventArgs e)
{
if (ResetButtonClicked != null)
ResetButtonClicked(this, e);
}
protected void Save(object sender, EventArgs e)
{
if (SaveButtonClicked != null)
SaveButtonClicked(this, e);
}
protected void Page_Load(object sender, EventArgs e)
{
}
And in the parent
criteriaControl.SaveButtonClicked += imgbtnSaveParam1_Click;
criteriaControl.ResetButtonClicked += imgbtnResetParams_Click;
criteriaControl.SelectionIsUpdated += MyParams_SelectedIndexChanged;
We have an HttpModule that is designed to catch exceptions and log them to the db. It looks something like this:
public class ExceptionLoggingModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.Error += OnError;
}
private static void OnError(object sender, EventArgs e)
{
try
{
var context = (HttpApplication) sender;
var exception = context.Server.GetLastError();
if (exception != null)
{
// Log exception
}
}
catch(Exception)
{
}
}
}
This works in general, but I've just noticed that the OnError method never fires when an error occurs within Page Methods (i.e. methods in a code behind file marked with the WebMethod attribute).
How come?
Is there something I can do about this, other than reimplementing the exception logging inside the Page Method itself?
I found a solution that worked for me here:
http://blogs.microsoft.co.il/blogs/oshvartz/archive/2008/05/17/asp-net-error-handling-using-httpmodule-full-and-partial-post-back-ajax-updatepanel.aspx
Here's the key points of the handler I've written:
public class PathfinderModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PostMapRequestHandler += this.OnPostMapRequestHandler;
context.Error += OnError;
}
private void OnPostMapRequestHandler(object sender, EventArgs e)
{
Page aux = HttpContext.Current.Handler as Page;
if (aux != null)
{
aux.Error += this.OnPageError;
}
}
private static void OnError(object sender, EventArgs e)
{
// Blah..
}
private void OnPageError(object sender, EventArgs e)
{
// Blah...
}
}
When I run my method in global.asax it doesn't run and when I use IHttp module it is working. Please give any advice.
Maybe it is caused of :
context.PostRequestHandlerExecute += new EventHandler(Application_EndRequest);
Is it possible to call it without Module?
Code Example:
Method that I run:
public static void EndSession()
{
HttpContext context = HttpContext.Current;
if (context.Session != null)
{
ISession session = context.Session["Session"] as ISession;
if (context.Session["Session"] != null)
{
if (!session.Transaction.IsActive)
OpenTransaction(session);
session.Flush();
CommitTransaction(session);
session.Close();
context.Session["Session"] = null;
}
}
}
Global:
private void Application_EndRequest(object sender, EventArgs e)
{
NhSessionHelper.EndSession();
}
IHTTPMODULE:
namespace MME.DAL.SesionManager
{
internal class SessionRequest : IHttpModule
{
#region Public Methods
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PostRequestHandlerExecute += new EventHandler(Application_EndRequest);
}
#endregion
#region Private Methods
private void Application_EndRequest(object sender, EventArgs e)
{
NhSessionHelper.EndSession();
}
#endregion
}
}
Ok I understand now PostRequestHandlerExecute fires page finishes execution so the name of
private void Application_EndRequest(object sender, EventArgs e)
was little confusing and that is why there was a problem.
I got this code which extends the tablerow to make them clickable.
namespace ClickableTableRow
{
public class ClickableTableRow : TableRow, IPostBackEventHandler
{
public ClickableTableRow()
: base()
{ }
private EventHandler _click;
public event EventHandler Click
{
add { _click += value; }
remove { _click -= value; }
}
protected virtual void FireClickEvent()
{
if (_click != null)
_click(this, new EventArgs());
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Onclick,
Page.ClientScript.GetPostBackEventReference(this, String.Empty));
base.RenderAttributes(writer);
}
public void RaisePostBackEvent(string eventArgument)
{
FireClickEvent();
}
}
The code above works well if I create the table manually, but when i create the table in the code behind it seems to be firing postbacks but no resuts returned. is there any thing wrong i might doing. my codebehind looks like:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void row1_Click(object sender, EventArgs e)
{
Messagebox.Text = "message";
}
ClickableTableRow.ClickableTableRow row1;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Table Table1 = new Table();
TableCell cell1 = new TableCell();
row1= new ClickableTableRow.ClickableTableRow();
row1.Attributes.Add("onmouseover", "this.style.cursor='hand'");
cell1 = new TableCell();
cell1.Text = "llllll";
row1.Cells.Add(cell1);
Table1.Rows.Add(row1);
row1.Click += new EventHandler(row1_Click);
this.pnl2.Controls.Add(Table1);
}
}
Try moving this code to Init or PreInit. This is the typical part in the lifecycle where dynamic controls should be added.
We can programatically add HttpModules using DynamicModuleUtility.RegisterModule(typeof (SomeHttpModule)) - is there a way to remove them?
Instantiate the HTTP Module in Init method in Global.asax
Call Module.Init() as described here
In Init method of your module, hook required eventhandlers.
Override the Dispose method in the handler and unhook the
eventhandlers.
Expose the instance as public property on global.asax so that you
can call Dispose when you want to unregister the module
// Global.asax
public IHttpModule MyModuleInstance { get; private set; }
public override void Init()
{
base.Init();
MyModuleInstance = new MyModule();
MyModuleInstance.Init(this);
}
// MyModule.cs
public void Dispose()
{
_context.BeginRequest -= context_BeginRequest;
}
public void Init(HttpApplication context)
{
_context = context;
context.BeginRequest += context_BeginRequest;
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
app.Context.Response.Write("Hello from OnBeginRequest in custom module.<br>");
}
// TO unregister
protected void Button1_Click(object sender, EventArgs e)
{
this.ApplicationInstance.MyModuleInstance.Dispose();
}