What is EditorReuseAttribute really for? - c#

I can't find any idea of the way to use this attribute?

MSDN indicates it is indeed to indicate that a property editor can be reused without needing to recreate each time.
This is a performance win, especially if your editor needs to do significant work on start up which can be avoided. Unless you are actually having performance issues then I wouldn't worry about it.

imagine you have scenario like this:
class Complex
{
public OtherComplex1 Property1 { get; set; }
public OtherComplex2 Property2 { get; set; }
public OtherComplex2 Property3 { get; set; }
.....
public OtherComplexN PropertyN { get; set; }
}
each of your properties has its own type designer, which displays some properties, etc.
say, you have two different instances of the Complex class + instance of some other arbitrary class.
now, when you toggle between your objects like this - complex instance 1 -> other -> complex instance 2 - everything will work fine, but if you do something like this:
complex instance 1 -> complex instance 2, you'd notice that properties are not beeing refreshed.
that is default behavior of property grid, which tries to optimize number of data refresh operations. unless you want to bake a lot of logic in order to keep your designers updated, i'd suggest marking your complexTypes with editor reuse attribute set to false - in this case, whenever selection changes to a different instance, property grid would still refresh your designers.

If you don't know what it does, why do you need to use it? Do you have any code that is using it currently that you could post as an example?
It sounds like it allows you to define that a property editor for your property can be reused without restarting. I am not particularly sure why this would be useful.

Related

C# bind Object to a JSON file?

I have an Object:
public class BindObjectToFile
{
public int Property1 {get; set;}
public int Property2 {get; set;}
public BindObjectToFile(string BindingFilePath)
{
...
}
}
I have a Json File:
{
"Property1" : 1,
"Property2" : 2,
}
Whenever a property on the Object Changes, I want the Json File to change with it.
Whenever a property in the JsonFile Changes, I want the Object to change with it.
I'd like all children of BindObjectToFile to easily inherit this functionality, without requiring adjustments to the getters/setters on their properties.
Essentially, I want an object that feels like it is stored in a file, not in memory.
What I've Tried:
I started by (stupidly) Serializing/Deserializing the entire object on every single getter/setter in the object:
internal int _property1;
public int Property1
{
get
{
return JsonConvert.DeserializeObject<ObjectToFile>(File.ReadAllText(JsonFilePath))._property1;
}
set
{
_property1 = value;
File.WriteAllText(JsonFilePath, JsonConvert.SerializeObject(this));
}
}
Newtonsoft.json is great, But this approach seems wrong because it forces me to rewrite all of that boiler plate for each property on each new child without communicating to anyone that that is how my BindObjectToFile class is supposed to be used.
Next, I tried implementingINotifyPropertyChanged to only save the newly serialized object when a property changes. This was a little better, but it still doesn't account for situations where the file is changed by something other than this instance of 'BindObjectToFile'.
I tried Creating a Generic BindObjectToFile which also implemented INotifyPropertyChanged. I did this in hopes that by using a Generic object, I could get around this problem without using inheritance, so that I wouldn't need to find a way to force children to write crazy getters/setters for each of their properties:
public abstract class ObjectToFile<T> : INotifyPropertyChanged
{
public T _value;
public T Value
{
get
{
return JsonConvert.DeserializeObject<T>(File.ReadAllText(Path));
}
set
{
_value = value;
File.WriteAllText(Path, JsonConvert.SerializeObject(_value ));
}
}
public string JsonFilePath;
public ObjectToFile(T value, string path)
{
_value = value;
JsonFilePath = path;
}
}
But, this still forces me to either raise or manage PropertyChange events in the child classes when their properties change.
And I don't want to do any of that--I Just want a fix-the-problem parent class so that I can happily create child classes that behave correctly without me needing to think about any of this.
That seems reasonable, right?
Caveats:
I don't mind rewriting/rereading the entire file every time a property is accessed or changed.
In my context, I don't care much about speed. If someone else opens up one of these files and I have to wait a few hundred ms for my turn, that's not a problem.
All the objects that I'm working with are extremely simple, containing properties with basic data types.
All the objects that I'm working with are extremely small, and rarely have more than five or six properties.
Thanks, All!
I don't believe you can only change part of a json file, to only save the property value that was changed. If the length of value changed, it would have to move the rest of the file up or down and I don't think you can do that. So you will have to rewrite the entire file every time. Which really sucks if some code changes more than one property at a time. I would probably add a .Save method or maybe even add change tracking with a .Commit when done making changes - so the file is written once per set of changes. This also helps to communicate to anyone using the class that that is how the object is to be used.
You also shouldn't be reading/deserializing the file every time a property is referenced. I would instead try using the FileSystemWatcher class (setting the Filter property) to be notified of changes to the file.
If the number of consumers watching the same file is an issue, perhaps look into using a document/nosql database instead of manually doing it yourself.

