Does the using statement keep me from closing or destroying objects? - asp.net

If I use something like:
using (OdbcConnection conn = new OdbcConnection(....))
{
conn.open();
my commands and sql, etc.
}
Do I have to do a conn.close(); or does the using statement keep me from doing that last call? Does it dispose of everything in the using block? For example, if I called other objects unlrelated would it dipose of those automatically also?
Thank you. I was unclear after reading about using on Microsoft's site. I want to make sure I don't have any memory leaks.

The using block will dispose of the OdbcConnection.
Normal scope rules work for anything declared inside the using block.
The using block will not clean up any other IDisposable objects. It only cleans up the declared item
note that you can nest using blocks, or if the items are the same type, multiple items can be initialized at the same time.
See the top bit of my other answer for How do I use the using keyword in C# for a little more information.
I should also mention that you can close (dispose) of the connection as soon as you are done with it to release the resource. The guidelines say that the caller should be able to repeatedly call the dispose method. The using block is essentially just a safety net and allows writing clearer code in most circumstances.
[Edit]
e.g. multiple initialization in a using: initialize more than one object in the same using without having to nest using blocks if the objects are the same type:
using (Bitmap b1 = new Bitmap("file1"), b2 = new Bitmap("file2"))
{ ... }
Joel Coehoorn mentioned stacking, which is nesting but omitting the braces, much as you can omit the braces in a for, or if statement. The UI doesn't reformat with an indent. I'd be curious what the IL looks like.
using(Bitmap b = new Bitmap("filex"))
using(Graphics g = Graphics.FromImage(b))
{
}
It is an error to use put different objects in the same using error CS1044: Cannot use more than one type in a for, using, fixed, or declaration statement.
// error CS1044
using(Bitmap b = new Bitmap("filex"), Graphics g = Graphics.FromImage(b))

The using statement will handle calling the Close and Dispose methods for you.
Scott Hanselman has a pretty good explanation of the using statement.

The using statement ensures that an object which implements IDisposable gets disposed. It will only dispose the object that is referened in the using block so your code is basically equivlant to:
OdbcConnection conn = new ....;
try
{
conn.open();
conn.....
}
finally
{
conn.dispose();
}

Related

Exit for loop inside using keyword [duplicate]

I've the following code
using(MemoryStream ms = new MemoryStream())
{
//code
return 0;
}
The dispose() method is called at the end of using statement braces } right? Since I return before the end of the using statement, will the MemoryStream object be disposed properly? What happens here?
Yes, Dispose will be called. It's called as soon as the execution leaves the scope of the using block, regardless of what means it took to leave the block, be it the end of execution of the block, a return statement, or an exception.
As #Noldorin correctly points out, using a using block in code gets compiled into try/finally, with Dispose being called in the finally block. For example the following code:
using(MemoryStream ms = new MemoryStream())
{
//code
return 0;
}
effectively becomes:
MemoryStream ms = new MemoryStream();
try
{
// code
return 0;
}
finally
{
ms.Dispose();
}
So, because finally is guaranteed to execute after the try block has finished execution, regardless of its execution path, Dispose is guaranteed to be called, no matter what.
For more information, see this MSDN article.
Addendum:
Just a little caveat to add: because Dispose is guaranteed to be called, it's almost always a good idea to ensure that Dispose never throws an exception when you implement IDisposable. Unfortunately, there are some classes in the core library that do throw in certain circumstances when Dispose is called -- I'm looking at you, WCF Service Reference / Client Proxy! -- and when that happens it can be very difficult to track down the original exception if Dispose was called during an exception stack unwind, since the original exception gets swallowed in favor of the new exception generated by the Dispose call. It can be maddeningly frustrating. Or is that frustratingly maddening? One of the two. Maybe both.
using statements behave exactly like try ... finally blocks, so will always execute on any code exit paths. However, I believe they are subject to the very few and rare situations in which finally blocks are not called. One example that I can remember is if the foreground thread exits while background threads are active: all threads apart from the GC are paused, meaning finally blocks are not run.
Obvious edit: they behave the same apart from the logic that lets them handle IDisposable objects, d'oh.
Bonus content: they can be stacked (where types differ):
using (SqlConnection conn = new SqlConnection("string"))
using (SqlCommand comm = new SqlCommand("", conn))
{
}
And also comma-delimited (where types are the same):
using (SqlCommand comm = new SqlCommand("", conn),
comm2 = new SqlCommand("", conn))
{
}
Your MemoryStream object will be disposed properly, no need to worry about that.
With the using statement, the object will be disposed of regardless of the completion path.
Further reading...
http://aspadvice.com/blogs/name/archive/2008/05/22/Return-Within-a-C_2300_-Using-Statement.aspx
http://csharpfeeds.com/post/8451/Return_Within_a_Csharp_Using_Statement.aspx
Take a look at your code in reflector after you compile it. You'll find that the compiler refactors the code to ensure that dispose is called on the stream.

