Why would you use the using statement this way in ASP.NET? - c#

Refactoring some code again. Seeing some of this in one of the ASP.NET pages:
using (TextBox txtBox = e.Row.Cells[1].FindControl("txtBox") as TextBox)
{
}
There is no need to dispose txtBox, because it's just a reference to an existing control. And you don't want the control disposed at all. I'm not even sure this isn't harmful - like it would appear to ask for the underlying control to be disposed inappropriately (although I have not yet seen any ill effects from it being used this way).

TextBox inherits its implementation of IDisposable from its Component superclass. That implementation removes the component from its site container if it has one.
So, doing that might have nefarious effects if the text box actually resides in a site container. Also, after calling Dispose() on an object, you should not use it again, no matter what (it's not in a usable state anymore).
I'd suggest you avoid that pattern with ASP.NET web controls.

This is wrong, it shouldnt be used like this. I would imagine there are potential problems using this that wont show up immediately. The textboxes dispose is called upon leaving the using statement but it wont be garbage collected immediately. If it is collected then you will have problems later when you try to access that control.

The TextBox instance could potentially be null if not found, so Dispose() is called a NullReferenceException would be thrown.
I've never seen that pattern in practice, but if you need to use it, it'd be worth handling any potential errors.

There should be no negative secondary effects, but it's not necessary either. If we did using (x) { ... } on everything that implements IDisposable in the CLR most C# code would be unreadable.

Actually, here the TextBox instance is accessible only to the context inside the brackets of using statement, maybe that was the main reason of using it.

From MSDN:
Within the using block, the object
is read-only and cannot be modified
or reassigned.
So I guess you can only read the textbox properties, but not change them, inside the using block.

Related

C# - How to guarantee that a properties remains Get only over time?

I'm implementing a piece of sensitive software and I can see a possible "failure point"/"security leak" IF in the future someone sticks a public set on a specific property.
Besides the obvious //Do not make this property set operator public because of XYZ are there other safeguards I can put in place to prevent such misguided change?
I don't know your exact design but as I understand from the comments, you're using property to return a resource that needs to be discarded properly with using. If somebody else sets the property the handle to the IDispoable is lost, so it's up to the GC's mercy to dispose it.
Don't use properties to return IDisposable's (or any other resource type hat needs to be explicitly disposed). Use a method instead. That way, the object reference wouldn't be cached in the class, but in the caller. So, caller would be responsible of disposing it. This prevents adding any other code to change the instance in your class, because caching isn't done there anymore.
You can only direct developers to the right direction with a design that describes its intent clearly.

ASP.Net C# Active Directory: Inherited an application with thread.sleep() after each DirectoryEntry.MoveTo() calls

So I'm working on this application that was developed by other people that are not involved with the project anymore. As stated in the title there are a few thread.sleep() calls that have me scratching my head. I have no experience working with AD.
The worst offender is the following one with a 50 second sleep in a class that inherits Principle.
public class Computer:ComputerPrinciple
{
...
public void MoveToOu(string ou)
{
var userObject = (DirectoryEntry)GetUnderlyingObject();
var newParentOu = new DirectoryEntry("LDAP://" + ou);
userObject.MoveTo(newParentOu);
Thread.Sleep(50000);
userObject.Close();
newParentOu.Close();
}
...
}
There is nothing that explains the reason but I suspect it was an issue with the page refreshing before the changes were fully committed (?). One thing I'm pretty sure of is that Thread.Sleep(50000) is not the correct solution to whatever problem they we're having.
I'd like to hear from people who have experience with this if there is indeed some sort of issue that this would "fix" and what would be the incorporate solution.
Also I'm thinking I should use the "using" directive but I'm wondering about disposing the UnderlyingObject or even just closing it because this code is called from something like this where computer is the principle in witch the move code is
computer.UpdateComputerDescription(collection);
computer.UpdateComputerOu(collection); <--- offending MoveToOu method is called in here
computer.UpdateComputerIsActivedProperty(collection);
computer.Save();
Would closing or disposing of the underlyingObject have a side effect on the methods after that call?
Any input would be welcome.
This use of Thread.Sleep is likely a workaround for not calling CommitChanges.
From documentation
If UsePropertyCache is true, call the CommitChanges method on the new object to make the move permanent
It looks like they were waiting for the cache to flush using an empirical delay.
Second, wrapping any IDisposable you create inside MoveToOu in using will not break anything. It is the correct way to go. Objects used, but not created, inside MoveToOu scope should not be disposed here, but rather be left to the container class dispose mechanism.

How to make the JIT extend stack variables to the end of scope (GC is too quick)

We're dealing with the GC being too quick in a .Net program.
Because we use a class with native resources and we do not call GC.KeepAlive(), the GC collects the object before the Native access ends. As a result the program crashes.
We have exactly the problem as described here:
Does the .NET garbage collector perform predictive analysis of code?
Like so:
{ var img = new ImageWithNativePtr();
IntPtr p = img.GetData();
// DANGER!
ProcessData(p);
}
The point is: The JIT generates information that shows the GC that img is not used at the point when GetData() runs. If a GC-Thread comes at the right time, it collects img and the program crashes. One can solve this by appending GC.KeepAlive(img);
Unfortunately there is already too much code written (at too many places) to rectify the issue easily.
Therefore: Is there for example an Attribute (i.e. for ImageWithNativePtr) to make the JIT behave like in a Debug build? In a Debug build, the variable img will remain valid until the end of the scope ( } ), while in Release it looses validity at the comment DANGER.
To the best of my knowledge there is no way to control jitter's behavior based on what types a method references. You might be able to attribute the method itself, but that won't fill your order. This being so, you should bite the bullet and rewrite the code. GC.KeepAlive is one option. Another is to make GetData return a safe handle which will contain a reference to the object, and have ProcessData accept the handle instead of IntPtr — that's good practice anyway. GC will then keep the safe handle around until the method returns. If most of your code has var instead of IntPtr as in your code fragment, you might even get away without modifying each method.
You have a few options.
(Requires work, more correct) - Implement IDisposable on your ImageWithNativePtr class as it compiles down to try { ... } finally { object.Dispose() }, which will keep the object alive provided you update your code with usings. You can ease the pain of doing this by installing something like CodeRush (even the free Xpress supports this) - which supports creating using blocks.
(Easier, not correct, more complicated build) - Use Post Sharp or Mono.Cecil and create your own attribute. Typically this attribute would cause GC.KeepAlive() to be inserted into these methods.
The CLR has nothing built in for this functionality.
I believe you can emulate what you want with a container that implements IDispose, and a using statement. The using statement allows for defining the scope and you can place anything you want in it that needs to be alive over that scope. This can be a helpful mechanism if you have no control over the implementation of ImageWithNativePtr.
The container of things to dispose is a useful idiom. Particularly when you really should be disposing of something ... which is probably the case with an image.
using(var keepAliveContainer = new KeepAliveContainer())
{
var img = new ImageWithNativePtr();
keepAliveContainer.Add(img);
IntPtr p = img.GetData();
ProcessData(p);
// anything added to the container is still referenced here.
}

