OmitAutoProperties affects non auto property - autofixture

I have a class that has property like this
public string Foo
{
get { return _foo; }
set
{
if (!string.Equals(_foo, value))
{
_foo= value;
OnPropertyChanged();
}
}
}
When I create object with _fixture = new Fixture {OmitAutoProperties = true};, I expect it has value but it's null and setter never hit. Do I miss something?

This is by design. As the documentation states:
Gets or sets if writable properties should generally be assigned a value when generating an anonymous object.
In other words, in AutoFixture, the term auto-property refers the the feature of AutoFixture that automatically populates writable properties. Perhaps a better word would have been DoNotAutomaticallyPopulateProperties.
I can understand the confusion, as in C#, auto-property can also be interpreted as meaning Auto-Implemented Properties.
Frankly, AutoFixture's terminology should, perhaps, have been chosen with greater care, but in all these years, I don't think this has ever been brought to my attention before.
Specifically in the OP Foo is a writable property, and when you disable auto-properties, the setter is never invoked.

The OmitAutoProperties setting determines if a writable property should be set or not:
Gets or sets if writable properties should generally be assigned a value when generating an anonymous object.
So, if it's true, AutoFixture does not try to set any property values and that is by design.

Related

Why can't I remove elements from an Array in its willSet event?

The logic is to clear an Array when it has a specified amount of elements. I could put the check outside of the Array but I was trying to see what if do it in Array's willSet event. The result is elements in Array stay still.
Here is the code
var MyArr=[String]() {
willSet{
print("now count is:\(MyArr.count)")
if MyArr.count>2 {
print("now remove all!")
MyArr.removeAll()
}
}
}
MyArr.append("hello")
MyArr.append(",world")
MyArr.append("!")
MyArr.append("too much.")
print("The conent is \(MyArr)")
MyArr was expected to have only one elements while actual result was four.
The behavior has nothing to do with value type / reference type
Please note the warning
Attempting to store to property 'MyArr' within its own willSet, which is about to be overwritten by the new value
which means that modifying the object in willSet has no effect.
Citing the Language Guide - Properties - Property Observers [emphasis mine]:
Property Observers
Property observers observe and respond to changes in a property’s
value.
...
You have the option to define either or both of these observers on a
property:
willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.
As you are experimenting with the willSet property observer, any mutation of the property you are observing within the willSet block precedes the actual storing of the newValue which follows immediately after the willSet block. This means you are essentially attempting to mutate "the old copy" of myArr prior to it being replaced with its new value.
Arguably this could be discussed as something illegal, as any mutation of myArr should lead to the invocation of any property observers, thus mutation of a property within a property observer (mutation of the reference for reference types or the value for value types) could arguably lead to recursive calls to the property observer. This is not the case, however, and for the willSet case, specifically, instead a warning is emitted, as pointed out in #vadian's answer. The fact that mutation of the property itself within a property observer will not trigger property observers is not really well-documented, but an example in the Language Guide - Properties - Type Properties points it out [emphasis mine]:
Querying and Setting Type Properties
...
The currentLevel property has a didSet property observer to check
the value of currentLevel whenever it is set. ...
NOTE
In the first of these two checks, the didSet observer sets
currentLevel to a different value. This does not, however, cause
the observer to be called again.
This is also a special case we can somewhat expect, as e.g. didSet is an excellent place to incorporate e.g. bounds checks that clamps a given property value to some bounds; i.e., over-writing the new value by a bounded one in case the former is out of bounds.
Now, if you change to mutate the property to after the new value has been stored, the mutation will take affect and, as covered above, not trigger any additional calls to the property observers. Applied to your example:
var myArr = [String]() {
didSet {
print("now count is: \(myArr.count)")
if myArr.count > 2 {
print("now remove all!")
myArr.removeAll()
}
}
}
myArr.append("hello")
myArr.append(",world")
myArr.append("!")
myArr.append("too much.")
print("The content is \(myArr)") // The content is ["too much."]
aAlan's comment on didSet vs willSet is interesting. I tried the same code but with didSet and it did remove the elements from the array which seemed odd initially. I think it's by design. My reasoning is:
if you actually did get a reference to the actual item itself inside willSet and made changes then everything would get overwritten. It makes all your changes nullified. Because you're doing this before you even read what's about to happen. Also (repeating what dfri has said) if you set it again inside willSet well then you're going to trigger the property observer again and again and will create a feedback loop which will crash the compiler, hence the compiler behind the scene creates a copy avoiding all this... will just suppress this mutation ie it won't allow it. It won't create a copy...simply put it would just ignore it. It does that by throwing a vague (because it doesn't really tell you that it will ignore the changes) warning:
same is not true with didSet. You wait...read the value and then make your decision. The value of the property is known to you.