Updating DDD Aggregates with Collections

So, I've got an aggregate( Project ) that has a collection of entities (ProjectVariables) in it. The variables do not have Ids on them because they have no identity outside of the Project Aggregate Root.
public class Project
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<ProjectVariable> ProjectVariables { get; set; }
}
public class ProjectVariable
{
public string Key { get; set; }
public string Value { get; set; }
public List<string> Scopes { get; set; }
}
The user interface for the project is an Angular web app. A user visits the details for the project, and can add/remove/edit the project variables. He can change the name. No changes persist to the database until the user clicks save and the web app posts some json to the backend, which in turns passes it down to the domain.
In accordance to DDD, it's proper practice to have small, succinct methods on the Aggregate roots that make atomic changes to them. Examples in this domain could be a method Project.AddProjectVariable(projectVariable).
In order to keep this practice, that means that the front end app needs to track changes and submit them something like this:
public class SaveProjectCommand
{
public string NewName { get; set; }
public List<ProjectVariable> AddedProjectVariables { get; set; }
public List<ProjectVariable> RemovedProjectVariables { get; set; }
public List<ProjectVariable> EditedProjectVariables { get; set; }
}
I suppose it's also possible to post the now edited Project, retrieve the original Project from the repo, and diff them, but that seems a little ridiculous.
This object would get translated into Service Layer methods, which would call methods on the Aggregate root to accomplish the intended behaviors.
So, here's where my questions come...
ProjectVariables have no Id. They are transient objects. If I need to remove them, as passed in from the UI tracking changes, how do identify the ones that need to be removed on the Aggregate? Again, they have no identification. I could add surrogate Ids to the ProjectVariables entity, but that seems wrong and dirty.
Does change tracking in my UI seem like it's making the UI do too much?
Are there alternatives mechanisms? One thought was to just replace all of the ProjectVariables in the Project Aggregate Root every time it's saved. Wouldn't that have me adding a Project.ClearVariables() and the using Project.AddProjectVariable() to the replace them? Project.ReplaceProjectVariables(List) seems to be very "CRUDish"
Am I missing something a key component? It seems to me that DDD atomic methods don't mesh well with a pattern where you can make a number of different changes to an entity before committing it.
In accordance to DDD, it's proper practice to have small, succinct
methods on the Aggregate roots that make atomic changes to them.
I wouldn't phrase it that way. The methods should, as much as possible, reflect cohesive operations that have a domain meaning and correspond with a verb or noun in the ubiquitous language. But the state transitions that happen as a consequence are not necessarily small, they can change vast swaths of Aggregate data.
I agree that it is not always feasible though. Sometimes, you'll just want to change some entities field by field. If it happens too much, maybe it's time to consider changing from a rich domain model approach to a CRUD one.
ProjectVariables have no Id. They are transient objects.
So they are probably Value Objects instead of Entities.
You usually don't modify Value Objects but replace them (especially if they're immutable). Project.ReplaceProjectVariables(List) or some equivalent is probably your best option here. I don't see it as being too CRUDish. Pure CRUD here would mean that you only have a setter on the Variables property and not even allowed to create a method and name it as you want.

