This question already has answers here:
Compare equality between two objects in NUnit
(20 answers)
Closed 7 years ago.
Is there an assertion built into Nunit that checks all properties between 2 objects are the same, without me having to override Equals?
I'm currently using reflection to Assert each individual property for a pair of objects.
I don't believe there is.
Assert.AreEqual compares non-numeric types by Equals.
Assert.AreSame checks if they refer to the same object
You can write framework agnostic asserts using a library called Should. It also has a very nice fluent syntax which can be used if you like fluent interfaces. I had a blog post related to the same.
http://nileshgule.blogspot.com/2010/11/use-should-assertion-library-to-write.html
You can two objects and there properties with ShouldBeEquivalentTo
dto.ShouldBeEquivalentTo(customer);
https://github.com/kbilsted/StatePrinter has been written specifically to dump object graphs to string representation with the aim of writing easy unit tests.
It comes witg Assert methods that output a properly escaped string easy copy-paste into the test to correct it.
It allows unittest to be automatically re-written
It integrates with all unit testing frameworks
Unlike JSON serialization, circular references are supported
You can easily filter, so only parts of types are dumped
Given
class A
{
public DateTime X;
public DateTime Y { get; set; }
public string Name;
}
You can in a type safe manner, and using auto-completion of visual studio include or exclude fields.
var printer = new Stateprinter();
printer.Configuration.Projectionharvester().Exclude<A>(x => x.X, x => x.Y);
var sut = new A { X = DateTime.Now, Name = "Charly" };
var expected = #"new A(){ Name = ""Charly""}";
printer.Assert.PrintIsSame(expected, sut);
Related
I am using the Entity Framework to generate data access code from an old database.
The database table names and properties are all named in capitals with _ to separate words ie. CLIENT, CLIENT_NAME, D_CLIENT_ID etc.
I have written a class to transform these into camel cased strings:
public static class Extensions{
public static string FirstCharToUpper(this string input)
{
return input.First().ToString().ToUpper() + input.Substring(1).ToLower();
}
public static string CamelCase(this string input)
{
return input.Split('_').Where(a=>!string.IsNullOrEmpty(a)).Select(a=>a.FirstCharToUpper()).Aggregate((a,b)=>a+b);
}
}
I am invoking this from my tt files and I have got to the point where my data classes and DbContext naming is the way I want it.
However I now get an error when I try to create a controller: 'Unable to retrieve metadata for myNamespace.Client'. Could not find the CLR type for 'myModel.ENTITYNAME'. (in capital)
To fix this, I made my Data.tt decorate my data classes with [Table("ENTITYNAME")] and my properties with [Column("COLUMNNAME")] - however this did not make any difference.
What am I missing?
Are you updating it the same way in all three (or two corresponding) layers: CSDL/MSL/SSDL? I would suspect there is a mismatch between two of the layers.
Possible useful in this case - here is a library I wrote for creating/updating/manipulating EDMX files a bunch of years ago: https://github.com/KristoferA/HuagatiEDMXTools/
If you use an older version of Visual Studio (2013 or older) then I also have a free VS addon/plugin that adds renaming and db<->model sync etc. You can download it from here:
https://huagati.com/edmxtools/
Update: based on the comments below, I think you are renaming classes and properties in the generated code without making the corresponding change in the CSDL.
Instead of changing the generated code / tt templates: change the names in the CSDL and the references to those CSDL objects in the MSL. Then the default templates will generate code with the class/property/etc names you want.
This question already has answers here:
Scala: Can I declare a public field that will not generate getters and setters when compiled?
(2 answers)
Closed 7 years ago.
I wonder if it is possible to declare a public field in a Scala class. Scala normally generates a private field for val and var body variables/constructor parameters and getters/setters with the appropriate visibility.
I would like to know if it is possible to declare a public Java class field in Scala, not a getter.
PS: Why would anyone need that? It may be useful e.g. for integration with Java frameworks relying on fields:
class MyTest extends JUnitSuite {
#Rule
val temporaryFolder = new TemporaryFilder()
// throws java.lang.Exception: The #Rule temporaryFolder must be public
}
This is in response to the P.S, someone else has already posted an answer to the main question.
Because the logic behind using getters in setters (in java, for instance) is to "future-proof" your code, so that if your private field "x" somewhere down the line needs logic every time you get/set it, then you will just modify the method call and won't break any existing code that calls it. Whereas if you had just public fields and the need for logic arose, you would have to create getters/setters and then would break existing code due to changing the contract of the class. So scala just does this automatically to remove boilerplate code.
Hope this helps!
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?
I'm building a MEF-based plugin-centric WPF application and I'm facing an issue with GetExports, maybe it's just my ignorance but I find an odd behaviour. I have a number of exported parts, all derived from 2 different interfaces (let's name them A and B), but all marked with the same metadata attribute X. So I have code like:
[Export(typeof(A))]
[TheXAttributeHere...]
public class SomePart1 : A { ... }
for each part, and the same for classes implementing B:
[Export(typeof(B))]
[TheXAttributeHere...]
public class SomePart2 : B { ... }
Now, when I try getting all the parts implementing A and decorated by attribute X with some values, MEF returns not only the A-implementing parts, but ALSO the B-implementing parts. So, when I expect to deal with A-objects I get a B, whence a cast exception.
In the real world, interfaces are named IItemPartEditorViewModel and IItemPartEditorView, while their common attribute is named ItemPartEditorAttribute and exposes a PartType string property on which I do some filtering. My code to get parts is thus like e.g.:
var p = (from l in container.GetExports<IItemPartEditorViewModel, IItemPartEditorMetadata>()
where l.Metadata.PartType == sPartType
select l).FirstOrDefault();
When looking for IItemPartEditorViewModel whose PartType is equal to some value, I get the IItemPartEditorView instead of IItemPartEditorViewModel implementing object. If I comment out the attribute in the IItemPartEditorView object instead, I correctly get the IItemPartEditorViewModel implementing object.
Update the suggested "templated" method was used, but I mistyped it here as I forgot to change lessthan and greaterthan into entities. Anyway, reviewing the code I noticed that in the attribute I had "ViewModel" instead or "View" for the interface type, so this was the problem. Shame on me, sorry for bothering :)!
I think I'd need to see more of the code to know for sure what's going on. However, I'd suggest you call GetExports like this:
// Get exports of type A
container.GetExports<A>();
// Get exports of type B
container.GetExports<B>();
Then do your filtering on the list returned. This will probably fix the cast issues you are having. I'd also be interested in seeing the code for the custom metadata attribute. If it derives from ExportAttribute for example, that might be part of the problem.
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.