Difference between CoreceValueCallback and ValidateValueCallback?

I know that CoerceValueCallback is used to correct a value and that ValidateValueCallback will return true or false. But my question is why we need ValidatevalueCallback? We can simply use CoerceValueCallback to validate (using if condition) and correct the value. Can you give some practical example of when to use coercion vs. validation?
Here are the rules I follow for when to use coercion vs. validation.
Use CoerceValueCallback If...
You can safely correct a value to be valid without needing to throw an error.
Your property depends on one or more other dependency properties.
You need to provide instance-level validation as opposed to class-level validation.
You allow others to override your validation logic.
Use ValidateValueCallback If...
You cannot correct a value to be valid.
You must throw an error if an invalid value is provided.
You do not want others to override your validation logic.
So, it primarily depends on whether or not your property depends on other dependency properties or if you want others to be able to override your validation logic.
Since the ValidateValueCallback is not part of the PropertyMetadata, inheritors cannot modify the callback through the DependencyProperty.OverrideMetadata function.
Also, since the ValidateValueCallback does not provide your DependencyObject as a parameter, you cannot perform advanced validation that depends on other dependency properties.
Example 1
Suppose you have Minimum, Maximum, & Value properties. When any of these change, a CoerceValueCallback shoud be used to ensure the other properties are consistent.That is, Minmum <= Value <= Maximum.
However, assuming these values are doubles, then there are some values that would never make sense, namely Double.NaN, Double.PositiveInfinity, and Double.NegativeInfinity. Therefore, a ValidateValueCallback should be used to verify that the double values are normal, numeric values.
In fact, this is exactly how RangeBase works!
Example 2
Suppose you have a RegexTextBox control which takes a string containing a regular expression (call it RegexString). If a bad regular expression is provided, then what should be used instead? It might make sense to coerce it to be a null/empty value, rendering it useless; however, I suggest that this property be validated with a ValidateValueCallback. This is because any error is now thrown at compile-time when designing via the WPF designer.
For this property, there shouldn't be a CoerceValueCallback at all.
There is a whole lot of information describing how to use these callbacks.
I'd suggest taking a look at the MSDN article, Dependency Property Callbacks and Validation, for more in-depth knowledge.
Value coercion is basically to change the value, if the the new value is not as system expected. A best example is Slider control. A Slider has both Minimum and Maximum properties. Clearly, it would be a problem if the Maximum value were allowed to fall below the Minimum value. Value coercion is used to prevent this invalid state from occuring.
Validate value, is something that system will only check whether the given input is valid or not. It will throw Argument Exception if value is invalid (if we returned false for such value). For example, we have Age property, and it should be in range of 0 to 120. In case the new value is 500, the system may warn the user instead coercing it to some hardcoded value.
Any way both callbacks are optional and can be used based on the requirement.

MarkupExtension that uses a DataBinding value

