473,394 Members | 1,785 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,394 software developers and data experts.

DbConnection

Hello, Newsgroupians:

I am creating a wrapper for (I)DbConnection. I can connect to a database
and place queries; however, I'm having some problems with my wrapped class.

In short, I have the following...

public class CDB
{
protected System.Data.IDbConnection m_conn;

...

}

Now, I've read that I should ALWAYS close my connection when I'm finished.
So when my class that wraps the connection is ready for garbage collection, I
close the connection in the destructor. It is as follows...

~CDB()
{
if (this.m_conn.State == System.Data.ConnectionState.Open)
{
try
{
this.m_conn.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine(); // I add this just so I can see the message.
}
}
}

The problem is I always receive the exception -- which is an
InvalidOperationException -- "Handle is not initialized." Any ideas what I
am doing wrong, or how to rectify the situation? Thank you. Should you need
more of my code, please do not hesistate to ask. I just thought the other
code was irrelevant in this situation. Thank you again.
Trecius
Aug 15 '07 #1
12 4219

Which part of the code throws the exception? When you check the connection
status or when you try to close the connection?

Adrian.
--
[Please mark my answer if it was helpful to you]


"Trecius" wrote:
Hello, Newsgroupians:

I am creating a wrapper for (I)DbConnection. I can connect to a database
and place queries; however, I'm having some problems with my wrapped class.

In short, I have the following...

public class CDB
{
protected System.Data.IDbConnection m_conn;

...

}

Now, I've read that I should ALWAYS close my connection when I'm finished.
So when my class that wraps the connection is ready for garbage collection, I
close the connection in the destructor. It is as follows...

~CDB()
{
if (this.m_conn.State == System.Data.ConnectionState.Open)
{
try
{
this.m_conn.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine(); // I add this just so I can see the message.
}
}
}

The problem is I always receive the exception -- which is an
InvalidOperationException -- "Handle is not initialized." Any ideas what I
am doing wrong, or how to rectify the situation? Thank you. Should you need
more of my code, please do not hesistate to ask. I just thought the other
code was irrelevant in this situation. Thank you again.
Trecius
Aug 15 '07 #2


Don't use a finalizer. Make your class implement IDisposable and in
Dispose() call Close() on the connection. Any time your custom class
contains an instance variable which is IDisposable, your class also
needs to be IDisposable.

Since the connection is itself a managed object it's improper for you
to reference it at all in a finalzer (it may have been finalized
already).

HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.

On Wed, 15 Aug 2007 10:52:01 -0700, Trecius
<Tr*****@discussions.microsoft.comwrote:
>Hello, Newsgroupians:
~CDB()
{
if (this.m_conn.State == System.Data.ConnectionState.Open)
{
}
}

The problem is I always receive the exception -- which is an
InvalidOperationException -- "Handle is not initialized." Any ideas what I
am doing wrong, or how to rectify the situation? Thank you. Should you need
more of my code, please do not hesistate to ask. I just thought the other
code was irrelevant in this situation. Thank you again.
Trecius
Aug 15 '07 #3
The method that is creating the exception is this.m_conn.Close().
Trecius

"Adrian Voicu" wrote:
>
Which part of the code throws the exception? When you check the connection
status or when you try to close the connection?

Adrian.
--
[Please mark my answer if it was helpful to you]


"Trecius" wrote:
Hello, Newsgroupians:

I am creating a wrapper for (I)DbConnection. I can connect to a database
and place queries; however, I'm having some problems with my wrapped class.

In short, I have the following...

public class CDB
{
protected System.Data.IDbConnection m_conn;

...

}

Now, I've read that I should ALWAYS close my connection when I'm finished.
So when my class that wraps the connection is ready for garbage collection, I
close the connection in the destructor. It is as follows...

~CDB()
{
if (this.m_conn.State == System.Data.ConnectionState.Open)
{
try
{
this.m_conn.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine(); // I add this just so I can see the message.
}
}
}

The problem is I always receive the exception -- which is an
InvalidOperationException -- "Handle is not initialized." Any ideas what I
am doing wrong, or how to rectify the situation? Thank you. Should you need
more of my code, please do not hesistate to ask. I just thought the other
code was irrelevant in this situation. Thank you again.
Trecius
Aug 15 '07 #4
Now, I'm a little confused. So you're all stating that I must ALWAYS call
the Dispose() method everytime I use my class? I'm still new to C#, but it's
impossible to create a class that can dispose of itself? What about
instances where the programmer forgets to call Dispose() on the object
they're using. In this case, the Close() method will never be called. I
suppose this is the crux of the problem, and it's my question. How can I
create my class that will automatically call Close() when the object goes out
of scope and needs to be garbage collected. Thank you.
Trecius

