I've got a lot of entity classes, and now in all properties of the entity classes need to add new functionality (call some method) in the getters and setters. What i want to say looks like this:
public class PersistentClass : BaseClass {
private string attr1;
[Persistent]
public string Attr1
{
get
{
//need to call here base class method
//refreshContents();
return attr1;
}
set
{
//need to call here base class method
//refreshContents();
attr1 = value;
}
}
private SomeObject attr2;
[Persistent]
public SomeObject Attr2
{
get
{
//need to call here base class method
//refreshContents();
return attr2;
}
set
{
//need to call here base class method
//refreshContents();
attr2 = value;
}
}
private List<SomeOtherObhect> details;
[Persistent]
pubic List<SomeOtherObject> Details
{
get
{
//need to call here base class method
//refreshContents("details");
return details;
}
set
{
//need to call here base class method
//refreshContents("details");
details = value;
}
}
}
For different types of fields i need to call different methods e.g. refreshContents() and refreshContetns("fieldName"). I'm looking to solve problem with IoC and Dependency Injection.
Could you help me please?
This seems like a use case for Aspect Oriented Programming (AOP).
Here are some links to start with:
Introduction to Aspect Oriented
Programming
And some examples
What will IoC or DI do in your case?
i think you just want a generic method in base class and call thios method from getters or setters
If you want to keep your refresh logic at one place, and call it differently from your properties, consider implementing INotifyPropertyChanged and handling the PropertyChanged event in your entity class itself and implement the refresh logic there.
However, More important question is why do you want to refresh the contents when a property is set or get? It might help to understand if you provide some real property names.
Related
So I have a generic base class like this:
class DatabaseDatasourceClassBase<DomainClass>
where DomainClass : new()
{
protected DomainClass m_DbObject;
public AddableDatabaseDatasourceClassBase()
{
m_DbObject = new DomainClass();
}
public AddableDatabaseDatasourceClassBase(DomainClass initialObject, ISessionWrapper dbSession)
{
m_DbObject = initialObject;
//Do stuff like calling SetSession(dbSession);
}
//Several functions and stuff like SetSession(ISessionWrapper dbSession)
}
I also got a lot (>20) of datasource-classes for the use in wpf-datagrids.
class CurrencyDatasource : AddableDatabaseDatasourceClassBase<Currency>
{
//The constructors look always the same
public CurrencyDatasource()
:base()
{
}
public CurrencyDatasource(Currency initialExchange, ISessionWrapper dbSession)
:base(initialExchange, dbSession)
{
}
//Following Properties are always different
public string Name
{
get
{
return m_DbObject.Name;
}
set
{
m_DbObject.Name = value;
}
}
}
So I wonder if there is a way to avoid having to write the same code (the 2 constructors + their call to the base class) in every Datasource class?
or
If this is not possible:
At least define that all classes which are derived from DatabaseDatasourceClassBase have to have these 2 Constructors?
So I wonder if there is a way to avoid having to write the same code (the 2 constructors + their call to the base class) in every Datasource class?
Each class must provide their own constructor(s) and define how they wish to call the base class's constructor(s).
At least define that all classes which are derived from DatabaseDatasourceClassBase have to have these 2 Constructors?
Classes must call at least one base class constructor, but there is no way to enforce which one, or require more than one base constructor be hooked up.
That's at least in code.
I guess you could do something crazy with static code analysis.
Is there a way I can define a method, that is called in every case, when a getter for any property in a class is called?
The class is a base class, and I want to implement various SubClasses of it, but each one should have in common that regardless of the property that should be accessed by its getter function, an action should be performed before the attribute is returned.
No, not unless you code it into every Getter, or you abandon "Plain Old C# Classes" altogether and construct a data model paradigm based around a read-audited set of data. If you go down that route that you simply have each "data class" being an Dictionary of Get/Set delegates and access its data values through those delegates. Its not an uncommon design, but it no longer follows the OO paradigms.
Example (psuedo code)
public class MonitoredCustomerObject
{
// Assumption that the Get/Set delegates are stored in a simple Tuple.
private Dictionary<string, Tuple<delegate,delegate>> getterSetterDict = new ...
public GetValue(string key)
{
executeMyOnReadCode();
return getterSetterDict[key].Item1();
}
public SetValue(string key)
{
executeMyOnWriteCode();
getterSetterDict[key].Item2();
}
}
You can kind of fake this, or you can write a Fody extension that does it. For example, you can have your base class defined as:
public abstract class MyBaseClass
{
public object MyProperty
{
get
{
RunSomeMethod();
return MyPropertyValue;
}
}
protected abstract object MyPropertyValue { get; }
}
Which "kind of" forces the implementer to write it like:
public class MyDerivedClass : MyBaseClass
{
protected override object MyPropertyValue
{
get
{
return SomeObjectValue();
}
}
}
The derived class can still hide the base class properties with new, but at least that causes the developer to explicitly realize that they are doing something unintended.
In the following code
// MVVM Views part class
public partial class DashBoard : UserControl
{
public DashBoard()
{
InitializeComponent();
this.DataContext = new DashBoardViewModel();
}
}
Could we use base.DataContext instead this.DataContext. In which case could we use base instead of this?
It's usually clearer to use this. You normally only specify base when you want to explicitly call a base class constructor or the base implementation of an overridden method or property.
Using base.DataContext would work, but it would might imply that this.DataContext would mean something different.
You use this to access a method defined in the present class (or superclass if it's not in the present class). You use base to access a method in the superclass or higher. In this case you could have used either (or none as Marc points out above).
I prefer to emit this except when it's (rarely) required.
To add to what the others have said, base. is used when you've overridden something from the base class with either the overrides or new keywords, you'll need to use base to gain access to the original method.
class a
{
public virtual void method1()
{
}
public string property1 { get; set; }
}
class b : a
{
// this has it's own instance in b, the only way to get to
// the original property1 is with base (or reflection)
public new string property1 { get; set; }
public override void method1()
{
// the only way to get to the original method1 and property1
base.method1();
base.property1 = "string";
}
}
In your example if the DataContext property uses either of these keywords then base and this don't mean the same thing at all.
Considering your case u are trying to initialize DataContext property of class DashBoard with some value. So if you then call DataContext typed property of (base)UserControl class object, it still will be not initialized. Therefore, to decide which property to initialize, u must to look to your program's logic.
Basicly MSDN tells that u should use (base.) in two scenarious:
-Call a method on the base class that has been overridden by another method.
-Specify which base-class constructor should be called when creating instances of the derived class.
In my practise i used first scenario when (this) method ends with exception, i was trying to call more general (base) method. Good luck!
I have an abstract base class and two derived classes. The base class contains 6 properties which all can be maintained on a form.
The two derived classed both have 1 extra property. Those two properties can also be maintained on the same form.
In my form I have now code like this:
btnSomething.visible = (myObject is DerivedA);
pnlPanel.visible = !(myObject is DerivedA);
if(myObject is DerivedA)
myBindingSource.DataSource = myObject as DerivedA
mySecondBindingSource = myObject;
I am not very happy with this approach, it smells. So my question is, what is a neat/good way to make this more OO? Because it is possibly that in the future DerivedC comes in...
I think this approach breaks the OCP principle (and probably other principles)
You can use polymorphism and inheritance here:
Define an interface
interface ICommonFeatures
{
bool ContainsFoo {get;}
//yak-yak
}
Then your derived classes implement it
class DerivedA: ICommonFeatures
{
bool ContainsFoo {get {return true;}}
//so-and-so
}
class DerivedB: ICommonFeatures
{
bool ContainsFoo {get {return false;}}
//this-and-that
}
And when you use it, you deal only with the interface
ICommonFeatures foo = new DerivedB();
btnSomething.visible = foo.ContainsFoo;
pnlPanel.visible = foo.Prop2;
myBindingSource.DataSource = foo.CurrentDataSource
A crazy idea would be make the UI extensible.
You could make a form implement a base form.
Then in the derived form class you would only insert the missing controls and behavior for the its model class.
In the derived model class or library you could have some sort binding to the correct form.
A good approach for this would be follow some MVP principles.
Hope it helps you somehow..
I would declare an abstract boolean method/property for each control that need to behave according to the underlying type.
For instance
// to handle pnlPanel.visible = !(myObject is DerivedA);
abstract bool SupportsPanel{get;}
As for your binding sources, I would also provide some virtual BindingSource and SecondBindingSource properties.
Maybe something like (purely an example)
public abstract class BaseClass
{
// All your exising class declaration here
public virtual object BindingSource
{
get
{
// By default, a BaseClass is not valid as a binding source
return null;
}
}
public virtual object SecondBindingSource
{
get
{
// By default, a BaseClass is a valid Second Binding source
return this;
}
}
}
public class DerivedA : BaseClass
{
// All your exising class implementation here
public override object BindingSource
{
get
{
// For DerivedA, the data sourse is itself.
// other classes might have their own implementations.
return this;
}
}
// No need to override SecondBindingSource as the BaseClass one works as expected.
}
So, your code could stop caring about the object type and look like:
myBindingSource.DataSource = myObject.BindingSource;
mySecondBindingSource = myObject.SecondBindingSource;
Hope this helps.
I'm trying to create a class (in C#) that serves as an environment for my application.
I'm trying to make the class dynamic, and send it as a parameter to entities in my application. The problem is, that I want to be able to change the properties of this environment class (public setters), but at the same time I want the classes that receive the environment to be unable to use these setters.
I can't seem to find a good way to phrase my question (which I figure is a part of the reason I can't find anything like this on Google or msdn), but to put shortly, I want to create a class with setters that are public only for some of my objects and not for all.
I'm currently amusing the following idea:
Avoiding the public setters all together, and expose the private fields using event registration.
The class will register to events in a new third object (sent as a parameter to the constructor). The methods that will be registered by the environment are not much more then setters, and so triggering these events will "allow access" to the private fields.
I'd love some ideas (seeing as I feel that mine isn't all that great), or better yet some patterns I could make use of.
Thanks in advance
Isn't "internal" sufficient for what you need?
And you could move the setters into an interface as explicit implementation. Then they are hidden from the public interface and only accessible if you cast to the interface.
And if you want to make really sure that nobody else can call it you can add some parameter to these functions where you expect a certain token object which you only give to trusted classes.
void SetX(int value, object token)
{
if(token!=correctToken)
throw new ArgumentException("wrong token");
x=value;
}
You could create a proxy, and send that proxy to your entity classes.
class MyClass
{
public int MyProperty { get; set; }
}
class MyProxyClass
{
public MyProxyClass(MyClass myClass)
{
_myClass = myClass;
}
private MyClass _myClass;
public int MyProperty
{
get { return _myClass.MyProperty; }
}
}
You could try using Friend assemblies. That will allow only the assemblies you specify to have access to your privates (snicker).
Maybe i understood something not quite well, but i think Jon had a quite similar problem which he described here. Maybe this can help you.
How about
class Callee
{
public void SetX(TypeOfCaller caller, int value)
{
}
}
class TypeOfCaller
{
public void Do()
{
Callee instance;
//..
instance.SetX(this, 5);
}
}
Doing so; you can also use Visual Studio' Find References feature! In case you want multiple types of caller; you can either opt for class hierarchy or can simply have required overloads
Why not return clones of your protected objects instead of the actual objects? Solves the problem without adding any more complexity.
public class MyService
{
private List<MyObject> _protectedObjects = new List<MyObject>();
public MyObject GetItem(int id)
{
return (MyObject)_protectedObjects.First(i => i.Id == id).Clone();
}
}
public class MyObject : ICloneable
{
//[...]
public object Clone()
{
return MemberwiseClone();
}
}