Double type DependencyProperties has wrong values in WinRT - double

I have a custom control with a dependency property of double type. When I set this property from XAML, say I am giving 12.34 as value to this property. The property changed call back giving the value as 12.3400001525879, the actual value has trailing garbage decimal values.
(This is not the case for Silverlight)
This happens only when we set the value through XAML, and also it happens only if we have more than one decimal value.
public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(double), typeof(TextBoxExt), new PropertyMetadata(null, new PropertyChangedCallback(OnValueChanged)));
private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.NewValue);//Not priniting the exact value.
}
Does anyone facing the same problem?

Not all decimal values are exactly representable by fixed-width binary floating point types like float and double. Decimal values that are not exactly representable (like 12.34) are rounded to the nearest value that is representable. You can read all about floating point types in David Goldberg's excellent article, "What Every Computer Scientist Should Know About Floating-Point Arithmetic."
In this case, the actual values you mention indicate that either (a) the value 12.34 is being parsed as a float or (b) it is being converted to a float at some point. This is a bit odd, but may either be by design or a bug. Whether or not it is a bug, if you use floating point types in your software, you need to account for potential rounding error.

I can see the same problem in my testing. Looks clearly like a bug in Jupiter. I would report it in MSDN Forums.

Related

Show/Hide variables on Editor[Unreal engine 4]

I have a master class called Door, and this door has 3 variables, aimationDuration, Start Delay and an Enum with 2 options - ClosingDoor and OpeningDoor. Now, I would like to know if its possible when I choose ClosingDoor the editor will display only the animationDuration variable and hide the StartDelay variable, and then choose the openingDoor and hide the animationDuration and show the StartDelay. Is this possible or is there another way to accomplish this?
There were improvements related to MetaTags since this question was asked and answered.
Starting with UE4.23:
The EditCondition meta tag is no longer limited to a single boolean property. It is now evaluated using a full-fledged expression parser, meaning you can include a full C++ expression.
This means we can do things like disabling (or even hiding) a property based on the value of an enum UPROPERTY. Hiding can be achieved by using the EditConditionHides MetaTag. Example:
UENUM(BlueprintType)
enum class EInterpolationMode : uint8 { Linear, Curve };
USTRUCT(BlueprintType)
struct FBlendableInterpolationData
{
GENERATED_BODY()
UPROPERTY(BlueprintReadWrite, EditAnywhere)
EInterpolationMode InterpolationMode = EInterpolationMode::Linear;
UPROPERTY(EditAnywhere, meta = (EditCondition = "InterpolationMode == EInterpolationMode::Linear", EditConditionHides))
float Duration;
UPROPERTY(EditAnywhere, meta = (EditCondition = "InterpolationMode == EInterpolationMode::Curve", EditConditionHides))
UCurveFloat* Curve;
};
WARNING: There is a special case where EditConditionHides can crash the editor for engine versions 4.26 and 4.27.
More examples for property disabling/hiding can be found here: https://thomassampson.co.uk/posts/ue4-uproperty-editcondition/
There is infact exactly something for this, but it might require a little bit of hackery as you need ENUM values and the method seems to be for boolean values.
Unreal's metadata specifiers have a 'editcondition' specifier that lets you point to a boolean variable and say, when that variable is true, let me edit this property, and it doesn't matter what the property is it works for everything.
Here's an example from the Unreal answerhub with some code:
https://answers.unrealengine.com/questions/189864/hide-and-show-variable-in-property-window.html
If the boolean method works for you that's great, otherwise you'll need to look into overriding AActor::PostEditChangeProperty() in order to do a hack where when you change the enum values, it sets a boolean value in that function (which gets called after any change in the property window for an actor), and then should work as you need it to.
If you actually want proper hiding/showing that's more complicated and requires you to use Slate which I have no idea of but here's the documentation:
https://docs.unrealengine.com/latest/INT/Programming/Slate/DetailsCustomization/index.html

Does a class variable have a right to exist if its value can be calculated using other data?