I'm trying to create a WPF MarkupExtension class that provides translated text from my text translation class. The translation stuff works great, but requires a static method call with a text key to return the translated text. Like this:
ImportLabel.Text = Translator.Translate("import files");
// will be "Dateien importieren" in de or "Import files" in en
Its speciality is that it accepts a counting value to provide better wordings.
ImportLabel.Text = Translator.Translate("import n files", FileCount);
// will be "Import 7 files" or "Import 1 file"
Another example: If something takes yet 4 minutes, it's a different word than if it only takes one minute. If a text key "minutes" is defined as "Minuten" for any number and as "Minute" for a count of 1, the following method call will return the right word to use:
Translator.Translate("minutes", numberOfMinutes)
// will be "minute" if it's 1, and "minutes" for anything else
Now in a WPF application, there's a lot of XAML code and that contains lots of literal texts. To be able to translate them without getting nuts, I need a markup extension which I can pass my text key and that will return the translated text at runtime. This part is fairly easy. Create a class inheriting from MarkupExtension, add a constructor that accepts the text key as argument, store it in a private field, and let its ProvideValue method return a translation text for the stored key.
My real problem is this: How can I make my markup extension accept a counting value in such a way that it's data-bound and the translation text will update accordingly when the count value changes?
It should be used like this:
<TextBlock Text="{t:Translate 'import files', {Binding FileCount}}"/>
Whenever the binding value of FileCount changes, the TextBlock must receive a new text value to reflect the change and still provide a good wording.
I've found a similar-looking solution over there: http://blogs.microsoft.co.il/blogs/tomershamam/archive/2007/10/30/wpf-localization-on-the-fly-language-selection.aspx But as hard as I try to follow it, I can't understand what it does or why it even works. Everything seems to happen inside of WPF, the provided code only pushes it in the right direction but it's unclear how. I can't get my adaption of it to do anything useful.
I'm not sure whether it could be useful to let the translation language change at runtime. I think I'd need another level of bindings for that. To keep complexity low, I would not seek to do that until the basic version works.
At the moment there's no code I could show you. It's simply in a terrible state and the only thing it does is throwing exceptions, or not translating anything. Any simple examples are very welcome (if such thing exists in this case).
Nevermind, I finally found out how the referenced code works and could come up with a solution. Here's just a short explanation for the record.
<TextBlock Text="{t:Translate 'import files', {Binding FileCount}}"/>
This requires a class TranslateExtension, inherited from MarkupExtension, with a constructor accepting two parameters, one String and one Binding. Store both values in the instance. The classes' ProvideValue method then uses the binding it gets, adds a custom converter instance to it and returns the result from binding.ProvideValue, which is a BindingExpression instance IIRC.
public class TranslateExtension : MarkupExtension
{
public TranslateExtension(string key, Binding countBinding)
{
// Save arguments to properties
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
countBinding.Converter = new TranslateConverter(key);
return countBinding.ProvideValue(serviceProvider);
}
}
The converter, say of class TranslateConverter, has a constructor that accepts one parameter, a String. This is my key argument from the TranslateExtension above. It remembers it for later.
Whenever the Count value changes (it comes through the binding), WPF will request its value anew. It seems to walk from the source of the binding, through the converter, to the surface where it's displayed. By using a converter, we don't have to worry about the binding at all, because the converter gets the binding's current value as a method argument and is expected to return something else. Counting value (int) in, translated text (string) out. This is my code.
So it's the converter's task to adapt the number to a formulated text. It uses the stored text key for that. So what happens is basically a kinda backwards data flow. Instead of the text key being the main information and the count value being added to it, we need to treat the count value as the primary information and just use the text key as a side parameter to make it whole. This isn't exactly straightforward, but the binding needs to be the primary trigger. Since the key won't change, it can be stored for good in the instance of the converter. And every occurence of a translated text gets its own copy of the converter, each with an individual key programmed in.
This is what the converter could look like:
class TranslateConverter : IValueConverter
{
private string key;
public TranslateConverter(string key)
{
this.key = key;
}
public object Convert(object value, ...)
{
return Translator.Translate(key, (int) value);
}
}
That's the magic. Add the error handling and more features to get the solution.

FrameworkElement.Name problem

I am attempting to set the Name property of a Page in the constructor:
public partial class PageListView : Page
{
public PageListView(string title)
{
InitializeComponent();
Name = title;
}
}
However, I often get the following error message.
'x' is not a valid value for property 'Name'.
Where x seems to be almost anything, drilling down into the exception details doesn't seem to provide any useful information (e.g. the InnerException is null.)
Does anyone know what is happening here?
The Name property generally follows the rules of C#/VB.NET identifiers (i.e. fields). Based on the documentation:
The string values used for Name have some restrictions, as imposed by
the underlying x:Name Directive defined by the XAML specification.
Most notably, a Name must start with a letter or the underscore character
(_), and must contain only letters, digits, or underscores.
Based on the parameter you are passing (i.e. title), it seems like you may violate that. But you'd have to give some specific examples to be sure.
Of course, moments after posting this I realised what's going on.
Because FrameworkElement.Name is used for creating object references, you have to ensure that the string contains only valid chars for an object instance variable name.
Use Title or another plain text property instead, unless you really want to set the x:Name property for referencing.