Is there any Interdependent Collections Modifications Management Framework?

Last day I ended up thinking about some collections interdependence.
I cannot put a better label, name, title, or whatever suggesting this situation... so feel free to suggest anything better than my cheap labeling, that is " Interdependent Collections Modifications Management".
Long story short, the example below.
First, let's consider a couple of classes:
public class DummyItem
{
public DummyItem(String name)
{
this.Name = name;
}
public String Name { get; set; }
}
// A kind of repository of DummyItems
public class BusinessClassProvider
{
public BusinessClassProvider()
{
this.Collection = new List<DummyItem>();
}
public IList<DummyItem> DummyItems{ get; private set; }
}
public class BusinessClassConsumer
{
public BusinessClassConsumer()
{
this.Collection = new Collection<DummyItem>();
}
public ICollection<DummyItem> DummItems{ get; private set; }
}
Now let's say that BusinessClassProvider.Collection is populated via some processes, user inputs, etc.
The BusinessClassConsumer Collection is something selected from BusinessClassProvider Collection by let's say also some user inputs or any other way.
Now if I remove or add a DummyItem from the BusinessClassProvider Collection I need to create Additional Nethods to wrap or eventually if they are some events supported to notify the others of what have been changed and remove accordingly the related other Collections (e.g. BusinessClassConsumer one) to also remove this item.
Basically it means a lot of boilerplate code and a lot of stuff to handle manually.
Of course, we could go with another strategy using IEnumerable as BusinessClassConsumer Collection but it does not provide the same options about indexing for instance, furthermore it forces to iterate over and over on BusinessClassProvider Collection.
I know it raises many more questions like which collection is kinda the provider and the others which consumes from.
Is there any frameworks via Attributes, or any other nasty tricks to enforce the dependency between several collections?
By the way, once again, is there anybody who knows how to label correctly this sort of situation?
If your need is to be notified when a collection change (item added, removed or the whole collection refreshed) you might want to use an ObservableCollection.
It's used mostly in WPF to notify the UI when a collection of item has changed and needs to be refreshed.
If your need is a producer/consumer collection, you might want to look for a BlockingCollection.
It's a thread safe collection that do all the producer/consumer things for you.
Yes, there are. Quite a few actually, but ObservableCollection that come with .net are not preferred. Instead one would use Rx-Linq(Reactive extension) that adds observables, Linq and schedulers together.

How to Design whether a Class Property has Changed?

I have a class with about 20 properties but I'd simplify it for this question:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
I'd like to have a class or property that identifies whether my class is dirty. By this I mean to identify whether any of its values have changed?
There are 3 design approaches I can take:
1)
When setting the property inside the class, I check whether the property IsDirty.
public string Name
{
get { return this._name; }
set { if (this._name != value) { this.IsDirty = true; this._name = value; }
}
2)
When setting the property from outside the class, I check whether the property IsDirty.
e.g.
if (p.Name != newName)
{
p.IsDirty = true;
p.Name = newName;
}
This approach forces me to add lots of ifs in the client class. Some properties are even collections or even reference objects so the number of lines would be increased even.
3)
When the object is ready to be saved, then I check whether any properties IsDirty by getting a cloned object and checking the equality.
This would have a poorer performance as I would have to clone or load again the original object then compare the properties one by one.
Which one is the best design? or is there any other design pattern that can help with this?
Another option would be to Implement the INotifyPropertyChanged Interface.
Please note that this will help you make thing more tidy and your API clearer, but as far as internal implementation regarding keeping track after changes, It is still up to you to implement. I think this goes along best with your Option #1
Option 1 is clearly best: it puts the responsibility of tracking dirtiness where it belongs: inside the object. Option 2 is out because as you mentioned, you are forcing this responsibility onto the clients of your classes. And option 3 has the additional problem as you mentioned of performance.
Incidentally, you should look into a proxy implementation using DynamicProxy. This will allow your code to look like this:
public class Product
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
and with the judicious use of interceptors, you can get the behaviour you want. You can write an interceptor to intercept any "sets" and do some logic inside, such as setting an IsDirty flag.
Another idea would be to make this a GoF Observable and let interested Observer parties register their interest in changes. It's a more event-based approach.
This is the best solution and complies with SRP principle very nicely, I created the below classes:
ProductWithChangeDetection; this uses the Decorator pattern to add this new feature to an existing product object
ProductChangeDetector; this contains logics for checking and notification. Currently only exposes ChangeDetected property but if more complexity needed one should implement INotifyPropertyChange interface.
ProductEquitable; this implements IEquitable and has some overloads for checking whether two objects/properties are equal