Common uses for the Tag property

I've started using this alot to link elements of my UI to their data backing class (whatever that might be). What are some of the common uses you put the Tag property to use for?
Indeed, do you use it at all? I know I didn't for a very long time.
Just as you describe, the most frequent use of the Tag property I have come across and use in both WinForms, WPF and Silverlight is to indicate the real data that the control relates to. This is especially useful on ListViewItem instances or auto-generated user interface where you want to use the same event handler for multiple objects where only the target data is different (i.e. the action to be performed remains the same).
However, I have also used the Tag to store an enumeration value (though you should avoid value types as it would cause boxing when assigning the value to the Tag property) or a string that is then used to determine the action that needs to be performed instead of the data on which to perform it, and in one particular usage, I stored a delegate so that I could auto-generate some buttons and embed their handlers in the Tag (the handler information was supplied in a data driven manner).
I am sure there are many other ways to use Tag and many other ways to replace the uses of Tag with something more strongly typed, but that's how I've used it.
The Tag property is an ancient (in programming language terms) hold over for controls. To my knowledge, it's been used in everything from visual basic, delphi, and pretty much any other gui based language.
It is simply an extra property that allows you to add a numeric value for any reason you want to the control.
I've seen it used for everything from a counter to holding a record id that the control is tied to.
It is a bit of a kludge. It is often used in for instance a TreeView to link a Node to a data element.
But I would not over-use it, since it is very public and not very flexible. Note that you can almost always use a Dictionary< Control, ValueType> instead, and have a lot more control that way.
I use it all the time with ListViews and TreeViews. It makes trying to find the underlying data much easier. In fact, I'm not sure how you'd make a readable Winforms application without it.
I also use it a lot when creating ContextMenus at run-time. I stuff an object into the Tag member of each ToolStripMenuItem and then I can point each menu item's click handler at the same method. It results in a lot less code.
I just wish it didn't require so much casting.

