473,405 Members | 2,167 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Binding behaviour regarding exceptions

Is there any way to enable exception throws in VS 2005, that occur during
binding operations?

I am upset that i can't see exceptions that are thrown during binding
operations. It's very hard to track down erroneous behaviour of your app if
you can't see where the problem is... i mean it's realy hard to debug
binding issues and it would be realy of help if i could somehow enable this
during debug session.

Sep 19 '06 #1
6 2423
Try catching the BindingComplete event for a Binding, where
e.BindingCompleteState== BindingCompleteState.Exception and look at
e.Exception.

You should be able to walk the Controls and their Bindings to attach the
handler globally; you can also subclass Binding and do it that way (I think
there is a virtual OnBindingComplete method) - but this won't catch those
added with DataBindings.Add("Text",obj,"Property"), since it will create a
vanilla Binding instance.

Any use?

Marc
Sep 19 '06 #2
Hi Mikus,

Internally, the Binding class will handle the bound control's Validate
event:

private void Target_Validate(object sender, CancelEventArgs e)
{
try
{
if (this.PullData(true))
{
e.Cancel = true;
}
}
catch
{
e.Cancel = true;
}
}

That's why the exception is eaten silently.

To catch the exception during debugging, I recommend first use your custom
exception class to throw:

public class MyValidateException : Exception
{ }

