|
Hi!
I have a tricky question regarding exceptions in C#:
I need to know, somewhere in my code, if an execption has been thrown or not.
Basically, in the code below, when an unhandled exception is thrown within my using statement, the code will first call the Dispose() method on my UnitOfWork object (the one in the "using"), and THEN go in the catch statement. Wich is exactly what I want.
The only problem is, in my Dispose() method, I have no way to know if I'm there because of an exception (in that case I want to call some rollback code), or if I'm there because the code in the "using" ran ok.
My question is: how can I know if I'm in an error context from within my Dispose() method?
A few things you need to know:
- I'm working on a WinForm (so I can't use the ASP.NET Server.GetLastError())
- I can't use the event UnhandledException (as it can be handled externaly to my using statement, as showb below)
- I basicaly need the equivalent of Server.GetLastError(), but in WinForm...
<br />
try<br />
{<br />
<br />
using (Dao.GetUnitOfWork())<br />
{<br />
throw new Exception("Wanted Exception");<br />
}
}<br />
catch<br />
{<br />
}<br />
Thanks!!!
Antoine
|
|
|
|
|
You could pass the exception to UnitOfWork before Dispose is called. Something like this:
try
{
using ( var work = Dao.GetUnitOfWork() )
{
try
{
throw new Exception( "Wanted Exception" );
}
catch ( Exception x )
{
work.ExceptionWasThrown( x );
throw;
}
}
}
catch { ... }
If you don't need the exception object, but just whether any exception was thrown or not, then you could use a transaction pattern:
try
{
using ( var work = Dao.GetUnitOfWork() )
{
throw new Exception( "Wanted Exception" );
work.Commit();
}
}
catch { ... }
If Commit has not been called before Dispose, then you know an exception was thrown.
Nick
----------------------------------
Be excellent to each other
|
|
|
|
|
Hi Nick,
First, many thanks for your answer!
Unfortunately, it doesn't solve my problem:
Indeed, my try/catch was only there to show my point, but what I really want, is my UnitOfWork to dispose when I don't have a try/catch.
Of course, the best pattern would be to try:commit/catch:rollback everytime, but I wanted to simplify that by just using my "using" statement.
in other word, my question shouldn't have had any try/catch in the first place:
using ( Dao.GetUnitOfWork() )
{
Console.WriteLine("Everything works");
}
using ( Dao.GetUnitOfWork() )
{
Console.WriteLine("code always called");
throw new Exception( "Wanted Exception" );
Console.WriteLine("code never called");
}
public void Dispose()
{
if (???)
Commit();
else
Rollback();
}
So here, when Dispose() is called (knowing that my UnitOfWork object doesn't know the context in which it is used!), I need to know whether my code ran correctly or if I'm in an Exception situation...
Please advise if I'm confusing
|
|
|
|
|
There's no Exception.Current property or similar that I know of, so I think you're going to have to implement this explicitly.
My second example in my previous post can work. I've removed the name clash to make it clearer:
using ( var work = Dao.GetUnitOfWork() )
{
Console.WriteLine( "Everything works" );
work.RegisterSuccess();
}
using ( var work = Dao.GetUnitOfWork() )
{
throw new Exception();
work.RegisterSuccess();
}
partial class UnitOfWork
{
private bool _Success = false;
public void RegisterSuccess() { _Success = true; }
public void Dispose()
{
if ( _Success )
Commit();
else
Rollback();
}
}
When an exception is not thrown, work.RegisterSuccess() is called and _Success is set to true , so you can call Commit() in Dispose() .
When an exception is thrown, work.RegisterSuccess() is not called and _Success is still false , so you call Rollback() is Dispose() .
Is that what you wanted?
Nick
----------------------------------
Be excellent to each other
|
|
|
|
|
Hi Nick,
Thanks for this, it's indeed a solution, though not perfect as the consumer of the code needs to remember to call the RegisterSuccess() method each time, which, IMHO, should be avoided.
But as you said, there's no Exception.Current or similar, so I'm afraid I won't be able to do it the way I wanted
Many thanks anyway for your input!
Cheers
Antoine
|
|
|
|
|
Hi Antoine,
No, not perfect! But I've used this pattern before and it is workable. If you forget to call RegisterSuccess, the code will fail in a big way, so it's quite an obvious bug.
Antoine Jaussoin wrote: Many thanks anyway for your input!
You're welcome.
Nick
----------------------------------
Be excellent to each other
|
|
|
|
|
as Nick said.
work.RegisterSuccess() is what I suggest too.
I would probably call it work.Commit() though.
|
|
|
|
|
Hi all,
I want to enumerate all the distinct source of the events written in any event log in C#.
Can any one help me ?
|
|
|
|
|
Hi,
From all the event log sources or from a specific one?
Regards,
The only programmers that are better C# programmers, are those who look like this -> |
Programm3r
My Blog: ^_^
|
|
|
|
|
What about something like this:
List<System.Diagnostics.EventLogEntry> entries = new List<System.Diagnostics.EventLogEntry>();
foreach (System.Diagnostics.EventLog eLog in System.Diagnostics.EventLog.GetEventLogs())
foreach (System.Diagnostics.EventLogEntry entry in eLog.Entries)
entries.Add(entry);
IEnumerable<System.Diagnostics.EventLogEntry> distinct = entries.Distinct();
entries = new List<System.Diagnostics.EventLogEntry>();
foreach (System.Diagnostics.EventLog eLog in System.Diagnostics.EventLog.GetEventLogs())
foreach (System.Diagnostics.EventLogEntry entry in eLog.Entries)
if (entry.Source == "TFSShellExt")
entries.Add(entry);
IEnumerable<System.Diagnostics.EventLogEntry> distinct2 = entries.Distinct();
Kind regards,
The only programmers that are better C# programmers, are those who look like this -> |
Programm3r
My Blog: ^_^
|
|
|
|
|
|
Can we program Micro controller AVR with C# codings
Cause AVR is difficult for me to code it. and now i wanna to program micro
with C# ?
|
|
|
|
|
Probably not - the range of RAM available is 0.5K to 384K bytes, so I doubt it. The lower ones especially, are very unlikely. I know C is available for the AVR but you will be best to talk to the manufactures about your specific chip from the range to find out if C# is available, (or even possible)
All those who believe in psycho kinesis, raise my hand.
|
|
|
|
|
|
Acording to MSDN:
The typical .NET Micro Framework device has a 32 bit processor with no external memory management unit (MMU) and could have as little as 64K of random-access memory (RAM).
The AVR is eight bit and some of the range is a lot less than 64K. Plus, I always take minimum specs as half the real-world minimum spec!
Have a look at the Porting Kit and see if you can use it...
All those who believe in psycho kinesis, raise my hand.
|
|
|
|
|
the short answer is: no.
One could come up with a C# compiler that generates either C/C++ code or assembly code, so the language could be made available to any processor you choose (I haven't seen a single one though).
However, that is only a small fraction of the solution, as you probably want the whole .NET framework with its many namespaces and classes to be available too; and that would require lots of memory, and solutions for advanced topics such as reflection, which you may or may not need on your micro-controller.
|
|
|
|
|
Hello
how delete Maximize and Minimize button form to C#?
These function delete cloce button no how delete Maximize and Minimize?
protected override CreateParams CreateParams
{
get
{
CreateParams myCp = base.CreateParams;
myCp.ClassStyle = myCp.ClassStyle | 0x200;
return myCp;
}
}
|
|
|
|
|
You just need to set the Form's MinimiseButton and MaximiseButton properties to false.
|
|
|
|
|
|
Is there any particular reason for this? Properties will certainly be a great deal easier than manually overriding the control style.
|
|
|
|
|
try ..this
ControlBox=False
in the property window of the form.
Failure is Success If we learn from it!!
|
|
|
|
|
hi,
i am getting this error called "A network-related or instance-specific error occurred while establishing a connection to SQL Server".
i am using win service instead of web app. my service can connect to sql server in same machine but i found sometime i is giving exception for the above error.
my connection string is look like below one
Server=192.168.88.10\NNKPC;Network Library=DBMSSOCN;Initial Catalog=NNK_DB;User ID=TEST;Password=TEST
so where is wrong in my connection........i am very confuse that sometime not often i am gettting the error like below one and it is in detail.
Error A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Error System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
please help me with some suggestion to get rid of this error.
thanks in advance
tbhattacharjee
|
|
|
|
|
This[^] looks like a pretty good checklist of things to work through to resolve your problem.
|
|
|
|
|
Hi,
I have recently faced a problem, which i am unable to solve. Anyone can guide me please.
Scenario:
I am using MSMQ to communicate between many programs running concurrently...
Programs:
Dedicated TCP/IP server - Windows service
Dedicated Serial Server - Windows service
Dedicated listening Data Processor server - Windows service
Server Manager - Winform App
Message queues:
Data Queue
Command Queue
Admin Queue
I have two communication server listening and sending data to remote clients and data processor. Raw and Processed data are communicated through messages from servers to winform app through data processor. There are two classes named (Event receiver, Event reporter), which each running program subscribes too to communicate between each other. The reporting side is simple containing commands only to send messages. The problem lies in the design of event receiver class.
Its a single classes initializing three receiving(not peeking) events on three message queues. Whereby then it distributes received messages, by using many custom events.
Problem.
Currently declared events as static as they are too be used by many programs running in different projects (i.e the server service project , server manager winform project). The Event reporter, and receiver are in a class library.
What i want is a design pattern for the event receiver class. Which houses MSMQ object initialization and events generated by receiving messages on queue asynchronously, + custom delegates/ events for reporting these messages to different programs in different projects(who subscribe to the static event in this class).
Currently i initialized the Class in the main method of service project, every thing works perfectly there. But nothing happens if i initialize the same class in winform project, which is also dumb work from me as receiving event for message queues now occurs twice in memory as there are now two objects for the class. i.e. May be message is already taken by one class from the queue.
Finally i want a solution in the same design pattern whereby all programs running in different projects are able to to subscribe to same event receiver classes housing receiving events on MSMQ's and custom events , may be static or not?
Help pleasee
i am really stuck!!!!
|
|
|
|
|
If you don't want the WinForm app to steal data from the data processor then why would you reuse the same class to read data? It sounds like you need another communications method to make the data processor and manager app talk with each other.
faheemnadeem wrote: Finally i want a solution in the same design pattern whereby all programs running in different projects are able to to subscribe to same event receiver classes housing receiving events on MSMQ's and custom events , may be static or not?
I don't understand what that means. It doesn't matter if classes are in the same project or not, if a class is instantiated in two different processes then having static members won't make the two instances share members.
|
|
|
|
|