Make a data binding between 2 properties in different classes - c#

I have to classes in C# every one contain one proptery so i want to make a data binding between the proprty in the first class and the property in the other one how can i do it. There is an example:
public class FirstClass
{
public string Name { get; set; }
public void BindNameFromRealName()
{
// what can i write here ?
}
}
public class Origine
{
public string RealName { get; set; }
}

You have to have a way to feed the Origine class into the FirstClass. Perhaps a required property for Origine in FirstClass? You can't magically make it know there are other objects in play.

I echo the previous post. Perhaps you want to evaluate your need; what exactly is it you're trying to do. Why do you want to carry data using 2 objects instead of one? If this is like Data Transfer Object <-> Business Object data transfer in scenarios like web service calls, then you might want to check object mapping frameworks like Automapper

Related

where to put the checking function for the model (asp.net mvc5)

i know the model should not have any logic , but i don't know where is the good place to put the checking or the update function for a particular model
ex.
public class GuestBook
{
public int money { get; set; }
[Required]
public string name { get; set; }
[Required]
public string email { get; set; }
public DateTime content { get; set; }
public bool rich()
{
if (this.money <3000)
return false;
else
return true;
}
public void earn(GuestBook b)
{
this.money += b.money;
}
}
the function rich() and earn() is only use for this module(GuestBook)
if i didn't put it in this module , then where i should put?
Following good OOP design principles, the only way to really protect your classes' invariants (and not have a maintainability nightmare) is by not allowing them to be changed by anyone other than the class. Typically this is done by NOT exposing public setter methods (public auto properties are evil), making your fields readonly (wherever possible), and initializing them from the constructor.
The whole point of having classes is to group data with behavior. A simple data structure containing ints and strings is not a class in the OOP sense, it's just a struct.
In some cases you are stuck with an even more evil ORM that FORCES you to make all properties public. This is not an issue with Entity Framework (and some others too) though, EF can magically reflect in and access private setters if needed, you just gotta make sure there's also a private default constructor.
According to your class rich method is validating and earn method is applying business logic. You can create AdditionalMetadataAttribute for rich method logic that can fire on ModelState.IsValid and for earn method you need to create BO class that apply your all business logic.
here a link for AdditionalMetadataAttribute

Where to create the class