Can State Pattern help with read only states?

I'm trying to model a certain process and I'm thinking that the State Pattern might be a good match. I'd like to get your feedback though about whether State will suit my needs and how it should be combined with my persistence mechanism.
I have a CMS that has numerous objects, for example, Pages. These objects (we'll use the example of Pages, but it's true of most objects) can be in one of a number of states, 3 examples are:
Unpublished
Published
Reworking
When Unpublished, they are editable. Once Published, they are not editable, but can be moved into the Reworking state. In the Reworking state they are editable again and can be Republished.
Obviously the decision for whether these Pages are editable should be in the models themselves and not the UI. So, the State pattern popped into mind. However, how can I prevent assigning values to the object's properties? It seems like a bad idea to have a check on each property setter:
if (!CurrentState.ReadOnly)
Any ideas how to work this? Is there a better pattern for this?
Using wikipedia's Java example, the structure has a Context, which calls methods defined in the base State, which the concrete states override.
In your case, the context is something like a page. In some states, the edit() method is simply a no-op. Some of the actions on the context may execute a state change implicitly. There is never any need in the client code to test which state you are in.
Update:
I actually thought of a method this morning that would work with your specific case and be a lot easier to maintain. I'll leave the original two points here, but I'm going to recommend the final option instead, so skip to the "better method" section.
Create a ThrowIfReadOnly method, which does what it says on the tin. This is slightly less repetitive and avoids the nesting.
Use an interface. Have an IPage that implements the functionality you want, have every public method return an IPage, then have two implementations, an EditablePage and a ReadOnlyPage. The ReadOnlyPage just throws an exception whenever someone tries to modify it. Also put an IsReadOnly property (or State property) on the IPage interface so consumers can actually check the status without having to catch an exception.
Option (2) is more or less how IList and ReadOnlyCollection<T> work together. It saves you the trouble of having to do a check at the beginning of every method (thus eliminating the risk of forgetting to validate), but requires you to maintain two classes.
-- Better Method --
A proper technical spec would help a lot to clarify this problem. What we really have here is:
A series of arbitrary "write" actions;
Each action has the same outcome, dependent on the state:
Either the action is taken (unpublished/reworking), or fails/no-ops (read-only).
What really needs to be abstracted is not so much the action itself, but the execution of said action. Therefore, a little bit of functional goodness will help us here:
public enum PublishingState
{
Unpublished,
Published,
Reworking
}
public delegate void Action();
public class PublishingStateMachine
{
public PublishingState State { get; set; }
public PublishingStateMachine(PublishingState initialState)
{
State = initialState;
}
public void Write(Action action)
{
switch (State)
{
case PublishingState.Unpublished:
case PublishingState.Reworking:
action();
break;
default:
throw new InvalidOperationException("The operation is invalid " +
"because the object is in a read-only state.");
}
}
}
Now it becomes almost trivial to write the classes themselves:
public class Page
{
private PublishingStateMachine sm = new
PublishingStateMachine(PublishingState.Unpublished);
private string title;
private string category;
// Snip other methods/properties
// ...
public string Title
{
get { return title; }
set { sm.Write(() => title = value; }
}
public string Category
{
get { return category; }
set { sm.Write(() => category = value; }
}
public PublishingState State
{
get { return sm.State; }
set { sm.State = value; }
}
}
Not only does this more-or-less implement the State pattern, but you don't need to maintain separate classes or even separate code paths for the different states. If you want to, for example, turn the InvalidOperationException into a no-op, just remove the throw statement from the Write method. Or, if you want to add an additional state, like Reviewing or something like that, you just need to add one case line.
This won't handle state transitions for you or any really complex actions that do different things depending on the state (other than just "succeed" or "fail"), but it doesn't sound like you need that. So this gives you a drop-in state implementation that requires almost no extra code to use.
Of course, there's still the option of dependency injection/AOP, but there's obviously a lot of overhead associated with that approach, and I probably wouldn't use it for something so simple.

Resources