When to use Properties and Methods?

I'm new to the .NET world having come from C++ and I'm trying to better understand properties. I noticed in the .NET framework Microsoft uses properties all over the place. Is there an advantage for using properties rather than creating get/set methods? Is there a general guideline (as well as naming convention) for when one should use properties?
It is pure syntactic sugar. On the back end, it is compiled into plain get and set methods.
Use it because of convention, and that it looks nicer.
Some guidelines are that when it has a high risk of throwing Exceptions or going wrong, don't use properties but explicit getters/setters. But generally even then they are used.
Properties are get/set methods; simply, it formalises them into a single concept (for read and write), allowing (for example) metadata against the property, rather than individual members. For example:
[XmlAttribute("foo")]
public string Name {get;set;}
This is a get/set pair of methods, but the additional metadata applies to both. It also, IMO, simply makes it easier to use:
someObj.Name = "Fred"; // clearly a "set"
DateTime dob = someObj.DateOfBirth; // clearly a "get"
We haven't duplicated the fact that we're doing a get/set.
Another nice thing is that it allows simple two-way data-binding against the property ("Name" above), without relying on any magic patterns (except those guaranteed by the compiler).
There is an entire book dedicated to answering these sorts of questions: Framework Design Guidelines from Addison-Wesley. See section 5.1.3 for advice on when to choose a property vs a method.
Much of the content of this book is available on MSDN as well, but I find it handy to have it on my desk.
Consider reading Choosing Between Properties and Methods. It has a lot of information on .NET design guidelines.
properties are get/set methods
Properties are set and get methods as people around here have explained, but the idea of having them is making those methods the only ones playing with the private values (for instance, to handle validations).
The whole other logic should be done against the properties, but it's always easier mentally to work with something you can handle as a value on the left and right side of operations (properties) and not having to even think it is a method.
I personally think that's the main idea behind properties.
I always think that properties are the nouns of a class, where as methods are the verbs...
First of all, the naming convention is: use PascalCase for the property name, just like with methods. Also, properties should not contain very complex operations. These should be done kept in methods.
In OOP, you would describe an object as having attributes and functionality. You do that when designing a class. Consider designing a car. Examples for functionality could be the ability to move somewhere or activate the wipers. Within your class, these would be methods. An attribute would be the number of passengers within the car at a given moment. Without properties, you would have two ways to implement the attribute:
Make a variable public:
// class Car
public int passengerCount = 4;
// calling code
int count = myCar.passengerCount;
This has several problems. First of all, it is not really an attribute of the vehicle. You have to update the value from inside the Car class to have it represent the vehicles true state. Second, the variable is public and could also be written to.
The second variant is one widley used, e. g. in Java, where you do not have properties like in c#:
Use a method to encapsulate the value and maybe perform a few operations first.
// class Car
public int GetPassengerCount()
{
// perform some operation
int result = CountAllPassengers();
// return the result
return result;
}
// calling code
int count = myCar.GetPassengerCount();
This way you manage to get around the problems with a public variable. By asking for the number of passengers, you can be sure to get the most recent result since you recount before answering. Also, you cannot change the value since the method does not allow it. The problem is, though, that you actually wanted the amount of passengers to be an attribute, not a function of your car.
The second approach is not necessarily wrong, it just does not read quite right. That's why some languages include ways of making attributes look like variables, even though they work like methods behind the scenes. Actionscript for example also includes syntax to define methods that will be accessed in a variable-style from within the calling code.
Keep in mind that this also brings responsibility. The calling user will expect it to behave like an attribute, not a function. so if just asking a car how many passengers it has takes 20 seconds to load, then you probably should pack that in a real method, since the caller will expect functions to take longer than accessing an attribute.
EDIT:
I almost forgot to mention this: The ability to actually perform certain checks before letting a variable be set. By just using a public variable, you could basically write anything into it. The setter method or property give you a chance to check it before actually saving it.
Properties simply save you some time from writing the boilerplate that goes along with get/set methods.
That being said, a lot of .NET stuff handles properties differently- for example, a Grid will automatically display properties but won't display a function that does the equivalent.
This is handy, because you can make get/set methods for things that you don't want displayed, and properties for those you do want displayed.
The compiler actually emits get_MyProperty and set_MyProperty methods for each property you define.
Although it is not a hard and fast rule and, as others have pointed out, Properties are implemented as Get/Set pairs 'behind the scenes' - typically Properties surface encapsulated/protected state data whereas Methods (aka Procedures or Functions) do work and yield the result of that work.
As such Methods will take often arguments that they might merely consume but also may return in an altered state or may produce a new object or value as a result of the work done.
Generally speaking - if you need a way of controlling access to data or state then Properties allow the implementation that access in a defined, validatable and optimised way (allowing access restriction, range & error-checking, creation of backing-store on demand and a way of avoiding redundant setting calls).
In contrast, methods transform state and give rise to new values internally and externally without necessarily repeatable results.
Certainly if you find yourself writing procedural or transformative code in a property, you are probably really writing a method.
Also note that properties are available via reflection. While methods are, too, properties represent "something interesting" about the object. If you are trying to display a grid of properties of an object-- say, something like the Visual Studio form designer-- then you can use reflection to query the properties of a class, iterate through each property, and interrogate the object for its value.
Think of it this way, Properties encapsulate your fields (commoningly marked private) while at the same time provides your fellow developers to either set or get the field value. You can even perform routine validation in the property's set method should you desire.
Properties are not just syntactic sugar - they are important if you need to create object-relational mappings (Linq2Sql or Linq2Entities), because they behave just like variables while it is possible to hide the implementation details of the object-relational mapping (persistance). It is also possible to validate a value being assigned to it in the getter of the property and protect it against assigning unwanted values.
You can't do this with the same elegance with methods. I think it is best to demonstrate this with a practical example.
In one of his articles, Scott Gu creates classes which are mapped to the Northwind database using the "code first" approach. One short example taken from Scott's blog (with a little modification, the full article can be read at Scott Gu's blog here):
public class Product
{
[Key]
public int ProductID { get; set; }
public string ProductName { get; set; }
public Decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public virtual Category category { get; set; }
}
// class Category omitted in this example
public class Northwind : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
You can use entity sets Products, Categories and the related classes Product and Category just as if they were normal objects containing variables: You can read and write them and they behave just like normal variables. But you can also use them in Linq queries, persist them (store them in the database and retrieve them).
Note also how easy it is to use annotations (C# attributes) to define the primary key (in this example ProductID is the primary key for Product).
While the properties are used to define a representation of the data stored in the database, there are some methods defined in the entity set class which control the persistence: For example, the method Remove() marks a given entity as deleted, while Add() adds a given entity, SaveChanges() makes the changes permanent. You can consider the methods as actions (i.e. you control what you want to do with the data).
Finally I give you an example how naturally you can use those classes:
// instantiate the database as object
var nw = new NorthWind();
// select product
var product = nw.Products.Single(p => p.ProductName == "Chai");
// 1. modify the price
product.UnitPrice = 2.33M;
// 2. store a new category
var c = new Category();
c.Category = "Example category";
c.Description = "Show how to persist data";
nw.Categories.Add(c);
// Save changes (1. and 2.) to the Northwind database
nw.SaveChanges();

Categories

Resources