I'm trying to model a production system with "facility" as Class and some subclasses down to "Activity". The facility has a name as only parameter (at the moment), and I'd like to create an instance of the class reading the name as an input from a textbox. Since "activity" is inherit the properties from it's "parent classes" I'll create an instance of the class "activity" and not it's parent.
The problem is that I don't know where to create the class and how to pass it so that when I add the first subclass "Workstation" I can edit the properties of the same "activity" I created earlier.
I don't really have any code to add at this point unfortunately, but please tell me if there's anything special you'd like to see and I'll try to add it to the post.
And by the way, it's in the shape of a WinForm application with a GUI I'm trying to do this.
There are a couple things to note here. First, you'll want to use the Composite pattern to encapsulate the relationships between your classes. (For those who don't understand the OP's type hierarchy, it does make perfect sense in a factory context. There are many activities going on, which can be grouped into workstations and at a higher level into facilities.)
So, you should probably have a base Activity class (that supports the Composite pattern by exposing a collection of child activities), and then your "levels" (like Facility and Workstation) will inherit from Activity. Each of these classes will have unique properties.
The following classes should be created in their respective files, e.g. Activity.cs, Factory.cs, Workstation.cs:
class Activity
{
// An attribute that every Activity may need: a displayable name.
// This might be useful if you have a TreeView, e.g., showing all the activities.
public string Name { get; private set; }
// Every Activity could have child activities - this is the Composite pattern.
// You can loop through these to navigate through the hierarchy of your data.
// (This is often done using recursion; see example below with GetAllWorkstations().)
public List<Activity> ChildActivities { get; private set; }
public Activity()
{
ChildActivities = new List<Activity>();
}
public override string ToString() { return Name; }
}
class Factory : Activity
{
public string City { get; private set; }
public string Address { get; private set; }
}
class Workstation : Activity
{
public string WorkstationNumber { get; private set; }
}
The responsibility of loading your model then has to be handled somewhere. A good place to do it is in your main form. For example, you might write code like this:
class MainForm : Form
{
private readonly List<Factory> topLevelFactoryActivities;
public MainForm()
{
// ... other code
topLevelFactoryActivities = LoadTopLevelFactoryActivities();
}
private IEnumerable<Factory> LoadTopLevelFactoryActivities()
{
var factories = new List<Factory>();
// TODO: Load the factories, e.g. from a database or a file.
// You can load all the child objects for each factory here as well,
// or wait until later ("lazy-loading") if you want to.
// NOTE: If this becomes complex, you can move the LoadTopLevelFactoryActivities()
// method to its own class, which then becomes your "data access layer" (DAL).
return factories;
}
}
Now, if you want to find all the workstations that are part of a particular factory, you would write a method like the following on the Factory class:
class Factory : Activity
{
// ... other code
public IEnumerable<Workstation> GetAllWorkstations()
{
return GetWorkstationsRecursive(this);
}
private IEnumerable<Workstation> WorkstationsIn(Activity parentActivity)
{
foreach (var workstation in parentActivity.ChildActivities.OfType<Workstation>)
{
// Uses a C# feature called 'iterators' - really powerful!
yield return workstation;
}
foreach (var childActivity in parentActivity.ChildActivities)
{
// Using recursion to go down the hierarchy
foreach (var workstation in WorkstationsIn(childActivity))
{
yield return workstation;
}
}
}
}
You would call it like so, e.g. in your main form:
class MainForm : Form
{
// ... other code
public MainForm()
{
// ... other code
// Assume this is assigned to the factory that you want to get all the workstations for
Factory myFactory;
var workstations = myFactory.GetAllWorkstations();
// Now you can use 'workstations' as the items source for a list, for example.
}
}
As an example use case, you might want to show a second form (that belongs to the main form) which shows a list of all the workstations. (In practice you probably shouldn't create too many windows; prefer building a nonoverlapping layout. But just to show how you might pass the model instances around...)
class WorkstationListForm : Form
{
private IEnumerable<Workstation> workstations;
public WorkstationListForm(IEnumerable<Workstation> workstations)
{
this.workstations = workstations;
//TODO: You can now use 'workstations' as the ItemsSource of a list view in this form.
}
}
You could, of course, make topLevelFactoryActivities public on your MainForm and pass the variable this of the MainForm to the WorkstationListForm constructor instead. Then you could access the member on MainForm like this:
public WorkstationListForm(MainForm mainForm)
{
var topLevelFactoryActivities = mainForm.topLevelFactoryActivities;
// Now WorkstationListForm has full access to all the data on MainForm. This may or
// may not be helpful (it's usually best to minimize sharing and public fields).
}
Second, you'll want to use a proper separation between your view (user interface code/classes) and your model (the Activity hierarchy).
Third, if there's going to be any kind of live data being pushed to the user interface then you'll need a databinding mechanism to automatically update the view whenever the model changes.
In general, #2 & #3 are popularly addressed via the Model-View-ViewModel pattern. There is an excellent tutorial here for building an MVVM app using WinForms/C#.
That should get you started, at least. Also see an answer to a similar question. (Sorry about promoting my own answer, but I don't want to type out the whole example twice. Please forgive me. :))

asp.net mvc4 EF5 Singleton?

I have a project going on and I'd like to have one unique instance of a class.
I have a 'JobOffer' class, which has a property of type 'OfferStatus' (which is abstract and implements a state pattern). I have 'StateAvailable' and 'StateUnavailable' (or 'open' and 'closed' if you wish).
The 'JobOffer' objects have to be stored in the db.
I'd like to have just one 'StateAvailable' and one 'StateUnavailable', so when I create a new JobOffer I reference to 'StateAvailable' or 'StateUnavailable', and then I could list all the jobOffers which are Open (available) and all that are Closed (unavailable).
I know that I could do this by adding the states in the db in the seed method, and never instantiate a new state.
But I was wondering if it is possible to do a singleton or something to avoid that somebody (I mean controller, model or anything) can create new instances of that class.
public class JobOffer {
public int JobOfferId {get;set;}
public OfferState State {get;set;
public virtual ICollection<Person> People {get;set;}
//And some methods here, which depends on the state
//ie, this.State.myMethod();
My first thought was to use a boolean. Then you said you have to be able to expand to have more states, so I thought of an enum. Then you said you have this requirement to use a class, so... here's a little something I use when I want an enum with more smarts. You could call it a sort of "enumerating class", I suppose. So, your OfferState class looks like this:
public sealed class OfferState
{
public bool CanChangeState { get; set; }
//whatever properties you need
public static OfferState Available = new OfferState(true);
public static OfferState Unavailable = new OfferState(true);
public static OfferState Closed = new OfferState(false);
//whatever states you need
public OfferState(bool canChange)
{
CanChangeState = canChange;
}
}
This acts kind of like an enum, but it has properties like a class. So in your logic, you can check state:
if (jobOffer.State == OfferState.Available)
{
//stuff
}
You can also get properties off it, so you can use it to get information about the state:
jobOffer.ExpiryDate = jobOffer.CreationDate.Add(OfferState.Available.MaxDuration);
And of course, the static nature of the various states will ensure that there's only ever one instance of each.

How to separate controller from model when already mixed?

I'm not sure if this is exactly a MVC pattern, but what I'm trying to do is separate all the data layer (which in a few words is all that would be serialized to an XML file), from its actions. Implementing MVC just for the sake of it is really not my aim here. So if this is not exactly MVC, I'm fine with that.
Say, for instance, I have this classes (these are just sample classes that try to illustrate my problem, not my actual classes):
public class MixedSubClass
{
public string SomeData {get;set;}
public void DoSomeActionWhichRequiresControls(Control someControl)
{
// do stuff
}
}
public class MixedClass
{
private Control _SomeControl;
public List<MixedSubClass> _SubClasses = new List<MixedSubClass>();
public List<MixedSubClass> SubClasses { get { return _SubClasses; } }
public MixedClass(Control someControl)
{
_SomeControl = someControl;
}
public void DoSomeMoreActionsWhichRequiresControls()
{
foreach (var subClass in SubClasses)
{
subClass.DoSomeActionWhichRequiresControls(_SomeControl);
}
// Do more stuff
}
}
So when I serialize MixedClass, only public fields get serialized, which is what I want. But now I want to have an only data layer, which doesn't even require the Windows.Forms assembly. I want to stay with this:
public class MixedSubClass
{
public string SomeData {get;set;}
}
public class MixedClass
{
public List<MixedSubClass> _SubClasses = new List<MixedSubClass>();
public List<MixedSubClass> SubClasses { get { return _SubClasses; } }
}
And put all this into an independent assembly. But my problem now is how to turn this back to the previous thing. First thing I thought was using extension methods, but, as you can see in my sample code, sometimes I need to store some value that is not serializable, such as the Control _SomeControl. Also, on real life, these lists are lists of lists, trees and more complicated stuff like that so I need a some good foundation before I get started (actually I already have a project with all my data layer by itself which compiles fine without Windows.Forms, but now I'm having trouble putting it back together).
How would you handle this? Should I just not separate the data layer this way?
I think you are doing fine so far. Your data layer should absolutley be free of references to UI controls (whether they be winform, web, etc).
While it is hard to give an exact code sample based on what you've posted, you need to add a set of controller-like classes that map your data (aka model) onto your user-interface (aka view). They should hold a reference to both the data and UI objects and be the ones to perform th work that you stripped out (DoSomeActionWhichRequiresControls).

OOP principles in C#

I have a library (no source), to an certain object of which, I need to add some properties.
What would be the a way to do it ? I'm aware I could extend the class and add properties to the child. As well I know there are NO Extension Properties in C# yet. What would you suggest ? Thank you !
The metadata of class could be something like :
public class ResultClass
{
public IList<Item> Results { get; set; }
public int TotalResults { get; set; }
}
and I want to add a :
String description;
to it. Thanks.
There are a couple strategies you could take. Inheritance is the most obvious one. You might also consider composition. Can you give us some more details about what the object is and what properties you need to add to it and why?
After seeing the expanded question:
Either strategy outlined above (composition or inheritance) will probably work for you. Personally, I prefer composition. I think it better insulates you from changes that might be made to the third party library. It also forces you to work through the public interface of the library class, which is preferable when you have no knowledge or control of the internals of a class.
Here is the most basic example of composition.
public CompositeClass
{
private ResultClass _resultClass = new ResultClass();
public IList<Item> Results
{
get { return _resultClass.Results; }
set { _resultClass.Results = value; }
}
public int TotalResults
{
get { return _resultClass.TotalResults; }
set { _resultClass.TotalResults = value; }
}
//
// New Property
//
public string Description { get; set; }
}
Why do you need to add properties? If this is for binding purposes then I would suggest creating a wrapper class or creating your own inherited type that can raise PropertyChanged events in response to various state changes in your third party types. Instead of telling us your proposed solution you should tell us the actual problem you are trying to solve. Also (as I can't vote to close/migrate), this is not really a valid discussion for this site.
I think you are mixing up Extension Methods with Extension Properties.
And the last ones do not exist in C#.
So you should extend the class or create an inheriting class.

Categories