Temporarily storing and re-setting a property value in C# - c#

When I'm writing tests in a specific code base, I often need set a static property before my newly added code, and re-set it back when leaving. Example
public void SomeMethod(){
val oldVal = Notifier.DoNotify;
Notifier.DoNotify = false;
// Some code...
Notifier.DoNotify = oldVal;
}
I think this way is ugly and I want something nicer and which also makes it harder forget to re-set the value.
I tried cooking something up and got this. I see some benefits, but it's a pretty talky solution.
public class ValueHolder<T> : IDisposable
{
private readonly Action<T> setter;
private readonly T oldVal;
public ValueHolder(Func<T> getter, T tempVal, Action<T> setter)
{
this.setter = setter;
oldVal = getter();
setter(tempVal);
}
public void Dispose()
{
setter(oldVal);
}
}
Which then is used like
public void SomeMethod(){
using(new ValueHolder<bool>(() => Notifier.DoNotify, false, (b) => Notifier.DoNotify(b)) {
// Do something ...
}
}
What is a good solution to this?
(Edit removed reference to testing. Seemed to distract from what I wanted to ask)

There's a couple things you can do to make it a little easier to write. I would try to leverage whatever testing framework you are using to help running some setup/cleanup code before and after the test. But barring that here some tips that can cut down on the boiler plate.
First we can create a helper class that will cut down a little on the boilerplate for creating a ValueHolder<T> instance. I'll use LINQ Expressions to create the getter and setter delegates automatically rather than requiring the caller pass in both a getter and setter (although that could still be useful in advanced cases).
public class ValueHolder
{
public static ValueHolder<T> Create<T>(Expression<Func<T>> staticProp, T tempVal)
{
var ex = (MemberExpression)staticProp.Body;
var prop = (PropertyInfo)ex.Member;
var getter = (Func<T>)Delegate.CreateDelegate(typeof(Func<T>), prop.GetGetMethod());
var setter = (Action<T>)Delegate.CreateDelegate(typeof(Action<T>), prop.GetSetMethod());
return new ValueHolder<T>(getter, tempVal, setter);
}
}
This makes the creation a little more terse
ValueHolder.Create(() => Notify.DoNotify, false);
Second, you will probably need to set a few of these and a big using is kind of ugly. My answer to this question provides a way to handle this scenario in a slightly easier way using a class that inherits from List<T> which is also IDisposable. Combining these you could make your setup much simpler:
public void SomeTestMethod()
{
// before any state has change.
using (Setup())
{
// Test code.
}
// the cleanup code has run so the state is reset here.
}
private static IDisposable Setup()
{
return new DisposableList() {
ValueHolder.Create(() => Notify.DoNotify, false),
ValueHolder.Create(() => ConnectionManager.MaxConnections, 100),
ValueHolder.Create(() => SomeClass.SomeProp, 2.5),
// etc., I think you get the idea.
};
}

Related

Don't assign a field from many methods

I have a class that has a field that is being assigned a value from multiple methods.
public class Shape
{
private Point2D m_location;
public void Move()
{
m_location = ...
}
public void Rotate()
{
m_location = ...
}
public void Flip()
{
m_location = ...
}
}
I am getting a warning from NDepend that says:
Don't assign a field from many methods
https://www.ndepend.com/default-rules/Q_Don't_assign_a_field_from_many_methods.html
I am thinking of solving this problem by creating a separate method to assign the value of the field and calling this method from the other methods that currently assign a value to the field.
Here is an example of the code:
private void SetLocation(Point2D point)
{
m_location = location;
}
I want to know if this is a valid way to solve the problem and if it will just hide the code-smell that NDepend detected or actually fix the issue.
Is this a valid way to solve this problem?
No. As you suspect, this is a code smell. What NDepend is complaining about is mutable references; you have code where:
var s = new SomeObject(someInitialization);
var r = s.SomeResult();
// you now have no idea what s contains or if it is even usable any more.
The solution to this is to make SomeObject immutable and return new references instead of changing internals:
public SomeObject Something()
{
return new SomeObject(SomethingDifferentDependingOn(this.something));
}
Now instead of your first example you have:
var s = new SomeObject(someInitialization);
var r = s.Something().Result;
// s is guaranteed to be unchanged.
Yes some times you will need mutable references. In those cases; document them and explain why they have to be mutable. Then you can override NDepend rules on a case-by-case basis to prevent it showing a warning. If you have a code smell, warn people. Do not try to hide it.
The example after your edit is quite different, but the general principle still holds. If you have only a few internal fields that all change in method calls you can still return immutable references, e.g.:
public Shape Move()
{
return new Shape(m_location ...);
}
If you have many internal fields that don't all change, or you need to do something like share private fields you can't easily have immutable reference, but you can still avoid the warning by using accessors:
public Location
{
get { return m_location; }
private set { m_location = value; }
}
Then use Shape.Location exclusively in your internal methods.

How to reset delegate to original code

given this delegate
public class XYZ
{
public static Action<Profile> DoSomething = (profile) =>
{
//some default code here
return;
};
}
at some time in my main execution I override it with this:
XYZ.DoSomething = (currProfile) =>
{
// some overriding code here
}
How do I set the code back to the original default code when I need to without duplicating code?
Here's a good reason to never use public fields...
Once you set it; its gone. You can hold onto the original value though:
var originalAction = XYZ.DoSomething;
XYZ.DoSomething = ...;
XYZ.DoSomething = originalAction;
Usually it is a bad idea to rely on client code to handle this however; so if I was writing it I would expose as a property like so:
public Action<X> DoSomethingOverride {get; set;}
public Action<X> DoSomething => doSomethingOverride ?? DefaultMethod;
private void DefaultMethod (X param)
{
}
There are a number of other ways to handle this, but all involve storing off the original method. All good ways to handle this will use a property to ensure that only the declaring class is actually setting the DoSomething method and that resetting to the default is possible.
Total aside; since this is static setting the action will affect everything that uses this class. This is asking for bugs later; don't do that.
Maybe somthing like this?
public static Action<Profile> _doSomethingBase = (profile) =>
{
//some default code here
return;
};
public static Action<Profile> _doSomething = _doSomethingBase;
public static Action<Profile> DoSomething
{
get => _doSomething;
set => _doSomething = value;
}
public static void RevertDoSomething()
{
DoSomething = _doSomethingBase;
}

How can I avoid this deadlock in DevForce when using interceptors

We have recently started taking our business logic that relies heavily on DevForce and exposing it over a web API. We have been very careful to avoid threading issues by ensuring each request has its own set of entities, its own EntityManager, etc. However, we've started noticing logical deadlocks (in the .net code, not in SQL) when there are a lot of concurrent requests.
I've tracked down the problem to locking that is done by the PropertyInterceptors. We use them quite extensively and have cases where the interceptor on one property (Property A) will set another property (Property B) but that the converse is also true (setting B will also set A). The exact reasons for some of these cases are complicated but the basic idea is that we have some properties that we want to keep in sync. It seems that there is locking inside the PropertyInterceptor logic so we can easily hit deadlocks because the order in which those locks are taken can vary.
I've created a simple reproducible case below that involves an Entity with just two properties. One is an integer property and the other a string property. I have BeforeSet logic to keep these two in sync with each other. In the simple case of settings the properties one at a time, everything works. But since we are dealing with a web api, it's very common for things to execute in parallel. If we get one request that happens to set IntValue and another request that happens to set StringValue, we'll hit a deadlock. This is true even though we are talking about two different entities in two different EntityManagers. From our perspective, we are doing everything in a thread safe manner but then DevForce has some very long-lived locks which we know can be dangerous.
Here is the code which hopefully explains things. Keep in mind our actual code is much more complicated but the basic deadlock is the same:
public static void ReproduceDeadlock()
{
var e1 = new MyEntity();
var e2 = new MyEntity();
//This works - settings fields one at a time is fine
e1.IntValue = 1;
e2.StringValue = "2";
//But if we introduce some concurrency, we'll become deadlocked
Task.Run(() =>
{
//Wait a bit so e1.IntValue has a chance to start
Thread.Sleep(1000);
e2.StringValue = "22";
});
e1.IntValue = 11;
//Execution will never make it hear...setting the IntValue will never complete
}
public class MyEntity : Entity
{
[BeforeSet("StringValue")]
public void BeforeSetStringValue(PropertyInterceptorArgs<MyEntity, string> args)
{
//When the string is set, 'sync' it to the IntValue property
IntValue = int.Parse(args.Value);
}
[BeforeSet("IntValue")]
public void BeforeSetIntValue(PropertyInterceptorArgs<MyEntity, int> args)
{
//When the int is set, 'sync' it to the StringValue property
//Introduce a delay so the deadlock will obviously happen. In our real app, we don't have
// a Thread.Sleep() but we do have non-trivial logic that can cause just enough delay for the deadlock
// to happen sometimes
Thread.Sleep(2000);
StringValue = args.Value.ToString();
}
#region PropertyMetadata stuff
public class PropertyMetadata
{
public static readonly DataEntityProperty<MyEntity, string> StringValue =
new DataEntityProperty<MyEntity, string>("StringValue", true, false,
ConcurrencyStrategy.None, false, null,
false);
public static readonly DataEntityProperty<MyEntity, int> IntValue =
new DataEntityProperty<MyEntity, int>("IntValue", true, false,
ConcurrencyStrategy.None, false, null,
false);
}
public string StringValue
{
get { return PropertyMetadata.StringValue.GetValue(this); }
set { PropertyMetadata.StringValue.SetValue(this, value); }
}
public int IntValue
{
get { return PropertyMetadata.IntValue.GetValue(this); }
set { PropertyMetadata.IntValue.SetValue(this, value); }
}
#endregion
}
}
Stephen, maybe I do have a workaround for you. In the interceptor actions you can use SetValueRaw to sync the value to another property and avoid going through its interceptor (and validation). The method is available on the public IStructuralObject interface, which, although documented as for internal use only, is not something we plan to change. Both the EntityAspect and ComplexAspect classes implement this interface.
So your example would look like this:
[BeforeSet("StringValue")]
public void BeforeSetStringValue(PropertyInterceptorArgs<MyEntity, string> args)
{
//When the string is set, 'sync' it to the IntValue property
(this.EntityAspect as IStructuralObject).SetValueRaw(PropertyMetadata.IntValue, int.Parse(args.Value));
}
[BeforeSet("IntValue")]
public void BeforeSetIntValue(PropertyInterceptorArgs<MyEntity, int> args)
{
//When the int is set, 'sync' it to the StringValue property
//Introduce a delay so the deadlock will obviously happen. In our real app, we don't have
// a Thread.Sleep() but we do have non-trivial logic that can cause just enough delay for the deadlock
// to happen sometimes
Thread.Sleep(2000);
(this.EntityAspect as IStructuralObject).SetValueRaw(PropertyMetadata.StringValue, args.Value.ToString());
}
I'll note one other workaround too. The deadlock is in the interceptor, but you can have all the usual validation logic and change notification occur, just without the interception layer. One way to do this is to set the EntityGroup.PropertyInterceptionEnabled flag to false, but it's usually pretty clumsy to turn this on and off. Another option is a helper function to do exactly what the SetterInterceptor is doing:
public static void SetValueWithVerification(IStructuralObject so, DataEntityProperty property, object newValue)
{
if (so.VerifierEngine != null && so.VerifierEngine.Enabled && so.EntityGroup.VerificationEnabled)
{
if ((property.MemberMetadata.VerifierSetterOptions & VerifierSetterOptions.BeforeSet) > 0)
{
so.ValidatePropertyBeforeSet(property, newValue);
}
so.SetValueWithChangeNotification(property, newValue);
if ((property.MemberMetadata.VerifierSetterOptions & VerifierSetterOptions.AfterSet) > 0)
{
so.ValidatePropertyAfterSet(property, newValue);
}
}
else
{
so.SetValueWithChangeNotification(property, newValue);
}
}
Then call this in these tightly coupled interceptor actions:
SetValueWithVerification(this.EntityAspect, PropertyMetadata.StringValue, args.Value.ToString());

