Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
today I found a big showstopper for my programming.
There is a class
class Foo
{
classA property {get; set;}
classB property {get; set;}
classC property {get; set;}
}
And each of the classes A, B and C has svereal classes as properties too. So, my class Foo is quite nested. The claas Foo passes parameters to an option window which is opened by the ShowDialog() command.
ShowDialog()
result false -> SelectedFoo = backup / result true -> leave method
So if the user cancels the option window the SelectedFoo, which was passed to the ViewModel of the SettingsWindow gets replaced by the backup. Well, in theory. The classes are all reference type and changed duo to the data binding in MVVM. So my backup gets altered too.
How can I stop that behaviour? Is there some way to break the connection between these two classes?
There's a couple of ways I can think of.
An old pattern from wayback is to deep clone the current settings into a new object and only apply the new settings if the use clicks Apply. This way it won't affect the rest of the system until they "ok" it. If they click Cancel there is nothing to be done because we haven't overwritten anything.
Another slightly more complex alternative is to backup individual properties as required (optionally via reflection). In this mode, no deep clone is required at startup. When a user makes a change, your record the old value before setting the new. If the user decides to cancel, you playback all the changes but this time set the properties to the prior values.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Hope you are fine. I started learning C# about 2 weeks ago.I’ve been watching videos since now. Now he is teaching Constructions . I don’t get it. When you can use all strings and all numerical values, why restricting them? I mean does it make things bad if you just let it to be default? I tried many ways but I couldn’t find my proper answer. Your reply is so much to me and I really like to know why?!
There are many reasons why one might want to use a constructor, but they are optional and depend on what the developer wants to do.
Constructors can receive parameters and set values based on the
passed values/objects. So you can have many different constructors setting up the object in different ways
Constructors can also include logic to determine how fields/properties should be set. If at all
Constructors can call other constructors of the same class
Constructors are needed if you are using dependency injection, or
readonly fields/properties.
If you want to create copies of your class object, then constructors
can be very useful way to do this. Especially deep copies.
You can also have a static constructor. It is invoked only once in
the class and it is invoked during the creation of the first
reference to a static member in the class.
Constructors can also be private. And you can have a mix of public
and private constructors.
Constructors are useful in inheritance, to ensure that parent
fields/properties are still set correctly no matter what the child does (the child can then change these of course
Sometimes it is as simple as if you are setting many default values,
it can be easier to read if they are all in the same place where you can group them together can comment on them together
BTW: Even if you don't create a constructor, the compiler will create a default one for you.
So simply put, C# provides you with lots of different options. It is up to you to select the one which suits you best for this specific task & class.
There are several topics you can explore that will show where it is necessary...
Dependency injection and Private Readonly Properties for example.
It can also just be convenient
new Uri(pathNameString) will generate the Uri object you can put in an http request by just providing the string at instantiation.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 days ago.
Improve this question
Firstly I'm talking about loose-coupling scenario, in this scenario we don't use the DbContext directly on the client side, it's used in the service layer instead.
So DbContext cannot help track changes for updating action normally. Actually we can use DbContext directly in our project but I have a feeling that that way it's fairly tightly-coupled to Entity Framework. I always prefer to creating a separate service layer (even the project is a Windows desktop application which is fairly suitable to consume DbContext directly).
So in that loose-coupling scenario, we need to detect changes ourselves without the help of DbContext. There are several options here, one of those (that I'm asking here) is detect changes from the old instance and the new instance. Here the old instance can be requested (queried) from the database, it's something like this:
public void UpdateItem(Item item){
using(var db = new SomeDbContext()){
var oldItem = db.Set<Item>().Find(item.SomeKey);
db.Set<Item>().Attach(item);
//this will actually update some EntityState for the item's properties
detectChanges(oldItem, item);
db.SaveChanges();
}
}
The cost of above method is it requires one more query to find the old item. Moreover it may be dangerous if the new item was actually loaded partially (such as just some properties of the item are loaded because just those are interested in some specific view), when that's the case the detectChanges may misupdate the item's properties' EntityState which in turn will clear value of some missing properties unexpectedly.
So I'm a bit hesitant at this point. I am open to better approaches to save/update item in this scenario.
You should consider using row version (timestamp) to handle unintended updates. https://www.infoworld.com/article/3085390/application-development/how-to-handle-concurrency-conflicts-in-entity-framework.html
At that point you wouldn’t need to detect changes. Just attach and save changes. If the object you are saving is stale, EF will throw a concurrency exception which you can either handle by notifying the user or attempt a merge or just fail. It’s up to you.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a class/object called "User" that has about a dozen properties (eg: UserGUID, UserName, etc.). It has a constructor, static methods, couple other helpers/support methods, etc.
The website has hundreds of functions/methods where 2+ parameters come from the User object. For example:
public string HelloWorld(Guid userGUID, Guid accountGUID, bool somethingElse)
{
//Do something
}
I really want to pass in the User object itself to make the call cleaner and not have to keep adding parameters everytime I need a new value from the User object. Like this:
public string HelloWorld(User user)
{
//Do something
Guid userGUID = user.UserGUID;
}
So my question is, at what point is passing in the object good/bad vs passing in several parameters? Does it depend on the size of the object? How would I determine what's "too big" vs "OK"? Is it the number of parameters? How many params is too many?
You should think about what the method is supposed to do . Why does the method exist?
The semantic of the method will determine its arguments. So, for example, if HelloWord is supposed to print some stuff out, like a userId, and something else, then the signature should contain userId and something else as arguments.
On the other hand, if HelloWord is supposed to print out some information about a User, then the method signature should have the object User as a parameter.
It all depends on the method semantic.
In Clean Code, Robert Martin says to prefer 0 arguments, 1 or 2 arguments are acceptable and 3 is too many.
In my opinion as long as you're in the same process I think passing the object is preferable to passing arguments. You wouldn't want to send (or receive) more than is needed to another process (say a web service).
I highly recommend Clean Code, it's a good read and has a lot to say about structure.
There is a very important difference here, and this is not an opinion.
I have a class/object called "User" that has about a dozen properties
Given the above situation, if you were then to allow (User user) as opposed to only allowing (Guid userGUID, Guid accountGUID, bool somethingElse) you have just introduced a security hole.
Clients would be able to send more data than they were supposed to have access to by posting the extra names of the User class. For example, it is possible for a client to alter foreign navigation property keys in this fashion if you make the entire class available (and it had foreign relations). It is also possible for clients to alter timestamps, and even logical separations depending on information stored in that class.
Preventing this type of breach is easy to do if you allow the entire class to be accepted, you just need to then manually inspect each property to make sure it wasn't erroneously sent, or screen it by only selecting the subset of information sent. Either way, this is a bad idea.
While there may be no difference in using a User class with the same properties as the 3 shown, allowing the model binding of a User class which has a larger set than the 3 can be problematic if left unchecked.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
When to use Clone (not the definition please)? I can initiate an object and use the object so why to use clone in the real world?
What is the motivation for shallow clone (I know that it copies the value types and make a reference to the the reference type) ?
please give me an examples from the real world and not the definition of clone,deep clone or shallow clone.
thanks in advance.
please give me an examples from the real world
If you have an object that's not thread safe but you can clone it to multiple independent instances you can then use those individual instances on different threads.
please give me an examples from the real world
One Example which I used some days ago:
I developed a component for printing different kind of documents based on a third party component.
In my context this is a complex construction and not "cheap" and "easy" to instantiate. Sometimes I need more than one printing-component. So use a shallow clone and only replace the config-object ("sub-objects" of printing-component which provides all printing relevant environment informations) gives me what I need with lees amount of work.
An example could be, You might want to preserve your current object values and upon some condition you might want to rollback back to previous value. Think of settings for an application. In the settings window you might press cancel or save. If you press cancel you need to discard all changes. so you clone settings object, show it to the user and if pressed save simply get values from cloned object and set to real object
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've just got a stupid question. I have done research but I quite don't understand the explanations given as I'm a beginner in C#.
I have a class called things. The user now ca create a new object in this class by clicking a button. He can give some propertes for the object before, e.g. a description or a name.
This new object has to be created automatically then.
I want a list where all the object names are listed and when the user clicks on one of these, a label should show other properties of the object apart from the name, e.g. the description.
How shall I name these objects the user creates? And how can I make the label show the properties when the user just clicks on the list.
The program has no use really but I want to create it in order to learn how object orientation works.
I hope you understand my question.
Thanks in advance to everybody
Here is my assumption,
You have a Class named "SomeClass", When you click "New" Button, the new object should be created and it should be added to the list.
You can have a List<SomeClass> list = new List<SomeClass>() Which will act as a main list, and you can just use the single object as follows,
ON NEW OBJECT CLICK
SomeClass cls = new SomeClass();
cls.Description ="desc";
list.Add(cls)
Hope this is what you are expecting.