"Samuel R. Neff" wrote:
>

Don't use a finalizer. Make your class implement IDisposable and in
Dispose() call Close() on the connection. Any time your custom class
contains an instance variable which is IDisposable, your class also
needs to be IDisposable.

Since the connection is itself a managed object it's improper for you
to reference it at all in a finalzer (it may have been finalized
already).

HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.

On Wed, 15 Aug 2007 10:52:01 -0700, Trecius
<Tr*****@discussions.microsoft.comwrote:
Hello, Newsgroupians:
~CDB()
{
if (this.m_conn.State == System.Data.ConnectionState.Open)
{
}
}

The problem is I always receive the exception -- which is an
InvalidOperationException -- "Handle is not initialized." Any ideas what I
am doing wrong, or how to rectify the situation? Thank you. Should you need
more of my code, please do not hesistate to ask. I just thought the other
code was irrelevant in this situation. Thank you again.
Trecius

Aug 15 '07 #5
Trecius wrote:
Hello, Newsgroupians:

I am creating a wrapper for (I)DbConnection. I can connect to a database
and place queries; however, I'm having some problems with my wrapped class.

In short, I have the following...

public class CDB
{
protected System.Data.IDbConnection m_conn;

...

}

Now, I've read that I should ALWAYS close my connection when I'm finished.
So when my class that wraps the connection is ready for garbage collection, I
close the connection in the destructor.
..NET doesn't have destructors. That is a finalizer, and it doesn't work
the same as a destructor. The finalizer doesn't run when the object goes
out of scope, as a destructor does in a system that uses reference
counting. When the garbage collector is about to collect the object,
it's placed in a queue of objects that needs finalizing. A background
thread is going through the queue and calls the finalizer in each
object. The fact that the finalizer is run in a different thread might
be the reason for the error that you are getting.

A finalizer can not be used to control the life cycle of an object, as
you have no control over when the finalizer is run.
It is as follows...

~CDB()
{
if (this.m_conn.State == System.Data.ConnectionState.Open)
{
try
{
this.m_conn.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine(); // I add this just so I can see the message.
}
}
}

The problem is I always receive the exception -- which is an
InvalidOperationException -- "Handle is not initialized." Any ideas what I
am doing wrong, or how to rectify the situation?
You should implement the IDisposable interface, so that you can call the
Dispose method when you are done with the connection, just as the
DbConnection class does.

--
Göran Andersson
_____
http://www.guffa.com
Aug 15 '07 #6
Trecius wrote:
Now, I'm a little confused. So you're all stating that I must ALWAYS call
the Dispose() method everytime I use my class? I'm still new to C#, but it's
impossible to create a class that can dispose of itself? What about
instances where the programmer forgets to call Dispose() on the object
they're using. In this case, the Close() method will never be called. I
suppose this is the crux of the problem, and it's my question. How can I
create my class that will automatically call Close() when the object goes out
of scope and needs to be garbage collected. Thank you.
using (CDB db = new CDB())
{
// Use db here.
}

The pattern above is used when you instantiate an object that implements
IDisposable. When db goes out of scope then the Dispose method is
automatically called. This is simply compiler short-hand for this:

CDB db;
try
{
db = new CDB();
}
finally
{
db.Dispose();
}

Yes, you must somehow get your Dispose (i.e., Close) method to be called
or you'll run out of resources (like pooled database connections). If a
programmer forgets to use the using statement or the finally statement
then they have written incorrect code.

--
-glenn-
Aug 15 '07 #7
Trecius wrote:
Now, I'm a little confused. So you're all stating that I must ALWAYS call
the Dispose() method everytime I use my class?
Yes.
I'm still new to C#, but it's
impossible to create a class that can dispose of itself?
Yes. The compiler doesn't add any extra code to handle when objects go
out of scope. As there is no code to handle this, there is no way of
calling a destructor.

For fully managed objects there is no need for any destructor, as the
garbage collector can free all managed objects by itself. It's only when
you class handles unmanaged resources (like a database connection) that
you need to dispose the object in a controlled way.
What about
instances where the programmer forgets to call Dispose() on the object
they're using. In this case, the Close() method will never be called.
A finalizer is usually used as a backup when implementing IDisposable,
so the Close method will be called eventually, but as you have no
control over when this happens, you will still experience problems
sooner or later if you don't call Dispose properly.
I
suppose this is the crux of the problem, and it's my question. How can I
create my class that will automatically call Close() when the object goes out
of scope and needs to be garbage collected.
You can't do that. Nothing happens when an object goes out of scope.

