An unhandled exception of type 'System.InvalidOperationException' occurred when I want to display database data in listbox through a backgroundworker
Here is the code:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private List<Product> products;
private void LstProduct_loaded(object sender, RoutedEventArgs e)
{
BackgroundWorker Worker = new BackgroundWorker();
Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
Worker.DoWork += new DoWorkEventHandler(worker_DoWork);
Worker.RunWorkerAsync();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
products = App.StoreDb.GetProducts();
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
LoadingGrid.Visibility = Visibility.Collapsed;
Lstproducts.ItemsSource = products;
}
}
Try using
private void LstProduct_loaded(object sender, RoutedEventArgs e)
{
//create thread
ThreadStart myThreadStart = new ThreadStart(MyThreadRoutine);
Thread myThread = new Thread(myThreadStart);
myThread.ApartmentState = ApartmentState.STA;
myThread.Start();
}
//function
private void MyThreadRoutine()
{
this.Invoke((MethodInvoker)delegate {
products = App.StoreDb.GetProducts();
this.LoadingGrid.Visibility = Visibility.Collapsed;
this.Lstproducts.ItemsSource = products;
});
}
Related
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.
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.
When is the earliest point in which I can access HttpContext.User?
You could use the AuthenticateRequest event of the HttpApplication. Here is some sample code:
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.AuthenticateRequest += context_AuthenticateRequest;
}
void context_AuthenticateRequest(object sender, EventArgs e)
{
var application = (HttpApplication) sender;
var name = application.Context.User.Identity.Name;
}
public void Dispose()
{
}
}