Any side-effects using SqlParameterCollection.Clear Method?

I have this specific situation where I need to execute a stored procedure 3 times before I declare it failed. Why 3 times because to check if a job that was started earlier finished. I am going to ask a separate question for deciding if there is a better approach. But for now here is what I am doing.
mysqlparametersArray
do{
reader = MyStaticExecuteReader(query,mysqlparametersArray)
Read()
if(field(1)==true){
return field(2);
}
else{
//wait 1 sec
}
}while(field(1)==false);
MyStaticExecuteReader(query,mysqlparametersArray)
{
//declare command
//loop through mysqlparametersArray and add it to command
//ExecuteReader
return reader
}
Now this occasionally gave me this error:
The SqlParameter is already contained by another
SqlParameterCollection.
After doing some search I got this workaround to Clear the parameters collection so I did this:
MyStaticExecuteReader(query,mysqlparametersArray)
{
//declare command
//loop through mysqlparametersArray and add it to command Parameters Collection
//ExecuteReader
command.Parameters.Clear()
return reader
}
Now I am not getting that error.
Question: Is there any side-effect using .Clear() method above?
Note: Above is a sample pseudo code. I actually execute reader and create parameters collection in a separate method in DAL class which is used by others too. So I am not sure if making a check if parameters collection is empty or not before adding any parameters is a good way to go.
I have not ran into any side effects when I have used this method.
Aside from overhead or possibly breaking other code that is shared, there is no issue with clearing parameters.

ASP.NET :What advantage if i use using when creating an object

in ASP.NET, I have seen people coding like this
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
// Do the datatbase transactions
}
How does it differ from this one
SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString)
// Do the datatbase transactions
Is there any performance/speed improvements in using one over the other ?
The using statement allows the
programmer to specify when objects
that use resources should release
them. The object provided to the using
statement must implement the
IDisposable interface. This interface
provides the Dispose method, which
should release the object's resources.
A using statement can be exited either
when the end of the using statement is
reached or if an exception is thrown
and control leaves the statement block
before the end of the statement.
A good article can be found here
Understanding the 'using' statement in C#
It's just a shortcut. :)
using (var foo = new Foo())
foo.bar();
equals to:
Foo foo = new Foo();
try
{
foo.bar();
}
finally
{
if (foo != null)
((IDisposable)foo).Dispose();
}
using keyword ensures that object will be disposed (it must implement IDisposable).
It's useful when working with external resources (database connection, file streams etc.) - they will be released despite of errors that may occur.
Using: Defines a scope, outside of which an object or objects will be disposed.
So its just syntax instead of creating the object then disposing it.
More details on MSDN
objects created in the using construct have lifetime within the construct (the braces {}). And if you notice only those members which implement the IDisposable interface can only be created. It simply means that right after the using construct code the the compiler will automatically call the dispose method on the object you've created. It helps in garbage collection.
As in the case of SqlConnection objects we must call dispose otherwise the ado.net connection pool (which manages connections to database) will assign a new connection to another incoming request instead of reusing an old connection pool. Connection pooling is simply an inherent way to minimize the resources & time taken to acquire a connection to a database.
Refer:
Connection Pooling
IDisposable
using statement is a shortcut for
try
{
/* do the work here with obj */
}
finally
{
if (obj != null)
obj.Dispose();
}
In general, you should use the using syntax for any object that implements IDisposable - for example, SqlConnection.
The using statement ensures that the object is disposed correctly at the end of the block in (almost) all circumstances, even if exceptions occur.
There aren't any direct speed/performance differences either way, but if you don't dispose of your IDisposable objects (usually by using using) then you might encounter problems down the line because vital resources haven't been tidied up.
Using using is good practice and almost always the right way to do things. Not using using is usually a bad idea, unless you're absolutely certain of what you're doing and why.
the using statement would automatically call the finally, i.e once the using block is finished, it will dispose off the object.
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
// Do the datatbase transactions
}
is equivalent to:
SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString)
// Do the datatbase transactions
myConnection.Close();
myConnection.Dispose()

clone flex component