--
Göran Andersson
_____
http://www.guffa.com
Aug 15 '07 #8
If you implement the IDisposable interface, then you can using the
"using" statement, which will call IDisposable for you.

Here's how to implement the IDisposable interface:
http://www.codeproject.com/useritems/idisposable.asp

and here's an example of using the "using" statement. Remember,
connections shouldn't be left open, you should open them, do your
task, then close them (release back to the pool) as soon as possible.
Code:
using (IDbConnection connection =
DbProviderFactories.GetFactory(providerName).Creat eConnection())
{
connection.Open();

using (MyDataAdapter adapter = new MyDataAdapter())
{
adapter.Connection = connection;
adapter.Fill(myDataTable);
}
} // IDispose will be called on the connection here, automatically
closing it

Hope this helps.

Ship.

On Aug 16, 12:12 am, Göran Andersson <gu...@guffa.comwrote:
Trecius wrote:
Now, I'm a little confused. So you're all stating that I must ALWAYS call
the Dispose() method everytime I use my class?

Yes.
I'm still new to C#, but it's
impossible to create a class that can dispose of itself?

Yes. The compiler doesn't add any extra code to handle when objects go
out of scope. As there is no code to handle this, there is no way of
calling a destructor.

For fully managed objects there is no need for any destructor, as the
garbage collector can free all managed objects by itself. It's only when
you class handles unmanaged resources (like a database connection) that
you need to dispose the object in a controlled way.
What about
instances where the programmer forgets to call Dispose() on the object
they're using. In this case, the Close() method will never be called.

A finalizer is usually used as a backup when implementing IDisposable,
so the Close method will be called eventually, but as you have no
control over when this happens, you will still experience problems
sooner or later if you don't call Dispose properly.
I
suppose this is the crux of the problem, and it's my question. How canI
create my class that will automatically call Close() when the object goes out
of scope and needs to be garbage collected.

You can't do that. Nothing happens when an object goes out of scope.

--
Göran Andersson
_____http://www.guffa.com

Aug 16 '07 #9
Göran Andersson wrote:
>I'm still new to C#, but it's impossible to create a class that can
dispose of itself?

Yes. The compiler doesn't add any extra code to handle when objects go
out of scope. As there is no code to handle this, there is no way of
calling a destructor.
Just a clarification. It doesn't call any destructors (because there
aren't any), but the compiler treats the using statement specially and
does emit code to call an objects Dispose method. You can code the same
thing by hand with a try-finally block, but the compiler will do this
for you if you can use a using statement.
>What about instances where the programmer forgets to call Dispose() on
the object they're using. In this case, the Close() method will never
be called.

A finalizer is usually used as a backup when implementing IDisposable,
so the Close method will be called eventually, but as you have no
control over when this happens, you will still experience problems
sooner or later if you don't call Dispose properly.
Is a finalizer really a backup to Dispose? I've never heard that before
and question how it could be used that way. I mean, you have no idea
when a finalizer will be called so what can it do of any use since it
will not know the state of any unmanaged resources by the time the
finalizer runs? I don't think I've ever written a finalizer, especially
not one that has anything to do with the IDispose pattern.
>I suppose this is the crux of the problem, and it's my question. How
can I create my class that will automatically call Close() when the
object goes out of scope and needs to be garbage collected.

You can't do that. Nothing happens when an object goes out of scope.
I'm not sure I understand what you are saying. In this code:

using (CDB db = new CDB()) { ... }

When db goes out of scope, the compiler has emitted code to cause the
object's Dispose method to be called. So he would implement the IDispose
pattern to cause Close (i.e., Dispose) to be called when all the
references to the object have gone out of scope. (Of course, as already
pointed out, the IDispose pattern need not be implemented unless
unmanaged resources are being used by the class.)

Or do you mean that the just because all the references to an object
have gone out of scope, that doesn't mean anything about when the GC
will get around to cleaning up that object?

--
-glenn-
Aug 16 '07 #10
GlennDoten wrote:
Göran Andersson wrote:
>>I'm still new to C#, but it's impossible to create a class that can
dispose of itself?

Yes. The compiler doesn't add any extra code to handle when objects go
out of scope. As there is no code to handle this, there is no way of
calling a destructor.

