|
Hi Dave,
I beg to differ on this one, I would put as much code in a try block as logic dictates.
If my method needs 100 simple steps without any side-effects, and I don't care where
it fails, I'll put them all in a single try.
The net result would be either success, or failure in which case the details
of the failure are (should be) apparent from the exception, and probably the catch
block would contain code to throw an application-specific new exception (and store the
original as an inner exception).
If on the other hand, the steps have lots of side-effects (allocating resources,
opening files, etc) I would use more try/catch/finally blocks, even nested, to
handle this elegantly.
But I would avoid the fully sequential try one step, catch, try next step, ... approach
since then there could well be more error handling code than straight code, yielding lower
programmer efficiency, more code and more execution paths to test.
I do stress the use of line numbers while debugging though, a simple technique a lot
of people seem unfamiliar with (the fact that the Visual Editor by default does not
show them looks like a mistake to me).
Regards,
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Luc Pattyn wrote: I beg to differ on this one, I would put as much code in a try block as logic dictates.
If my method needs 100 simple steps without any side-effects, and I don't care where
it fails, I'll put them all in a single try.
True. I guess I tailored my answer to his case. If he can't find where the offending code is, that's a sign he's got too much in the Try block.
I try to keepo me Try's as small as possible, but it, agreeably, depends on the situation.
Luc Pattyn wrote: But I would avoid the fully sequential try one step, catch, try next step, ... approach
since then there could well be more error handling code than straight code, yielding lower
programmer efficiency, more code and more execution paths to test.
I think I should clarify that I'm not saying he should break each tiny step into it's own Try/Catch. I am saying that it should be closer to wrapping each step that makes up a transaction.
For instance, depending on the situation and granularity of the error handling in the requirements, wrapping creating and opening a connection object and running a query and returning a result set is probably going to be more "friendly" than wrapping each step in that same code. If you're going after a generic DAL library that executes arbitrary SQL on a database, then you might want to wrap each of those steps. It just depends on the flexibility or importance of the transaction in question.
Some transactions are tolerant of a single item failure and continue on. Others need to know so they can stop at a certain point. And still others need to backout in the event of a certain set of failures, but can continue on in the event of a smaller failure.
I've probably done a piss-poor job of explaining this. I apologize in advance. It's late in the day and I'm starting to fall asl.....
|
|
|
|
|
Dave Kreskowiak wrote: I've probably done a piss-poor job of explaining this
If so, you have amply rectified it.
Dave Kreskowiak wrote: It's late in the day
That's all relative.
Gnite.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Very good points there, Luc.
"The clue train passed his station without stopping." - John Simmons / outlaw programmer
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
|
|
|
|
|
Does an exception give any information more specific than the method in which it occurs and the exception type and message? If you have a long method it is sometimes hard to see where the error is.
Thanks!
|
|
|
|
|
Hi,
an Exception holds a lot of information:
- the Message (a one-line string)
- extra information (such as the file path on a file I/O error)
- the Stack TraceBack containing a list of methods, with line numbers when available
- and the same for any inner exception.
To get it all you need to use ToString(). Just looking at Message won't help much.
To locate the problem line, use a debug build and look at the very first line number
that appears in the stack traceback.
BTW: you can teach Visual to always show line numbers in the editor, see Tools/Options/
TextEditor/...
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Thanks Luc!!... might I ask another question of you?... what's the best way to capture the exception within the entire project? I have specific try..catches, but I don't want to make a separate one for each method.
|
|
|
|
|
I'm not seeing line numbers in the stacktrace. How can I be sure I'm compiling in debug mode?
Thanks
|
|
|
|
|
cstrader232 wrote: How can I be sure I'm compiling in debug mode?
Not sure for VB.NET, I do most stuff in C#, where the Build menu offers a Configuration
item, letting you choose between Debug and Release.
I expect the Debug menu is visible only while building for and running with debug.
I recall having had some trouble with C++ and/or VB.NET to get it the way I wanted,
but currently my VB.NET (VS2005 Express) is running debug, and showing line numbers
in exceptions (only on user code, the .NET libraries don't show line numbers here).
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Hi,
proper exception handling is a rather complex matter. I'll try and give some of the
basics here:
1.
you should not catch an exception and then ignore it, since that would destroy useful
information, needed to remedy an exceptional situation; every exception should either
be solved (e.g. an alternative way gets attempted), or the problem should be
signalled to the caller (through a "result" return value, a new exception, or by
not catching it in the first place).
2.
normally you should catch an exception where you are able to deal with it,
and that often is pretty close to where it happens.
Example: if you have a mathematical algorithm and suddenly get a divide-by-zero,
it does not make sense to have that catched several method levels above it, since
at that level the caller would not be aware of the algorithm, what a zero-divide
would be, and how it should be remedied. Instead, you should catch it locally, and
try to organize things such that the method fails gracefully.
3.
it is often wise to include a specification on exceptions when specifying a
method or a library; exception handling is a basic part of the contract.
(Java enforces this, .NET does not; there are pros and cons tho).
4.
It does not hurt to have a top-level try-catch (that's in the static main method itself);
it should NEVER fire in production code, it's main purpose is to help the developer notice
all the exceptions that are lacking a local try-catch.
If it fires in production code, it halts the app, which never looks good; but it should
show all available info (hence ToString), and urge the user to send that to the developer.
5.
not all exceptions are easily noticed and dealth with; there are special measures to
deal with exceptions in constructors, in background threads, in remote objects,
in native code, etc.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Thanks Luc, Thanks Dave!
That's very helpful. I'm at the point where I need to move my app from few tryblocks to a whole lot of them. I can see that that is going to be good in the end.
Honestly, I'm not sure where the "static main method" is:
Luc Pattyn wrote: It does not hurt to have a top-level try-catch (that's in the static main method itself);
Happy weekend!
chuck
|
|
|
|
|
Sorry, "static main" is a C# notion. You may have a "sub main" in a VB module,
or you just have a main form somewhere. I'm not that familiar with VB...
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
OK, that's all making sense and I found some line numbers! So thanks again!
|
|
|
|
|
Luc Pattyn wrote: Example: if you have a mathematical algorithm and suddenly get a divide-by-zero,
it does not make sense to have that catched several method levels above it, since
at that level the caller would not be aware of the algorithm, what a zero-divide
would be, and how it should be remedied. Instead, you should catch it locally, and
try to organize things such that the method fails gracefully.
If I'm trying to do something like plot a graph of a user-specified function, what would be the preferred try/catch methodology for the expression evaluation? I know that one isn't supposed to use try/catch to just ignore errors, but if I get a divide-by-zero, domain error, or other such problem do I really care why the evaluation failed? I should regard the function value at that point as undefined (meaning that the points before and after should probably not be connected) but other than that I don't see much that a try/catch block could usefully do.
Ideally, one could divide exceptions from such a routine into three classes:
- Those whose failure should simply cause a particular value not to be plotted.
- Those whose failure should cause the remainder of the plotting to be skipped, since remaining points won't work any better.
- Those which should send an exception to outer functions, since something very bad is happening (heap management failure, etc.)
From a practical standpoint, though, I don't see any clean way to accomplish that if the function to be plotted will be supplied by the user. Unless the called function has defined explicit exception types for 'failure that's going to occur on all points' versus 'failure that may just occur on one point', I see no way for the outer function to know what to make of any inner exceptions.
|
|
|
|
|
Hi,
this is how I see it:
your plot class should define a number of exceptions for the cases 1 and 2 you listed;
that's the conditions that have a functional significance to the plot itself.
these exceptions become part of the contract between the user-defined function and the plot class.
your plot method should react appropriately to these exceptions; and it should also protect
itself against spurious exceptions, i.e. anything else the function might (but really
shouldn't) throw; these include your third group. Probably the protection would just entail
catching everything, and encapsulating it into a single PlotException, of course with the original exception as an inner one.
on the other hand the user-supplied function should contain its own exception handling,
it should catch things such as overflow, zero divide, etc. and either return whatever value
it considers appropriate, or (better) throw one of the exceptions your plot method has defined.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
My VS2003 web application written in VB.NET works as required on my XP Pro desktop platform using .Net Framework 1.1, IIS 6.0 a local MSDE database. It uses System.Web.Mail to send emails via my ISP's web server which requires authentication. Everything works fine. Emails are sent ok.
However, when I migrate the application to my separate web server (Windows Server 2003, .Net Framework 1.1, IIS 6.0 ) and my separate database server (Windows Server 2000, SQL Server) the emails are not sent and I get the message "The transport failed to connect to the server."
Could this be a configuration issue with my web server? Or could it be the SMTP access coded in VB is missing something that is defaulted to on my desktop platform?
My VB code is as follows:-
Dim strBody As String
Dim msgEmail As MailMessage = New MailMessage
' provide external mail server with authentication for outgoing mail
Dim strUserName As String = "myname@MyEmail.com"
Dim strPassword As String = "MyPassword"
Dim intCdoBasic As Integer = 1
msgEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", intCdoBasic)
msgEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", strUserName)
msgEmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", strPassword)
msgEmail.Subject = "My Subject: "
msgEmail.BodyFormat = MailFormat.Html
msgEmail.Body = BuildBody() 'build html and copy to body
msgEmail.To = "TargetName@TargetDomain.com"
msgEmail.Priority = MailPriority.High
msgEmail.From = “SourceName@Domain.com”
SmtpMail.SmtpServer = "mail.MyISP.com" 'as provided by ISP
System.Web.Mail.SmtpMail.Send(msgEmail)
I get the following error stack:-
Server Error in '/' Application.
--------------------------------------------------------------------------------
The transport failed to connect to the server.
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.Runtime.InteropServices.COMException: The transport failed to connect to the server.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[COMException (0x80040213): The transport failed to connect to the server.
]
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) +0
System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) +473
System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) +58
[HttpException (0x80004005): Could not access 'CDO.Message' object.]
System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) +113
System.Web.Mail.CdoSysHelper.Send(MailMessage message) +1848
System.Web.Mail.SmtpMail.Send(MailMessage message) +150
OMOT_booking.SubmitRequest.SendPayReq(String strIref)
OMOT_booking.SubmitRequest.btnNext_Click(Object sender, EventArgs e)
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +108
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +138
System.Web.UI.Page.ProcessRequestMain() +1292
modified on Friday, February 15, 2008 11:06 AM
|
|
|
|
|
There's probably nothing wrong with the code. The problem is probably being caused by your ISP or a firewall in the way between where your code is running and the SMTP server.
Most ISP's won't let you send an email using their servers if the request comes from outside their network. This means that your code would work perfrectly from home, but once you move the code to a hosting facility outside your ISP's network, you can no longer get at their SMTP servers. There is no way around this problem. You'll have to use a different SMTP server.
Check for firewall's blocking traffic on both the inbound and outbound sides of the network connection between your hosting server and your ISP's SMTP server. Make sure the appropriate ports are opened on both sides.
Also, make sure that your ISP's DNS name for the SMTP server is resolvable by the server hosting your app. If it's not, there's nothing you can do about it, other than using a different SMTP server.
|
|
|
|
|
Thanks for your comments Dave. I will bear them in mind as I do plan to migrate my application to a web hosting ISP and I had not anticipated any problem calling my existing ISP's SMTP server.
However, my immediate problems concern my home network only. I have both an XP Pro development platform AND a home network that includes a web server box and a database server box.
I have investigated the differences in configuration and noticed that my desktop's IIS has a "Default SMTP Virtual Server" directory whilst that on my Win 2003 server does not. So I have concluded that the email service (IIS optional feature) on my Win Server 2003 box has has not been installed yet. I assume this service must be installed to provide a "virtual SMTP" server to communicate with my ISP's SMTP server. So, I am installing the IIS email service but it is taking forever.
Do you think this will fix my problem?
|
|
|
|
|
Stortman wrote: I have investigated the differences in configuration and noticed that my desktop's IIS has a "Default SMTP Virtual Server" directory whilst that on my Win 2003 server does not. So I have concluded that the email service (IIS optional feature) on my Win Server 2003 box has has not been installed yet. I assume this service must be installed to provide a "virtual SMTP" server to communicate with my ISP's SMTP server. So, I am installing the IIS email service but it is taking forever.
Do you think this will fix my problem?
Maybe, but not likely, because you're not using your local SMTP server at all. Also, most ISP's won't forward mail from unauthorized SMTP servers (like yours) anyway because of the proliferation of spam.
You MAY get the benefit of having libraries installed that may solve your problem, but I doubt it.
|
|
|
|
|
I have now successfully installed the optional email service that was not included when I originally installed the web server (IIS 6.0) on my Win 2003 server box.
I have also checked out my hardware firewall NAT settings (Draytek Vigor) and opened port 25 for the server box's IP address.
Now, when I test across the public internet, the web application's email feature works correctly.
The email feature accesses the remote SMTP server that my ISP (web site hosting company) operates. This SMTP server requires authorisation (registered email address and password) for all outgoing mail but I can use any sender email address I like.
So problem is fixed for the moment anyway. Thanks for your advice.
|
|
|
|
|
I also found I had to use the construct
SmtpMail.SmtpServer.Insert(0, "mail.MyISP.com")
and not
SmtpMail.SmtpServer = "mail.MyISP.com"
to get the Win 2003 box to work properly.
|
|
|
|
|
Plz how can u open a vs2005 project in vs2008 without converting?
when u convert, does it mean ur project is now .Net framework 3.5?
i have an application in .net 2.0 with vs2005 and i just got vs2008 and have installed and want to use it but want my existing projects to remain .Net 2.o
Plz help
phatkin
|
|
|
|
|
prubyholl wrote: Plz how can u open a vs2005 project in vs2008 without converting?
AFAIK, you can't. There is no option to do so.
prubyholl wrote: when u convert, does it mean ur project is now .Net framework 3.5?
No. It means the solution files are converted to VS2008 format. The code, nor the dependancy on which framework it's using, is not changed at all.
<blockquote class="FQ"><div class="FQA">prubyholl wrote:</div>i have an application in .net 2.0 with vs2005 and i just got vs2008 and have installed and want to use it but want my existing projects to remain .Net 2.o</blockquote>
Then don't change it. The projects will still be using .NET 2.0 when you recompile them.
BTW, did you even TRY this to see what happens?? It's easy. Make a backup copy of your project folder and open the thing in 2008. Trial and error, and the ability to do research is the life blood of any developer worth his paycheck.
|
|
|
|
|
|
Hi,
Is it possbile to disable the topMost property on a complete vb.net program (.exe) or somehow bypass it... The software is started maximized and its topMost property is set to True so I cannot see any other forms while I run this program...
Thank you!
|
|
|
|
|