I'll give a minimalist example to explain my question.
Suppose that there is a Shape class:
public class Shape {
User user;
int color;
}
and a User class:
public class User {
int mood;
}
Now suppose that a shape's color depends on the user's mood. Is it redundant for Shape to have a color field since it can be calculated by accessing its user's mood?
Consider that in a more realistic example accessing the necessary data to calculate the color can be more complex or via a longer sequence of accessors (color = user.getCat().getCousin().getMood()). Consider further that these classes may be mapped to a database and (in a way) duplicate data. On the other hand they can be marked as transient.
Color depends on the mood but color is not the same as the mood at all. So including color field seems only logical to me, however I cannot wholly justify this design.
Does a class variable have a right to exist if its value can be calculated using other data?
I would suggest you make color a property, that way you can calculate it or not and the rest of the program won't change.
Calculating it everytime will be slower, add extra code everytime it is being called. Keeping the value will be faster (don't need to calculate everytime) but you add the risk of not having the right value if it isn't updated properly.

MongoDB C# Select specific columns

I know that MongoDb C# driver doesn't support projections so I searched a little bit and I found that many people uses a mongoCursor to perform such queries, I'm trying to select only specific fields and my code is the following:
public T GetSingle<T>(Expression<Func<T, bool>> criteria,params Expression<Func<T, object>>[] fields) where T : class
{
Collection = GetCollection<T>();
return Collection.FindAs<T>(Query<T>.Where(criteria)).SetFields(Fields<T>.Include(fields)).SetLimit(1).SingleOrDefault();
}
I got and custom repository for users on top of that:
public User GetByEmail(string mail, params Expression<Func<User, object>>[] fields)
{
return GetSingle<User>(x=>x.Email==mail,fields);
}
this is the usage:
_repository.GetByEmail(email, x=>x.Id,x=>x.DisplayName,x=>x.ProfilePicture)
but I'm getting the fields included in the parameter but also all the Enums,dates and Boolean values that are part of the class User, the values that are string and not included in the field list are null so that's fine
what can I do to avoid that?
By using SetFields, you can specify what goes through the wire. However, you're still asking the driver to return hydrated objects of type T, User in this case.
Now, similar to say an int, enum and boolean are value types, so their value can't be null. So this is strictly a C#-problem: there is simply no value for these properties to indicate that they don't exist. Instead, they assume a default value (e.g. false for bool and 0 for numeric types). A string, on the other hand, is a reference type so it can be null.
Strategies
Make the properties nullable You can use nullable fields in your models, e.g.:
class User {
public bool? GetMailNotifications { get; set; }
}
That way, the value type can have one of its valid values or be null. This can, however, be clumsy to work with because you'll have to do null checks and use myUser.GetMailNotifications.Value or the myUser.GetMailNotifications.GetValueOrDefault helper whenever you want to access the property.
Simply include the fields instead this doesn't answer the question of how to it, but there are at least three good reasons why it's a good idea to include them:
When passing a User object around, it's desirable that the object is in a valid state. Otherwise, you might pass a partially hydrated object to a method which passes it further and at some point, someone attempts an operation that doesn't make sense because the object is incomplete
It's easier to use
The performance benefit is negligible, unless you're embedding huge arrays which I would suggest to refrain from anyway and which isn't the case here.
So the question is: why do you want to make all the effort of excluding certain fields?

benefits of getter/setter VS public vars?

Is there a benifit to using:
private var _someProp:String;
public function set someProp(value:String):void
{
_someProp = value;
}
public function get someProp():String
{
return _someProp;
}
As opposed to just using:
public var someProp:String;
I realise using getter/setter can be useful when you need to further processing or need to be notified of when the property is changed like so:
public function set someProp(value:String):void
{
_someProp = value;
_somePropChanged = true;
doSomethingElse();
}
But if you don't need this, then is there any reason to use getter/setter over just using a public var?
Thanks!!
Depending on your language, you should prefer getter/setter up front because you can't introduce them later (I'm looking at you, Java) if it turns out you do need them.
This really depends a bit on the language/framework/toolkit you are using -
However, there are often benefits when using getters and setters related to versioning and API compatibility. This can be a very useful reason to use them, all on its own.
This really can't be answered without knowing the language. Getters and Setters cost more in most languages, but they buy you flexibility down the road. In some languages you can't change a public to a Getter/Setter without changing the code in the callers because the use syntax changes. But this is not an issue with C#, which I what I write in mostly.
Getters and Setters let you do parameter validation. They let you delay creation of objects until first reference. They have a lot of advantages, and I use them whenever I need one of those advantages from the beginning.
But I use getters and setters ONLY when I need them right away, or when I'm pretty sure I'm going to need the flexibility. Otherwise I view them as bloat.
As a side note, you can start with a public var and if necessary convert it to a getter / setter later in code.. depending on the language you are using.
If your property is totally dumb, and has no side effects on the rest of the class - then by all means just expose it as a public field.
Its just that in many cases your properties will have side effects, so you need to control how they are set and accessed.
As a trivial example, what happens if your public variable is not set to something in your constructor? Are you ok with this being returned as null? Or would you like to set this variable to something rather than return null? This is a simple example where a custom getter is worthwhile.
Getters and Setters also give you more control over what values the variable can be set to.
bool setAge(int age){
bol retVal = true;
if(age <= 0)
retVal = false;
return retVal;
}
Without the setter, the value could be set to zero and bad things could happen.