Just a clarification. It doesn't call any destructors (because there
aren't any), but the compiler treats the using statement specially and
does emit code to call an objects Dispose method. You can code the same
thing by hand with a try-finally block, but the compiler will do this
for you if you can use a using statement.
That is correct. To furter clarify this, it's only the object that you
specify in the using clause that is disposed, any other objects that
happen to have the using block as scope doesn't get disposed.

Example:

using (StreamWriter writer = File.CreateText("info.txt)) {
String message = "Hello world.";
writer.Write(message);
}

Here the string message has the using block as scope. Still, only the
StreamWriter will be disposed, but not the string. (Yes, I know that
strings doesn't implement IDisposable, but it's just an example...)
>>What about instances where the programmer forgets to call Dispose()
on the object they're using. In this case, the Close() method will
never be called.

A finalizer is usually used as a backup when implementing IDisposable,
so the Close method will be called eventually, but as you have no
control over when this happens, you will still experience problems
sooner or later if you don't call Dispose properly.

Is a finalizer really a backup to Dispose?
Yes, it's used that way.
I've never heard that before
and question how it could be used that way. I mean, you have no idea
when a finalizer will be called so what can it do of any use since it
will not know the state of any unmanaged resources by the time the
finalizer runs?
The Dispose method will call GC.SuppressFinalize, so the finalizer will
only run if Dispose was not called.

You can check out the example code for the IDisposable interface:

http://msdn2.microsoft.com/en-us/lib...isposable.aspx
I don't think I've ever written a finalizer, especially
not one that has anything to do with the IDispose pattern.
>>I suppose this is the crux of the problem, and it's my question. How
can I create my class that will automatically call Close() when the
object goes out of scope and needs to be garbage collected.

You can't do that. Nothing happens when an object goes out of scope.

I'm not sure I understand what you are saying. In this code:

using (CDB db = new CDB()) { ... }

When db goes out of scope, the compiler has emitted code to cause the
object's Dispose method to be called.
The compiler adds the code at the end of the using block. This has
nothing at all to do with the scope of the variable. If the scope of the
variable is outside the using block, the code is still added at the end
of the using block:

CDB db = new CDB()
using (db) {
...
// Dispose is called here
}
// the db variable is still reachable here
So he would implement the IDispose
pattern to cause Close (i.e., Dispose) to be called when all the
references to the object have gone out of scope.
The Dispose method has to be called explicitly (for example by using
using). It's not called automatically when the object gets unreachable.
(Of course, as already
pointed out, the IDispose pattern need not be implemented unless
unmanaged resources are being used by the class.)

Or do you mean that the just because all the references to an object
have gone out of scope, that doesn't mean anything about when the GC
will get around to cleaning up that object?
I just mean that nothing happens when an object goes out of scope (or to
be more accurate, when the reference variable goes out of scope).

--
Göran Andersson
_____
http://www.guffa.com
Aug 16 '07 #11
Göran Andersson wrote:
GlennDoten wrote:
>Göran Andersson wrote:
>>>I'm still new to C#, but it's impossible to create a class that can
dispose of itself?

Yes. The compiler doesn't add any extra code to handle when objects
go out of scope. As there is no code to handle this, there is no way
of calling a destructor.

Just a clarification. It doesn't call any destructors (because there
aren't any), but the compiler treats the using statement specially and
does emit code to call an objects Dispose method. You can code the
same thing by hand with a try-finally block, but the compiler will do
this for you if you can use a using statement.

That is correct. To furter clarify this, it's only the object that you
specify in the using clause that is disposed, any other objects that
happen to have the using block as scope doesn't get disposed.

Example:

using (StreamWriter writer = File.CreateText("info.txt)) {
String message = "Hello world.";
writer.Write(message);
}

Here the string message has the using block as scope. Still, only the
StreamWriter will be disposed, but not the string. (Yes, I know that
strings doesn't implement IDisposable, but it's just an example...)
Agreed. In that case you'd use this:

using (StreamWriter writer = File.CreateText("info.txt))
{
using (string message = "Hello world.")
{
writer.Write(message);
}
}

(Again, as you said, a string is not disposable, but pretend it is.)
>I've never heard that before and question how it could be used that
way. I mean, you have no idea when a finalizer will be called so what
can it do of any use since it will not know the state of any unmanaged
resources by the time the finalizer runs?

The Dispose method will call GC.SuppressFinalize, so the finalizer will
only run if Dispose was not called.
Ah yes, now that you mention that. I forgot about SuppressFinalize.
>>>I suppose this is the crux of the problem, and it's my question.
How can I create my class that will automatically call Close() when
the object goes out of scope and needs to be garbage collected.

You can't do that. Nothing happens when an object goes out of scope.

I'm not sure I understand what you are saying. In this code:

using (CDB db = new CDB()) { ... }

When db goes out of scope, the compiler has emitted code to cause the
object's Dispose method to be called.

The compiler adds the code at the end of the using block. This has
nothing at all to do with the scope of the variable. If the scope of the
variable is outside the using block, the code is still added at the end
of the using block:

CDB db = new CDB()
using (db) {
...
// Dispose is called here
}
// the db variable is still reachable here
The code isn't added to the end of the using block, at least not like
that. The compiler automatically emits a finally block. So while "going
out of scope" is not technically correct, what I meant was that the db
variable is *effectively* out of scope once the finally block runs; that
is, the Dispose method has been run on the object once the scope of the
using block ends. I didn't mean to say the object referred to by the db
variable would be eligible for garbage collection after the using block
is finished, just that the Dispose method is guaranteed to have been
called at that point.
>So he would implement the IDispose pattern to cause Close (i.e.,
Dispose) to be called when all the references to the object have gone
out of scope.

The Dispose method has to be called explicitly (for example by using
using). It's not called automatically when the object gets unreachable.
Well, to nit-pick, I would say that using the using statement calls the
Dispose method implicitly.

Again, I hope I haven't given the impression that Dispose is called
somehow once all the references to it go out of scope.
>Or do you mean that the just because all the references to an object
have gone out of scope, that doesn't mean anything about when the GC
will get around to cleaning up that object?

I just mean that nothing happens when an object goes out of scope (or to
be more accurate, when the reference variable goes out of scope).
Except that it may make the object referenced by the variable eligible
to be garbage collected ("may" because other variables may hold
references to the object as well). But as far as Dispose is concerned,
agreed, nothing happens when a variable referencing an object goes out
of scope.

Phew, I think we're saying the same thing!
--
-glenn-
Aug 16 '07 #12
GlennDoten wrote:
Agreed. In that case you'd use this:

using (StreamWriter writer = File.CreateText("info.txt))
{
using (string message = "Hello world.")
{
writer.Write(message);
}
}
I prefer:

using (StreamWriter writer = File.CreateText("info.txt"),
string message = "Hello world.")
{
}

There are some contexts in which nesting using statements may make more
sense, but assuming the variables are nominally scoped to the same block
logically, the above syntax is preferable to me.

Pete
Aug 16 '07 #13

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

Similar topics

4
by: Troy | last post by:
We recently installed the .Net framework on a windows 2000 server. Shortly after that we experienced intermitant problems running a web based program that accesses an Access 2002 database. The...
3
by: Patrick.O.Ige | last post by:
I'm loading an Array below but getting the error "Object reference not set to an instance saying 'ItemNumber = CType(Args.Item.FindControl("ItemNumber"), TextBox).Text' is the error line. I DON'T...
14
by: Marcus | last post by:
I have a function that simply returns TRUE if it can connect to a particular Sql Server 2005 express, or FALSE if it cannot. I am getting some strange error codes returned when the computer that...
2
by: Roy | last post by:
I created my own DbConnection class using System; using System.Data; using System.Data.Common; using System.Xml; namespace MyNS { public sealed class MyConnection : DbConnection, ICloneable
1
by: arthy | last post by:
Hi, Is it possible to execute multiple statements on to the database using a single dbconnection object.what is the drawback in using .If not possible ,then how can the execution of multiple...
2
by: RSH | last post by:
I have a data access layer that needs to handle multiple Database types. I have seen genecric references being made to a DBConnection, DBCommand etc. What namespace are they in? Ron
2
by: Jelle de Jong | last post by:
Hi all, I have a datasource and I want to connect to it like ADO.Net and build my own DbConnection and stuff. But I don't want to build my own SQL-parser. Does someone have a good idea to use...
4
by: =?Utf-8?B?cmJEZXZlbG9wZXI=?= | last post by:
In the code below, I'm setting a watch on the variable dbCon. When I expand the watch on dbCon, one of the visible items under dbCon is "ServerVersion." When the dbCon.Close() executes, I see the...
3
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I've created a class that wraps DbConnection. public class CSQL { protected System.Data.Common.DbConnection m_conn; public CSQL {
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...

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.