I am trying to duplicate a flex component at run time.
For example if i have this
mx:Button label="btn" id="btn" click="handleClick(event)"/>
i should be able to call a function called DuplicateComponent() and it should return me a UI component thts exactly same as above button including the event listeners with it.
Can some one help me please??
Thanks in advance
Do a Byte Array Copy. This code segment should do it for you:
// ActionScript file
import flash.utils.ByteArray;
private function clone(source:Object):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}
One note, I did not write this code myself, I'm pretty sure I got it from a post on the Flex Coder's list.
To solve that problem you should use actionscript and create the buttons dynamically.
Lets say you want the button(s) to go in a VBox called 'someVbox'
for (var i:uint = 0; i< 10; i++){
var but:Button = new Button();
but.label = 'some_id_'+i;
but.id = 'some_id_'+i;
but.addEventListener(MouseEvent.CLICK, 'handleClick');
someVbox.addChild(but);
}
I haven't tested it, but that should add 10 buttons to a vbox with a bit of luck.
You can't take a deep copy of UIComponents natively. You're best bet would be to create a new one and analyse the one you have to add a duplicate setup. To be honest this does sound like a bit of a code smell. I wonder if there may be a better solution to the problem with a bit of a rethink..
Same question as: http://www.flexforum.org/viewtopic.php?f=4&t=1421
Showing up in a google search for the same thing. So you've cut&pasted the same question a month later. No luck eh?
There is no easy way to do this that I know of. Many of a component's settings are dependent on the container/context/etc... and get instantiated during the creation process, so there's no reason to clone from that perspective.
You can clone key settings in actionscript and use those when creating new elements.
For instance, assuming you only care about properties, you might have an array ["styleName","width","height",...], and you can maybe use the array like this:
var newUI:UIComponent = new UIComponent();
for each(var s:String in propArray) {
newUI[s] = clonedUI[s];
}
If you want more bites on your question (rather than waiting a month), tell us what you are trying to achieve.
mx.utils.ObjectUtil often comes in handy, however for complex object types, it's typically good practice to implement an interface that requires a .clone() method, similar to how Events are cloned.
For example:
class MyClass implements ICanvasObject
{
...
public function clone():ICanvasObject
{
var obj:MyClass = new MyClass(parameters...);
return obj;
}
}
This gives your code more clarity and properly encapsulates concerns in the context of how the object is being used / cloned.
You are right but as per my understanding UI Components are not cloned by mx.utils.ObjectUtil.
from : http://livedocs.adobe.com/flex/201/langref/mx/utils/ObjectUtil.html#copy()
copy () method
public static function copy(value:Object):Object
Copies the specified Object and returns a reference to the copy. The copy is made using a native serialization technique. This means that custom serialization will be respected during the copy.
This method is designed for copying data objects, such as elements of a collection. It is not intended for copying a UIComponent object, such as a TextInput control. If you want to create copies of specific UIComponent objects, you can create a subclass of the component and implement a clone() method, or other method to perform the copy.
Parameters value:Object — Object that should be copied.
Returns Object — Copy of the specified Object

Actionscript - is it better to cast or create a new variable? Or does it matter at all?

I find that in my daily Flex/Flash work, I do this number a lot:
//Calling a function...
MyCustomObject(container.getChildAt(i)).mySpecialFunction();
The question is - is this the best way to do this? Should I do this:
//Calling a function
var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;
tempItem.mySpecialFunction();
It might be incidental but I'm just wondering if there is an "accepted" way or a preferred way to do this. The second option seems more readable but I wonder if it takes more of a performance hit to create a new variable. Or does it all come down to style and preference?
It's important to remember that there is a difference between explicit casting and using the as keyword. Casting throws an error when it fails, whereas the as keyword does not (it just returns null).
// a casting error
try {
var number:int = 666;
var urlreq:URLRequest = URLRequest( number );
} catch(e:TypeError) {
// TypeError: Error #1034: Type Coercion failed: cannot
// convert 666 to flash.net.URLRequest.
trace(e);
}
Whereas the as keyword fails silently:
var number:int = 666;
var urlreq:URLRequest = number as URLRequest;
trace(urlreq); // prints null to the debug pane
Personally, I bear these behaviours in mind when deciding method to use. Generally, I'd recommend casting explicitly, as you'll know exactly how/when a cast failed. Often, though, you might want to fail silently and continue.
It generally doesn't matter. Creating a var just creates a pointer to the object, so it's not using more memory or anything like that.
The second example is definitely more readable and debuggable and should thus be preferred.
The risk you run from creating temp vars is that you might delay or prevent garbage collection for that object. This generally isn't a problem when it's just a local var in a function; just keep scope in mind when you're creating vars and passing them around.
For in-depth on the subject, read Grant Skinner's series on resource management in AVM2:
http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html
for the second example you might want to test for the nullity to avoid a NullPointerException when invoking "mySpecialFunction", e.g.
var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;
if ( tempItem )
{
tempItem.mySpecialFunction();
}
I usually prefer the second approach but you have to remember that you can only use the as operator for casting "Date" and "Array" types.

Resources