How to catch entitydatasource exception - asp.net

I have a gridview that is bound to a entitydatasource.I've creaetd this using drag and drop from the asp.net controls in the toolbox, and using an entity data model.I have had little input in the codebehind. For testing purposes I have edited the gridview and added data that is invalid. I've then clicked update to cause an exception.
So my question is I would like to try and catch the exception in my own error handler but I don't know where or how I can do this as I'm not sure which event I should be focusing on. I would just like to know where to begin with this.
Many thanks

You can trap the exception in the OnUpdated event of the EntityDataSource:
protected void EntityDataSource1_OnUpdated(object sender, EntityDataSourceChangedEventArgs e)
{
if (e.Exception != null)
{
// handle here
e.ExceptionHandled = true;
}
}
}

you won't able to given the form was designed using drag'n drop, declarative syntax. You are better off validating the user input before submitting it to the server. This should catch most exceptions.
your other option is to replace the declarative markup with code in the code behind where you can catch exceptions or call validation prior to calling SaveChanges();

you can catch the exception in global.asax but it will show generic error.

Related

ASP.NET Session and Page Life Cycle

Let's say that in an ASP.NET .aspx page I have the Page Load method and another method for a button click event.
In the Page Load method I'm checking if the user is logged in by checking the Session. Whether he is or not, I'm storing the result in a Global Variable.
Boolean isGuest = false;
protected void Page_Load(object sender, EventArgs e) {
if(Session["id"]==null)
isGuest = true;
else
isGuest = false;
}
Let's say 20 minutes have passed, and I don't know if the Session has terminated or not, and then I click a Button, the event goes like this:
protected void Button_Click(object sender, EventArgs e) {
if(isGuest==false)
//do something
else
// do another thing
}
My Question is : When I'm clicking the button, does ASP.NET go through the Page_Load method again (check isGuest again) or it simply executes what's inside the Button_Click method, means, it uses a Boolean isGuest that could be false, but in reality the session is terminated, means it should be true.
Page_Load is triggered always before the control events.
Have a look: ASP.NET Page Life Cycle Overview
Side-note: If you want to do things only on the first load and not on every postback you have to check the IsPostBack property.
You can:
Define your own class with the UserID, and other profile properties;
Add that class to session in the global.asax session started event Session["NameReferingToYourClass"] = new YourClass();
Set a member variable to your session object early in the page life cycle mYourClass = Session["NameReferingToYourClass"] casted if you need to;
Then you can make any changes to your class anywhere in the code your member variable is available;
Save back your class with all the changes into session on the Page.Unload(..){ Session["NameReferingToYourClass"] = mYourClass.
This way you are using your class properties in your code, including UserId, pretty much like a windows application, there will be no mentioning of session anywhere else in your code.

Dynamically loaded user control not rendering

I'm trying to make a usercontrol work like a plugin: load it dynamically (using reflection) from a user's selection. After I click the button, I can see that the UI had adjusted to supposedly indicate that the user control has been loaded but I cannot the control itself. I even used viewstate but still I cannot see the control.
Please find my code below:
protected void Page_Load(object sender, EventArgs e)
{
//the scenario should be: a user clicking a button and from there,
//loads the control just below it, but still in the same page.
if (Page.IsPostBack)
LoadUserControl();
//(a)I also tried to put in a ViewState but still nothing happens.
//if (ViewState["UserControl"] != null)
//{
// UserControl uc = (UserControl)ViewState["UserControl"];
// pnlReportControl.Controls.Add(LoadControl());
//}
}
//supposedly done after a button click
private void LoadUserControl()
{
enrolmentReports = string.Concat(Server.MapPath("~"), enrolmentDll);
assembly = Assembly.LoadFrom(enrolmentReports);
Type type = assembly.GetType("TZEnrollmentReports.EnrollmentUserControl");
enrolmentMethodInfos = type.GetMethods();
//also tried this way but also didn't work
//Page.LoadControl(type, null);
UserControl uc1 = (UserControl)LoadControl(type, null);
pnlReportControl.Controls.Add(uc1);
//(a)
//ViewState["UserControl"] = uc1;
}
Please help. This is just the first step of the whole complicated process. I still have to get a dataset from that report. But I think I'm leaving that to another thread.
Thank you!
I believe that this is by design with the LoadControl(Type, Object) that it doesn't return what you are expecting.
If you change it to use LoadControl("PathOfControl") then this should work.
See this SO Q&A for more info Dynamically Loading a UserControl with LoadControl Method (Type, object[])
A suggestion that could help you solve this issue, is to change a little the approach. Usually developing a pluggable system, you base the pluggability to some interfaces. In your case, I would create an interface IPlugin that defines a method like CreateUI and some other to retrieve the data managed by the custom control internally, in some generic form.
This way, you'll delegate to the plugin implementation (your custom control) the responsability to create the UserControl properly and to return it to the caller (your page).
Once loaded the plugin implementation via reflection (something like this):
Assembly pluginDLL = Assembly.Load(System.IO.File.ReadAllBytes(fullPath));
Type pluginType = pluginDLL.GetType(step.PluginClass);
IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);
then you can load the Control on your page:
pnlReportControl.Controls.Add(plugin.CreateUI());
try replacing following code in your page_load method
if (Page.IsPostBack) LoadUserControl(); with if (!Page.IsPostBack)
LoadUserControl();