Can AutoFixture execute a delegate at object creation time?

I'm looking to customize the creation-time behavior of AutoFixture such that I can set up some dependent objects after the properties of the fixture have been generated and assigned.
For example, suppose I have a method that customizes a User because its IsDeleted property always has to be false for a certain set of tests:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsDeleted { get; set; }
}
public static ObjectBuilder<User> BuildUser(this Fixture f)
{
return f.Build<User>().With(u => u.IsDeleted, false);
}
(I hand an ObjectBuilder back to the test so it can further customize the fixture if necessary.)
What I'd like to do is automatically associate that user with an anonymous collection by its Id at creation time, but I can't do this as-is because Id has not been generated by the time I hand the return value back to the unit test proper. Here's the sort of thing I'm trying to do:
public static ObjectBuilder<User> BuildUserIn(this Fixture f, UserCollection uc)
{
return f.Build<User>()
.With(u => u.IsDeleted, false);
.AfterCreation(u =>
{
var relation = f.Build<UserCollectionMembership>()
.With(ucm => ucm.UserCollectionId, uc.Id)
.With(ucm => ucm.UserId, u.Id)
.CreateAnonymous();
Repository.Install(relation);
}
}
Is something like this possible? Or perhaps there is a better way to accomplish my goal of creating an anonymous object graph?
For the Build method, this isn't possible, and probably never will be, because there are much better options available.
First of all, it should never be necessary to write static helper methods around the Build method. The Build method is for truly one-off initializations where one needs to define property or field values before the fact.
I.e. imagine a class like this:
public class MyClass
{
private string txt;
public string SomeWeirdText
{
get { return this.txt; }
set
{
if (value != "bar")
throw new ArgumentException();
this.txt = value;
}
}
}
In this (contrived) example, a straight fixture.CreateAnonymous<MyClass> is going to throw because it's going to attempt to assign something other than "bar" to the property.
In a one-off scenario, one can use the Build method to escape this problem. One example is simply to set the value explicitly to "bar":
var mc =
fixture.Build<MyClass>().With(x => x.SomeWeirdText, "bar").CreateAnonymous();
However, even easier would be to just omit that property:
var mc =
fixture.Build<MyClass>().Without(x => x.SomeWeirdText).CreateAnonymous();
However, once you start wanting to do this repeatedly, there are better options. AutoFixture has a very sophisticated and customizable engine for defining how things get created.
As a start, one could start by moving the omission of the property into a customization, like this:
fixture.Customize<MyClass>(c => c.Without(x => x.SomeWeirdText));
Now, whenever the fixture creates an instance of MyClass, it's just going to skip that property altogether. You can still assign a value afterwards:
var mc = fixture.CreateAnonymous<MyClass>();
my.SomeWeirdText = "bar";
If you want something more sophisticated, you can implement a custom ISpecimenBuilder. If you want to run some custom code after the instance has been created, you can decorate your own ISpecimenBuilder with a Postprocessor and supply a delegate. That might look something like this:
fixture.Customizations.Add(
new Postprocessor(yourCustomSpecimenBuilder, obj =>
{ */ do something to obj here */ }));
(BTW, are you still on AutoFixture 1.0? IIRC, there hasn't been an ObjectBuilder<T> around since then...)
There's a useful discussion on this topic on the AutoFixture CodePlex site.
I believe my postprocessor Customization linked over there should help you. Example usage:
class AutoControllerDataAttribute : AutoDataAttribute
{
public AutoControllerDataAttribute()
: this( new Fixture() )
{
}
public AutoControllerDataAttribute( IFixture fixture )
: base( fixture )
{
fixture.Customize( new AutoMoqCustomization() );
fixture.Customize( new ApplyControllerContextCustomization() );
}
class ApplyControllerContextCustomization : PostProcessWhereIsACustomization<Controller>
{
public ApplyControllerContextCustomization()
: base( PostProcess )
{
}
static void PostProcess( Controller controller )
{
controller.FakeControllerContext();
// etc. - add stuff you want to happen after the instance has been created

Best way of protect a backing field from mistaken use in C#

I have a class (Foo) which lazy loads a property named (Bar). What is your preferred way to protect against mistaken use (due to intellisense or inexperienced staff) of the uninitialized backing field?
I can think of 3 options:
class Foo {
// option 1 - Easy to use this.bar by mistake.
string bar;
string Bar {
get {
// logic to lazy load bar
return bar;
}
}
// option 2 - Harder to use this._bar by mistake. It is more obscure.
string _bar2;
string Bar2 {
get {
// logic to lazy load bar2
return _bar2;
}
}
//option 3 - Very hard to use the backing field by mistake.
class BackingFields {
public string bar;
}
BackingFields fields = new BackingFields();
string Bar3 {
get {
// logic to lazy load bar
return fields.bar;
}
}
}
Keep in mind, the only place I want people mucking around with the backing field bar is in setter and getter of the property. Everywhere else in the class they should always use this.Bar
Update
I am currently using the following Lazy implementation (not for all properties with backing fields, but for select ones that require lazy loading, synchronization and notification). It could be extended to support futures as well (force evaluation in a separate thread in a later time)
Note My implementation locks on read, cause it supports an external set.
Also, I would like to mention that I think this is a language limitation which can be overcome in Ruby for example.
You can implement lazy in this way.
x = lazy do
puts "<<< Evaluating lazy value >>>"
"lazy value"
end
puts x
# <<< Evaluating lazy value >>>
# lazy value
How about use of ObsoleteAttribute and #pragma - hard to miss it then!
void Test1()
{
_prop = ""; // warning given
}
public string Prop
{
#pragma warning disable 0618
get { return _prop; }
set { _prop = value; }
#pragma warning restore 0618
}
[Obsolete("This is the backing field for lazy data; do not use!!")]
private string _prop;
void Test2()
{
_prop = ""; // warning given
}
Option 5
Lazy<T>
works quite nicely in several situations, though option 1 should really be just fine for most projects so long as the developers aren't idiots.
Adding [EditorBrowsable(EditorBrowsableState.Never)] to the field won't help if it is private since this logic only kicks in for intellisense generated from metadata rather than the current code (current project and anything done via project references rather than dlls).
Note: Lazy<T> is not thread safe (this is good, there's no point locking if you don't need to) if you require thread safety either use one of the thread safe ones from Joe Duffy or the Parallel Exetensions CTP
I usually go for option 2, as it is easier to spot mistakes later on, although option 1 would pass a code review. Option 3 seems convoluted and whilst it may work, it's not going to be nice code to revisit 6 months down the line whilst trying to refactor/fix a bug/etc.
Option 1, coupled with some education.
Rationale: software is meant to be read more often than written, so optimize for the common case and keep it readable.
Code reviews will catch misuse so just go with the most readable. I dislike attempts to work around bad programmers in code, because 1) they don't work, 2) they make it harder for smart programmers to get their work done, and 3) it addresses the symptom rather than the cause of the problem.
I usually just go for option 1. Because it is a private field I don't think it really an issue, and using something like the wrapper class as in your option 3 only makes code difficult to read and understand.
I would just put a large comment block on the top of the class that would look like that:
/************************************************************
* Note: When updating this class, please take care of using *
* only the accessors to access member data because of *
* ... (state the reasons / your name, so they can ask *
* questions) *
*************************************************************/
Usually, just a note like that should be enough, but if this is the same for all the classes in the project, you might prefer to put it in a simple document that you give to programmers working on the project, and everytime you see code that isn't conform, you point them to the document.
Automatic properties:
public int PropertyName { get; set; }
will prevent access to the backing field. But if you want to put code in there (e.g. for lazy loading on first access) this clearly won't help.
The simplest route is likely to be a helper type which does the lazy loading, and have an private field of that type, with the public property calling to the correct property/method of the helper type.
E.g.
public class Foo {
private class LazyLoader {
private someType theValue;
public someType Value {
get {
// Do lazy load
return theValue;
}
}
}
private LazyLoader theValue;
public someType {
get { return theValue.Value; }
}
}
This has the advantage that the backing field is harder to use than the property.
(Another case of an extra level of indirection to solve problems.)
// option 4
class Foo
{
public int PublicProperty { get; set; }
public int PrivateSetter { get; private set; }
}
C# 3.0 feature, the compiler will generate anonymous private backing fields which can't be accessed by mistake, well unless you use reflection...
EDIT: Lazy instantiation
You can have laziness like this:
// I changed this with respect to ShuggyCoUk's answer (Kudos!)
class LazyEval<T>
{
T value;
Func<T> eval;
public LazyEval(Func<T> eval) { this.eval = eval; }
public T Eval()
{
if (eval == null)
return value;
value = eval();
eval = null;
return value;
}
public static implicit operator T(LazyEval<T> lazy) // maybe explicit
{
return lazy.Eval();
}
public static implicit operator LazyEval<T>(Func<T> eval)
{
return new LazyEval(eval);
}
}
Those implicit conversion make the syntax tidy...
// option 5
class Foo
{
public LazyEval<MyClass> LazyProperty { get; private set; }
public Foo()
{
LazyProperty = () => new MyClass();
}
}
And closures can be used to carry scope:
// option 5
class Foo
{
public int PublicProperty { get; private set; }
public LazyEval<int> LazyProperty { get; private set; }
public Foo()
{
LazyProperty = () => this.PublicProperty;
}
public void DoStuff()
{
var lazy = LazyProperty; // type is inferred as LazyEval`1, no eval
PublicProperty = 7;
int i = lazy; // same as lazy.Eval()
Console.WriteLine(i); // WriteLine(7)
}
}
Currently, I'm in a similar situation.
I have a field which should only be used by its property accessor.
I can't use automatic properties, since I need to perform additional logic when the property is set. (The property is not lazy loaded as well).
Wouldn't it be great if a next version of C# would allow something like this:
public class MyClass
{
public int MyProperty
{
int _backingField;
get
{
return _backingField;
}
set
{
if( _backingField != value )
{
_backingField = value;
// Additional logic
...
}
}
}
}
With such construct, the _backingField variable's scope is limited to the property.
I would like to see a similar language construction in a next version of C# :)
But, I'm afraid this feature will never be implemented:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=381625
This might be overly simple, but why not abstract all the lazy to a base class
public class LazyFoo{
private string bar;
public string Bar{
get{
// lazy load and return
}
set {
// set
}
}
}
public class Foo : LazyFoo{
// only access the public properties here
}
I could see the argument that it is unnecessary abstraction, but it is the simplest way I can see to eliminate all access to backing fields.
This seems like trying to design-out mistakes that might not happen in the first place, and basically it's worrying about the wrong thing.
I would go with option 1 + comments:
///<summary>use Bar property instead</summary>
string bar;
///<summary>Lazy gets the value of Bar and stores it in bar</summary>
string Bar {
get {
// logic to lazy load bar
return bar;
}
}
If you do get a developer who keeps using the backing variable then I'd worry about their technical competence.
By all means design to make your code easier to maintain, but try to keep it simple - any rule that you make for yourself here is going to be more hassle than it's worth.
And if you're still really worried about it create an FxCop (or whatever you're using) rule to check for this sort of thing.
Option 6:
Makes it very dumb indeed if you use it.
string doNotUseThisBackingField_bar6;
string Bar6 {
get {
// logic to lazy load
return doNotUseThisBackingField_bar6;
}
}
Option 4 (a new solution):
See if the question is really about how to prevent people from using an uninitialized variable then init it with an KNOWN INVALID value.
I would say something like:
string str = "SOMETHING_WRONG_HERE";
Who ever is using 'str' will have some sort of warning.
Otherwise Option 3 if preventing users from using 'str' is more important than readability etc.

Categories