|
The previous post is not entirely correct. Close() and Dispose() do not do the same thing with respect to a SqlConnection. It is true that Dispose() will close the connection if the ConnectionState is Open, but the converse is not true: if Close() is called, the SqlConnection is not disposed, and your initial assertion is correct - the connection may be re-opened.
In general, the following should ideally be true for disposable types (the concept of Close is not covered, since it doesn't really apply to the discussion, and may mean different things to different types - file streams, database connections, sockets etc.):
1. Dispose() should be responsible for cleaning up unmanaged resources and indicating to the GC that finalization is suppressed for the instance (suppressing finalization explicitly avoids the default two-pass collection of collectible objects). The value of Dispose() is that unmanaged resources can be reclaimed immediately (or nearly so), without waiting for the GC. Suppressing finalization for the object serves to streamline the garbage collection process so that it takes only one pass to reclaim the managed resources used by the object instead of two passes (one to finalize, one to reclaim).
2. Setting an object to null just drops a reference to the object, essentially setting it adrift in the (managed) heap until the GC executes and begins cleaning it up. There is no guarantee about when the resources for that object will be reclaimed.
For more info, look here.[^]
Hope this helps.
The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’
|
|
|
|
|
turbochimp wrote:
It is true that Dispose() will close the connection if the ConnectionState is Open, but the converse is not true: if Close() is called, the SqlConnection is not disposed
I don't understand. If Dispose calls Close(), then Dispose and Close must do the same thing. What do you mean by "the SqlConnection is not disposed" ? If you can call Open() on a connection on which you've called Close, you can as well call it after calling Dispose(). Dispose doesn't do anything extra, as you can see with a tool like Reflector.
Regards
Senthil
_____________________________
My Blog | My Articles | WinMacro
|
|
|
|
|
Dispose calls Close, but Close doesn't call Dispose, so the two don't do the same thing!
You can do this:
SqlConnection conn = new SqlConnection(...);<br />
conn.Open();<br />
conn.Close();<br />
conn.Open();<br />
conn.Dispose();
but you will get an exception with this:
SqlConnection conn = new SqlConnection(...);<br />
conn.Open();<br />
conn.Dispose();<br />
conn.Open();
Regards,
mav
|
|
|
|
|
Well, if you have two methods A() and B(), and A does nothing but call B(), then they both do the same thing. If A called B and B called A, you'll get mutual recursion
That apart, you're right, I missed the fact that Dispose clears the ConnectionString property after calling Close(). This piece of code works fine.
SqlConnection conn = new SqlConnection(...);
conn.Open();
conn.Dispose();
conn.ConnectionString = "...";
conn.Open();
conn.Dispose();
I still do maintain that they both essentially do the same thing, I don't know why the FCL designers added code to clear the connection string.. If you ask me, Close and Dispose should do the same thing.
Regards
Senthil
_____________________________
My Blog | My Articles | WinMacro
|
|
|
|
|
I think you are confused about the intended uses of Dispose() and Close() . They are very different. I would encourage you to read the same article I suggested in my original post.
I would also encourage you to look further into what actually happens when Dispose() is called on a SqlConnection (or any type that implements IDisposable , if it's implemented correctly). Specifically, in SqlConnection.Dispose() , you will (or should) see a call to base.Dispose(disposing) . If you had taken the time to inspect the base class (System.ComponentModel.Component ), you would have seen that there's a little more to the disposal of the SqlConnection instance than you indicated in either of your posts.
The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’
|
|
|
|
|
I admit that I was wrong with the semantics of Close() and Dispose with respect to SqlConnection .
What I'm still not convinced about is that Close is supposed to be a "customized" Dispose, as this[^] and this[^] link mention, [EDIT] but in the case of SqlConnection, they act differently.[/EDIT]
Regards
Senthil
_____________________________
My Blog | My Articles | WinMacro
|
|
|
|
|
While I would have to place myself in the "Richter" camp on this as well, I understand the point these articles are trying to make, and I don't know if I really disagree with their implementations, except possibly from an aesthetic point of view.
My thinking is:
1. Dispose() has a clear definition and purpose regardless of type. If the type has unmanaged resources, and it may be important to release those resources in a time-critical manner, then the type will likely benefit from a Dispose() method.
2. Close() has a somewhat less well-defined purpose that is affected by the type on which it is implemented. It has a high-level meaning that applies in most places (i.e. "To stop or obstruct some kind of operation or behavior") and means the same thing to most people, but the specifics of how to "Close" an instance of a type are potentially specific to the type itself, as are the rules about re-opening the instance, how closing affects state, etc.
There are clearly some cases where Close() and Dispose() might effectively mean the same thing, as the first article suggests, but there are obviously others (e.g. SqlConnection ) where the intent of the developers was to make the methods behave differently. Both are okay in my book, but what can't get overlooked is that while Close() may or may not be implemented on a disposable type, the IDisposable interface ( thus Dispose() ) *must* be implemented, or unexpected results may ensue. In those cases where Close() and Dispose() are interchangeable, the word "Close" may be considered more "user friendly" or less confusing than "Dispose", and so a case can be made for implementing a Close() method that simply masks the Dispose() method.
In general though, I'd prefer a more expository API (one that had both methods marked public, if the developers really felt that strongly about it), but that's just me, and the decision really boils down to developer preference and the consuming client's perceived level of understanding.
Have a good one.
The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’
|
|
|
|
|
The general rule of thumb is that anytime you call Dispose any unmanaged resources that were allocated are now unavailable so doing anything further with the object is risky. Since the object is kind of in an invalid state using the object beyond the Dispose .
It should also be noted that Dispose can happen independant of Object.Finalize . Dispose is an interface so an object can deallocate resources and not meant as the general "death of the object". There is a whole side topic of the GC that should be discussed outside of the thread if you really care.
My general practice is when I'm done with an object that has to manage limited resources, I call Dispose (I usually try to place this in a finally block) and then set it to null so if anyone "accidently" tries to reuse the object it will throw a NullReferenceException .
|
|
|
|
|
Okay now i see it more clear. Cause im working with 2 mates and 1 always does null, the other allways do Close or Dispose, and when i asked what was the difference they didnt know what to answer me.
Ty for ur answers ppl.I appreciate ur help
|
|
|
|
|
Hello.
I am trying to copy a worksheet in excel to an another worksheet.Let's say, I have an existing excel file(ExcelSablon.xls) and want to create a new excel file in a different name.
........
// Make an instance of Excel.
ExcelApplication excel = new ExcelApplication();
// Show Excel on the desktop. (fast = running in the background)
excel.Visible = true;
// Add a new workbook.
Workbook workbook = excel.Workbooks.Add(System.Type.Missing);
Workbook workBookSource = excelSource.Workbooks.Open(@"C:\TqmFiles\Templates\ExcelSablon.xls",missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing);
Worksheet workSheetSource = (Worksheet)excelSource.Sheets["Sheet1"];
Worksheet worksheet = (Worksheet)excel.ActiveSheet;
worksheet.Copy(workSheetSource,missing);
worksheet.SaveAs("C:\Temp\CopyOfExcelFile.xls", missing, missing, missing, missing, missing, missing, missing, missing, missing);
excel.Quit();
When I try to do this, it gives error in worksheet.Copy(workSheetSource,missing); statement.
Can anybody help me please?
Fatih Sen
|
|
|
|
|
You need to indicate what error you're receiving, for starters. You should also indicate what the value of the 'missing ' variable is (it should probably be something like Missing.Value ).
Also, I assume you plan to further use Excel automation to do something with the worksheet you copied, otherwise why not just use File.Copy ?
The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’
|
|
|
|
|
Hey guys,
With the help of this forum I came a long way on my learning proces getting connected to the Active Directory.:->
With an example from the MSDN I managed to get an listing of all groups including the users in that group:
strPath = "LDAP://domainname"; <br />
<br />
Console.WriteLine("Bind to: {0}", strPath);<br />
Console.WriteLine("Enum: Groups and members.");<br />
<br />
try{<br />
objADAM = new DirectoryEntry(strPath);<br />
objADAM.RefreshCache();<br />
}<br />
catch(Exception ex){<br />
Console.WriteLine("Error: Bind failed.");<br />
Console.WriteLine(" {0}", ex.Message);<br />
}<br />
<br />
<br />
try{<br />
objSearchADAM = new DirectorySearcher(objADAM);<br />
objSearchADAM.Filter = "(&(objectClass=group))";<br />
objSearchADAM.SearchScope = SearchScope.Subtree;<br />
objSearchResults = objSearchADAM.FindAll();<br />
}<br />
catch(Exception ex){<br />
Console.WriteLine("Error: Search failed.");<br />
Console.WriteLine(" {0}", ex.Message);<br />
}<br />
<br />
try{<br />
if(objSearchResults.Count != 0){<br />
foreach(SearchResult objResult in objSearchResults){<br />
objGroupEntry = objResult.GetDirectoryEntry();<br />
Console.WriteLine("Group {0}", objGroupEntry.Name);<br />
<br />
foreach(object objMember in objGroupEntry.Properties["member"]){<br />
Console.WriteLine(" Member: {0}", objMember.ToString());<br />
}<br />
}<br />
}<br />
else{<br />
Console.WriteLine("Results: No groups found.");<br />
}<br />
}<br />
catch(Exception ex){<br />
Console.WriteLine("Error: Enumerate failed.");<br />
Console.WriteLine(" {0}", ex.Message);<br />
}<br />
Console.WriteLine("Success: Enumeration complete.");<br />
Console.ReadLine();<br />
}
This works great. I know it's possible to connect to a single group. I mean something like:
strPath = "LDAP://domainname/CN=Groupname,DC=domain***,DC=domain***";
When I execute the code he throws an exception saying:
"Object not found on server"
So i'm doning something wrong in the syntax-connection-string is guess.
This is the exact string I'm trying to use:
strPath = "LDAP://cu4it/CN=D_Company, CN=Users,DC=Cu4iT, DC=tld";
cu4it -> domainname
CN=D_Company -> The group I'm trying to connect to
CN=Users -> Don't know why, but find this in many examples
DC=Cu4iT, DC=tld -> retrieved from rootDSE.Properties ["configurationNamingContext"]
Can anyone tell me what I'm doing wrong here?
Thanks in advance!
|
|
|
|
|
Hi,
Can anyone show me how to change the balance of an audio line!? I need the same function like the windows volume control pannel does.
If I change the balance in my program, I want should see teh change in the volume control pannel too.
How can I do this!?
Thx for help...
Daniel
|
|
|
|
|
I have a DataGrid control which has some DataGridTableStyles. I want to bind an IList to one of these DataGridTableStyles without converting this IList to a table and assign the name of this table to the MappingName property of the DataGridTableStyle. How can I do?
Thanks!
ghghgj
|
|
|
|
|
Hi,
the MappingName of the table style has to be set to the class name of the list class assigned to the data source. I dont know if IList is sufficient. If not take myList.GetType().Name as the mapping name.
The column style's mapping names then have to be set to the names of the properties you wish to show.
|
|
|
|
|
could anyone plz kindly tell me how to select row from the datagrid and display them in Textboxes. so that i can edit them.
for eg;- datagrid has two column containing first name(John) and lastname(smith). i need to select them and display them in textbox 1 for displaying first name and 2 for displaying last name.
leo
Kathmandu, Nepal
|
|
|
|
|
A simple example.
Suppose you have a dataSet that contains data from a couple of tables located in a Database. The following code snippet will loop through each of the records in the FIRST table of the dataSet and will display the values of the fields username and password, for each record (row). I know it's a silly example since it doesn't make a lot of sense to do something like that, but it demonstrates the way for accessing the rows in a table:
DataTable <code>dt</code> = dataSet1.Tables[0];
for(int <code>i</code> = 0; i < dt.Rows.Count; i++)
{
this.textBox1.Text.Trim() == dt.Rows[i]["Username"].ToString().Trim();
this.textBox2.Text.Trim() == dt.Rows[i]["Password"].ToString().Trim();
}
Hope this helps
Regards,
Polis
Can you practice what you teach?
|
|
|
|
|
Good day to all of you, I'm an intermediate C# programmer, and I'm trying to help my friend who has a small computer rental for the monitoring of the pc use, mostly for gaming/internet. As of now, he is confined to writing all in a record book and do all by hand, so I want every computer to have a small window that has their time remaining before the computer logs off or hibernate, the workstations are being controlled by the server in the cashier. The problem is how can I access the workstations for me to control it in the server and to place small windows in them. Somebody told me that it can be done using winsock. This is my first time to handle a network related application using C#. Thanks in advance.
|
|
|
|
|
You can probably do it with a quick script but...
If you want to use c# the fastest way is to create a client / server app using remoting.
|
|
|
|
|
How can I get the hardware profile of remote computer?
I am working on a web application which check visitor hardware profile and display it on the web... I have the problem of how can I make it run automatically without troubling the user to download it and run it on local machine.
|
|
|
|
|
I use this code to handle my event, but DoubleClick event not work.
Can some one help me?
thanks.
pictureBox.DoubleClick += new System.EventHandler(mouseDoubleClick);
pictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(MouseDown);
|
|
|
|
|
hi, i have tested it and it works. here are the 2 lines of my code
this.pictureBox1.DoubleClick += new System.EventHandler(pictureBox1_DoubleClick);
this.pictureBox1.MouseDown +=new MouseEventHandler(pictureBox1_MouseDown);
Make sure u get the sender and event args and no exception is skipping ur code.
I made a pic box which changes the location on double click and changes image in mouse down , show the methods code to see whats wrong.
|
|
|
|
|
Thanks for your answer.
there are my code it's a thumpnails image.
method doubleclick for open image.
and mousedown for dragdrop image to my other panel.
pictureBox.DoubleClick += new System.EventHandler(mouseDoubleClick);
pictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(MouseDown);
public void MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
PictureBox pb=(PictureBox)sender;
pb.DoDragDrop(filename,DragDropEffects.Copy);
}
public void mouseDoubleClick(object sender, System.EventArgs e)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName=filename;
proc.Start();
}
|
|
|
|
|
as topic, how to write a loading screen when my system is doing something like loading the sql statement, crystal report or datagrid?the loading screen will automatically show during loading, then it will automatically close when the loading is complete, anyone can provide some coding on this? ur help is greatly appreciated..;)
|
|
|
|
|
I have a form which has more than 10 combobox controls and all should be filled from a different fields in different tables in one mySQL database. I want to do this using the code and not at design time because I have the connection setting in the registry.
what is the best way to do it (with example please) to make sure the form loadng won't be too slow..
Many Thanks,
Jassim Rahma
|
|
|
|
|