How to change the standard event handler signature of asp Updatepanel?

I always used to use standard Asp.net Controls beside AjaxControlToolkit and never faced a problem. Recently I had to use Dundas Charting controls which are not standard .NET controls and I have to control a part of apage based on the report shown in Dundas.
Unfortunately Dundas Event Signature does not recognized by UpdatePanel and Iget the following error
Description:
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.InvalidOperationException: The 'CommandFired' event on associated control 'chart1' for the trigger in UpdatePanel 'updatepanel1' does not match the standard event handler signature.
So I want to know that is there any possibility to change the Handler signature of updatepanel? If yes, How to do that?
It looks as if the CommandFiredEventArgs class does not derive from System.EventArgs which is probably the issue. Rather than try and change the signature that the UpdatePanel is expecting, I would derive a subclass from the Chart object and then add your own events, with your own EventArgs class as part of the signature. It should then be easy to hook these up to the existing Dundas events.
A very rough sample without access to VisualStudio below. This has not been compiled so please tidy it up yourself, but it outlines the general idea.
public class CustomChart : Dundas.Charting.WebControl.Chart
{
public event EventHandler<EventArgs> MyCustomEvent;
public CustomChart()
{
this.CommandFired += SomeMethod;
}
private void SomeMethod(object sender, CommandFiredEventHandler args)
{
this.OnMyCustomEvent(EventArgs.Empty);
}
protected void OnMyCustomEvent(EventArgs args)
{
if (this.MyCustomEvent != null)
{
this.MyCustomEvent(this, args);
}
}
}

Response.Redirect() ThreadAbortException Bubbling Too High Intermittently

I understand (now) that Response.Redirect() and Response.End() throw a ThreadAbortException as an expensive way of killing the current processing thread to emulate the behaviour of ASP Classic's Response.End() and Response.Redirect methods.
However.
It seems intermittently in our application that the exception bubbles too high. For example, we have a page that is called from client side javascript to return a small string to display in a page.
protected void Page_Load(object sender, EventArgs e)
{
// Work out some stuff.
Response.Write(stuff);
Response.End();
}
This generally works, but sometimes, we get the exception bubbling up to the UI layer and get part of the exception text displayed in the page.
Similarly, else where we have:
// check the login is still valid:
if(!loggedin) {
Response.Redirect("login.aspx");
}
In some cases, the user is redirected to login.aspx, in others, the user gets an ASP.NET error page and stack dump (because of how our dev servers are configured).
i.e. in some cases, response.redirect throws an exception all the way up INSTEAD of doing a redirect. Why? How do we stop this?
Have you tried overloading the default Redirect method and not ending the response?
if(!loggedin) {
Response.Redirect("login.aspx", false);
}
You can use the following best-practice code instead, as explained by this answer to prevent the exception from happening in the first place:
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
Since I was looking for an answer to this question too, I am posting what seams to me a complete solution, rounding up the two above answers:
public static void Redirect(this TemplateControl control, bool ignoreIfInvisible = true)
{
Page page = control.Page;
if (!ignoreIfInvisible || page.Visible)
{
// Sets the page for redirect, but does not abort.
page.Response.Redirect(url, false);
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline
// chain of execution and directly execute the EndRequest event.
HttpContext.Current.ApplicationInstance.CompleteRequest();
// By setting this to false, we flag that a redirect is set,
// and to not render the page contents.
page.Visible = false;
}
}
Source:
http://www.codeproject.com/Tips/561490/ASP-NET-Response-Redirect-without-ThreadAbortExcep

Page.Validate Null Reference Exception

I have a bit of a problem I was wondering if you could help me.
I have the following little bit of code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
Page.Validate("RadMaterial");
Page.Validate("TopX");
int max = 0;
if (int.TryParse(txtbxHowMany.Text, out max))
{
GridView1.DataSource = this.GetMaterialData("123456",radTopx.SelectedItem.Value, "Primary", max);
GridView1.DataBind();
}
}
I have a couple of validation groups set up the first - if the click is made and the txtbxHowMany is not populated, a simple error is shown.
I also set up a validation group for the radiobutton list so that, should the user hit submit without checking a radiobutton, the required field validation should fire.
However, it is not firing. I am getting a "NullReferenceException was handled by user code."
My thinking is that because the radTopx.SelectedItem.Value is, well, null.
How would I go about getting around this little issue of mine? Again, apologies for what is most likely a ridiculously easy question.
Interesting the way you used Validate method.
See what msdn says about it.
http://msdn.microsoft.com/en-us/library/dwzxc386.aspx

Resources