Should you use accessor properties from within the class, or just from outside of the class? [duplicate]

This question already has answers here:
What is the best way to access properties from the same class, via accessors or directly? [closed]
(5 answers)
Closed 9 years ago.
I have a class 'Data' that uses a getter to access some array. If the array is null, then I want Data to access the file, fill up the array, and then return the specific value.
Now here's my question:
When creating getters and setters should you also use those same accessor properties as your way of accessing that array (in this case)? Or should you just access the array directly?
The problem I am having using the accessors from within the class is that I get infinite loops as the calling class looks for some info in Data.array, the getter finds the array null so goes to get it from the file, and that function ends up calling the getter again from within Data, array is once again null, and we're stuck in an infinite loop.
EDIT:
So is there no official stance on this? I see the wisdom in not using Accessors with file access in them, but some of you are saying to always use accessors from within a class, and others are saying to never use accessors from with the class............................................
I agree with krosenvold, and want to generalize his advice a bit:
Do not use Property getters and setters for expensive operations, like reading a file or accessing the network. Use explicit function calls for the expensive operations.
Generally, users of the class will not expect that a simple property retrieval or assignment may take a lot of time.
This is also recommended in Microsoft's Framework Design Guidelines.;
Do use a method, rather than a
property, in the following situations.
The operation is orders of magnitude
slower than a field set would be. If
you are even considering providing an
asynchronous version of an operation
to avoid blocking the thread, it is
very likely that the operation is too
expensive to be a property. In
particular, operations that access the
network or the file system (other than
once for initialization) should most
likely be methods, not properties.
I think its a good idea to always use the accessors. Then if you need any special logic when getting or setting the property, you know that everything is performing that logic.
Can you post the getter and setter for one of these properties? Maybe we can help debug it.
I have written a getter that opens a file and always regretted it later. Nowdays I would never solve that problem by lazy-constructing through the getter - period. There's the issue of getters with side-effects where people don't expect all kinds of crazy activity to be going on behind the getter. Furthermore you probably have to ensure thread safety, which can further pollute this code. Unit-Testing can also become slightly harder each time you do this.
Explicit construction is a much better solution than all sorts of lazy-init getters. It may be because I'm using DI frameworks that give me all of this as part of the standard usage patterns. I really try to treat construction logic as distinctly as possible and not hide too much, it makes code easier to understand.
No. I don't believe you should, the reason: maintainable code.
I've seen people use properties within the defining class and at first all looks well. Then someone else comes along and adds features to the properties, then someone else comes along and tries to change the class, they don't fully understand the class and all hell breaks loose.
It shouldn't because maintenance teams should fully understand what they are trying to change but they are often looking at a different problem or error and the encapsulated property often escapes them. I've see this a lot and so never use properties internally.
They can also be a performance hog, what should be a simple lookup can turn nasty if someone puts database code in the properties - and I have seen people do that too!
The KISS principle is still valid after all these years...!
Aside from the point made by others, whether to use an accessor or a field directly may need to be informed by semantics. Some times the semantics of an external consumer accessing a property is different from the mechanical necessity of accessing its value by internal code.
Eric Lippert recently blogged on this subject in a couple of posts:-
automatic-vs-explicit-properties
future-proofing-a-design
If using an Get method leads to this kind of error, you should access the value directly. Otherwise, it is good practice to use your accessors. If you should modify either the getter or setter to take specific actions in the future, you'll break your object if you fail to use that path.
I guess what you are trying to implement is some sort of a lazy-loading property, where you load the data only when it is accessed for the first time.
In such a case I would use the following approach to prevent the infinite loop:
private MyData _data = null;
public MyData Data
{
get
{
if (_data == null)
_data = LoadDataFromFile();
return _data;
}
}
private MyData LoadDataFromFile()
{
// ...
}
In other words:
don't implement a setter
always use the property to access the data (never use the field directly)
You should always use the accessors, but the function that reads the value from the file (which should be private, and called something like getValueFromFile) should only be called when the value has to be read from the file, and should just read the file and return the value(s). That function might even be better off in another class, dedicated to reading values from your data file.
If I am understanding it right, you are trying to access a property from within it's implementation (by using a method that calls the same property in the property's implementation code). I am not sure if there any official standards regarding this, but I would consider it a bad practice, unless there would be a specific need to do it.
I always prefer using private members within a class instead of properties, unless I need the functionality property implementation provides.

Categories

Resources