public int Currency
{
get { return _currency; }
set
{
if (value == 2)
{
throw new MyValidateException();
}
...

Then in Visual Studio IDE, open menu "Debug/Exception...", click button
"Add...", select type "Common Language Runtime Exceptions", input your
exception class's full name (including namespace) in the field "Name". When
added, make sure it's checked in the "Thrown" column.

This way, the exception will be caught everytime it's thrown regardless
there're try/catch handler or not.

By the way, although the exception is not displayed during debugging, the
output window of IDE should log the exception such as:

A first chance exception of type
'control_bind_not_refresh_display.MyValidateExcept ion' occurred in
control_bind_not_refresh_display.exe
A first chance exception of type
'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type
'control_bind_not_refresh_display.MyValidateExcept ion' occurred in
System.dll
A first chance exception of type
'control_bind_not_refresh_display.MyValidateExcept ion' occurred in
System.Windows.Forms.dll

Though it lacks of information such as exception location.

Sincerely,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Sep 20 '06 #3
Hi!
Thanks for information. This is new for me, but it does not help because I
would like to see all exceptions like NoReferenceFoundException,
DivideByZeroException and so on!

We have a bunch of properties and it would be insane to write try catch
blocks for all of them.
"Walter Wang [MSFT]" <wa****@online.microsoft.comwrote in message
news:de****************@TK2MSFTNGXA01.phx.gbl...
Hi Mikus,

Internally, the Binding class will handle the bound control's Validate
event:

private void Target_Validate(object sender, CancelEventArgs e)
{
try
{
if (this.PullData(true))
{
e.Cancel = true;
}
}
catch
{
e.Cancel = true;
}
}

That's why the exception is eaten silently.

To catch the exception during debugging, I recommend first use your custom
exception class to throw:

public class MyValidateException : Exception
{ }

public int Currency
{
get { return _currency; }
set
{
if (value == 2)
{
throw new MyValidateException();
}
...

Then in Visual Studio IDE, open menu "Debug/Exception...", click button
"Add...", select type "Common Language Runtime Exceptions", input your
exception class's full name (including namespace) in the field "Name".
When
added, make sure it's checked in the "Thrown" column.

This way, the exception will be caught everytime it's thrown regardless
there're try/catch handler or not.

By the way, although the exception is not displayed during debugging, the
output window of IDE should log the exception such as:

A first chance exception of type
'control_bind_not_refresh_display.MyValidateExcept ion' occurred in
control_bind_not_refresh_display.exe
A first chance exception of type
'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type
'control_bind_not_refresh_display.MyValidateExcept ion' occurred in
System.dll
A first chance exception of type
'control_bind_not_refresh_display.MyValidateExcept ion' occurred in
System.Windows.Forms.dll

Though it lacks of information such as exception location.

Sincerely,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your
reply
promptly.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no
rights.


Sep 22 '06 #4
Then perhaps the following?

Most binding operations will consider ICustomTypeDescriptor; if you
implement this interface on your object (or better, a base object), and
forward most of the calls to TypeDescriptor, except for GetProperties; in
this one you could call TypeDescriptor.GetProperties using "this" as the
component, but wrap each returned property in a bespoke PropertyDescriptor
that forwards all calls to the existing (reflective) descriptor, but adds
exception handling to the GetValue and SetValue members.

It sounds complex, but I have code that will do most of this if you want;
I'm not going to put forward an example unless you are interested, though.

Let me know,

Marc
Sep 22 '06 #5
I got bored... here you go... add code to "TODO":

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;

namespace WindowsApplication2 {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(fals e);
List<SomeClasslist = new List<SomeClass>();
list.Add(new SomeClass());
list.Add(new SomeClass());
list.Add(new SomeClass());
using (Form f = new Form())
using (DataGridView dgv = new DataGridView()) {
dgv.Dock = DockStyle.Fill;
f.Controls.Add(dgv);
dgv.DataSource = list;
Application.Run(f);
}
}
}
public class SomeClass : ICustomTypeDescriptor {
private string name = "";
public string Name {
get { return name; }
set {
if (value == "Fred") throw new InvalidOperationException();
name = value; }
}
private int number;
public int Number {
get { return number; }
set { number = value; }
}

AttributeCollection ICustomTypeDescriptor.GetAttributes() {
return TypeDescriptor.GetAttributes(GetType());
}
string ICustomTypeDescriptor.GetClassName() {
return TypeDescriptor.GetClassName(GetType());
}
string ICustomTypeDescriptor.GetComponentName() {
return TypeDescriptor.GetComponentName(GetType());
}
TypeConverter ICustomTypeDescriptor.GetConverter() {
return TypeDescriptor.GetConverter(GetType());
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() {
return TypeDescriptor.GetDefaultEvent(GetType());
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() {
return TypeDescriptor.GetDefaultProperty(GetType());
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType) {
return TypeDescriptor.GetEditor(GetType(), editorBaseType);
}
EventDescriptorCollection
ICustomTypeDescriptor.GetEvents(Attribute[] attributes) {
return TypeDescriptor.GetEvents(GetType(), attributes);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents() {
return TypeDescriptor.GetEvents(GetType());
}
PropertyDescriptorCollection
ICustomTypeDescriptor.GetProperties(Attribute[] attributes) {
return WrapProps(TypeDescriptor.GetProperties(GetType(),
attributes));
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() {
return WrapProps(TypeDescriptor.GetProperties(GetType())) ;
}
private PropertyDescriptorCollection
WrapProps(PropertyDescriptorCollection props) {
PropertyDescriptor[] newProps = new
PropertyDescriptor[props.Count];
int i = 0;
foreach(PropertyDescriptor prop in props) {
newProps[i++] = new ErrorLoggingPropertyDescriptor(prop);
}
return new PropertyDescriptorCollection(newProps, true);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDes criptor pd)
{
return this;
}
}
public class ErrorLoggingPropertyDescriptor :
ForwardingPropertyDescriptor {
public ErrorLoggingPropertyDescriptor(PropertyDescriptor root) :
base(root){}
public override object GetValue(object component) {
try {
return base.GetValue(component);
} catch (Exception ex) {
// TODO: do something with ex
throw;
}
}
public override void SetValue(object component, object value) {
try {
base.SetValue(component, value);
} catch (Exception ex) {
// TODO: do something with ex
throw;
}
}

}
public abstract class ForwardingPropertyDescriptor : PropertyDescriptor
{
private readonly PropertyDescriptor _root;
protected PropertyDescriptor Root { get { return _root; } }
protected ForwardingPropertyDescriptor(PropertyDescriptor root)
: base(root) {
_root = root;
}
public override void AddValueChanged(object component, EventHandler
handler) {
Root.AddValueChanged(component, handler);
}
public override AttributeCollection Attributes {
get {
return Root.Attributes;
}
}
public override bool CanResetValue(object component) {
return Root.CanResetValue(component);
}
public override string Category {
get {
return Root.Category;
}
}
public override Type ComponentType {
get { return Root.ComponentType; }
}
public override TypeConverter Converter {
get {
return Root.Converter;
}
}
public override string Description {
get {
return Root.Description;
}
}
public override bool DesignTimeOnly {
get {
return Root.DesignTimeOnly;
}
}
public override string DisplayName {
get {
return Root.DisplayName;
}
}
public override bool Equals(object obj) {
return Root.Equals(obj);
}
public override PropertyDescriptorCollection
GetChildProperties(object instance, Attribute[] filter) {
return Root.GetChildProperties(instance, filter);
}
public override object GetEditor(Type editorBaseType) {
return Root.GetEditor(editorBaseType);
}
public override int GetHashCode() {
return Root.GetHashCode();
}
public override object GetValue(object component) {
return Root.GetValue(component);
}
public override bool IsBrowsable {
get {
return Root.IsBrowsable;
}
}
public override bool IsLocalizable {
get {
return Root.IsLocalizable;
}
}
public override bool IsReadOnly {
get { return Root.IsReadOnly; }
}
public override string Name {
get {
return Root.Name;
}
}
public override Type PropertyType {
get { return Root.PropertyType; }
}
public override void RemoveValueChanged(object component,
EventHandler handler) {
Root.RemoveValueChanged(component, handler);
}
public override void ResetValue(object component) {
Root.ResetValue(component);
}
public override void SetValue(object component, object value) {
Root.SetValue(component, value);
}
public override bool ShouldSerializeValue(object component) {
return Root.ShouldSerializeValue(component);
}
public override bool SupportsChangeEvents {
get {
return Root.SupportsChangeEvents;
}
}
public override string ToString() {
return Root.ToString();
}
}
}
Sep 22 '06 #6
Hi Mikus,

I've done more research on this issue and found more information to share
with you.

From document of Binding.FormattingEnabled [4]:

Setting this property to true also enables error-handling behavior and
causes the BindingComplete event to be raised. The handler of this event
can take the appropriate action, based on the success, error, or exceptions
in the binding process, by examining the BindingCompleteState property of
the BindingCompleteEventArgs parameter.

So we need to follow Marc's suggestion in his first reply:

private void class1BindingSource_BindingComplete(object sender,
BindingCompleteEventArgs e)
{
if (e.BindingCompleteState == BindingCompleteState.Exception)
{
MessageBox.Show(e.Exception.Message );
}
}

But this need the FormattingEnabled property of the Binding class set to
true. If it's false, the exception will just get consumed by the Binding
class and never has a chance to report back.

However, this requirement conflicts with the other issue you've mentioned
in [1]; which is also reported as a known bug [2]. So my workaround in that
post is not completely working: it will cause this issue you're
experiencing. I must apologize for the confusion I've caused.

So, I think we will just make sure the FormattingEnabled property set to
true as the designer generated code did that for us. We will need find
another workaround to deal with the bug mentioned in [1] and [2].

We can use following workaround instead:

In the business object's PropertyChanged event, we can flip the
FormattingEnabled property of the Binding to make it reflect the changed
property value back to the source:

Class c1 = new Class1();
c1.PropertyChanged += new
PropertyChangedEventHandler(c1_PropertyChanged);

...

void c1_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
foreach (Binding b in textBox1.DataBindings)
{
if (b.IsBinding && b.BindingMemberInfo.BindingMember ==
e.PropertyName)
{
b.FormattingEnabled = !b.FormattingEnabled;
b.FormattingEnabled = !b.FormattingEnabled;
}
}

// you may need to handle other controls' DataBindings too
}

Please let me know what do you think of above workaround. Thanks.

References:

[1] #Control bind to object does not refresh it's display in
dotnet.languages.csharp
http://msdn.microsoft.com/newsgroups...icrosoft.publi
c.dotnet.languages.csharp&tid=31384fbc-a888-4286-b6c9-c3be53e77e5e&m=1&p=1

[2] #Feedback: Current control doesn't refresh values due to
PropertyChanged event
http://connect.microsoft.com/VisualS...k.aspx?Feedbac
kID=115342

[3] #Binding behaviour regarding exceptions in dotnet.languages.csharp
http://msdn.microsoft.com/newsgroups...icrosoft.publi
c.dotnet.languages.csharp&mid=72e21545-078c-4676-96aa-46c481827590&sloc=en-u
s&m=1

[4] #Binding.FormattingEnabled Property (System.Windows.Forms)
http://msdn2.microsoft.com/en-us/lib...binding.format
tingenabled.aspx

Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 25 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Bengt Richter | last post by:
;-) We have @deco def foo(): pass as sugar (unless there's an uncaught exception in the decorator) for def foo(): pass foo = deco(foo) The binding of a class name is similar, and class...
4
by: Vinay | last post by:
Hello My question is regarding "weak external symbols". Consider the following eg. class test { public : int func1(void); {cout <<"func1";} int func2(void);
2
by: Paul Drummond | last post by:
Hi all, I am developing software for Linux Redhat9 and I have noticed some very strange behaviour when throwing exceptions within a shared library. All our exceptions are derived from...
9
by: Zlatko Matić | last post by:
I was reading about late binding, but I'm not completely sure what is to be done in order to adjust code to late binding... For example, I'm not sure if this is correct: early binding: Dim ws...
3
by: Julia | last post by:
Thanks for all you responses assuming I have a collection of objects which I want to save in a database I wonder if the following is the way to deal with a situation that only some of the...
1
by: Chris | last post by:
Hi, a strange behaviour when working with exceptions : when I divide and integer by 0 will an exception be thrown. OK but, when I divide a double by 0 is no exception thrown ??? How come ? ...
0
by: JSantora | last post by:
Essentially, InsertAT is broken! For the past couple of hours, I've been getting this "Parameter name: '-2147483550' is not a valid value for 'index'." error. Apparently, its caused by having...
30
by: lgbjr | last post by:
hi All, I've decided to use Options Strict ON in one of my apps and now I'm trying to fix a late binding issue. I have 5 integer arrays: dim IA1(500), IA2(500), IA3(500), IA4(500), IA5(500) as...
19
by: Larry Lard | last post by:
In the old days (VB3 era), there was a thing called the Data Control, and you could use it to databind controls on forms to datasources, and so (as the marketing speak goes), 'create database...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.