How can I make a c# decimal match a SQL decimal for EF change tracking?

To avoid touching changeless records in EF it's important that original and current entity values match. I am seeing a problem with decimals where the EF entity has SQL representation and that is being compared to c# decimal.
This is debug output from entities with changes detected. This shows the problem pretty clearly. Even though both the entity and the source data are in of type decimal the values are considered difference even though they are equal.
How can I ensure that original and current values match when using c# decimal?
Maybe there is a way to turn the c# decimal into an entity (SQL) decimal before the update?
Another Example
I would expect the truncation to ignore the fact that the incoming precision is higher than the SQL scale
You could implement a proxy-property which handles the conversion from code-precision to db-precision:
public class MoneyClass
{
[Column("Money")]
public decimal MyDbValue { get; set; } // You existing db-property
[NotMapped]
public decimal MyCodeValue // some property to access within you code
{
get
{
return this.MyDbValue;
}
set
{
decimal newDbValue = decimal.Round(value, 2);
if (this.MyDbValue != newDbValue)
{
Console.WriteLine("Change! Old: {0}, New: {1}, Input: {2}", this.MyDbValue, newDbValue, value);
this.MyDbValue = newDbValue;
}
}
}
}
static void Main(params string[] args)
{
MoneyClass dbObj = new MoneyClass()
{
MyCodeValue = 123.456M
};
Console.WriteLine(dbObj.MyDbValue);
dbObj.MyCodeValue = 123.457M; // won't change anything
Console.WriteLine(dbObj.MyDbValue);
dbObj.MyCodeValue = 123.454M; // will change because of 3rd decimal value 4
Console.WriteLine(dbObj.MyDbValue);
dbObj.MyCodeValue = 123.46M; // will change
Console.WriteLine(dbObj.MyDbValue);
}
This answer is not supposed to fix exactly the issue you have, but to go around it.
I suggest to code the logic that decides whether an objects needs to be saved or not on a higher application layer (in that respect I consider the EF generated classes as low level objects).
The code which retrieves and stores data could be implemented in a repository class, i.e. a class that manages your data access logic. So what you application uses would be this repository class and not the EF code. Whether the repository class internally uses EF or something else would not be important anymore for you application.
If you define an interface for you repository class you could even replace it easily with some or technology to save and retrieve data.
See here for an article from microsoft about the repository pattern.
This is an info from a question here at stackoverflow.
I generally would not recommend to use the EF generated classes in normal application code. It might be tempting a first, but also cause problems later as in your case.