Code Contract on property in Interface - c#

Hi iam trying to put my code contract on interface on my class and i write something like this:
[ContractClass(typeof(MyClassContract))]
interface IMyClass
{
int Id { get; set; }
}
[ContractClassFor(typeof(IMyClass))]
sealed class MyClassContract : IMyClass
{
public int Id
{
get { return Id; }
set { Contract.Requires(value > 0); }
}
}
public class MyClass : IMyClass
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
}
but don't like to be forced to define a get in contract that will be never used, mean that i can write it as
get { return "abcdrdkldbfldsk"; }
and don't like to be forced to use public property in an internal class only because cant write
get { return ImyClass.Id; }
EDIT:
this is what i would like to write:
[ContractClassFor(typeof(IMyClass))]
sealed class MyClassContract : IMyClass
{
int IMyClass.Id
{
set { Contract.Requires(value > 0); }
}
}

If you add a Contract invariant in the ContractClassFor (MyClassContract):
[ContractInvariantMethod]
private void ObjectInvariant ()
{
Contract.Invariant (Id >= 0);
}
Then an Ensures / Requires pair will be added on the get / sets for the property. (Ref 2.3.1 of the reference)
You can then use an automatic property in the ContractClassFor
int Id { get; set; }
(i.e. will still need to add the property, because of the interface)
More here

Related

Triggering get and set for properties using attribute

I need to build an attribute that will override the getter and the setter of an property. To be more clear, here is how it works today and how it should work using the attribute (the result should be the same).
Old version:
public class A
{
private Handle _handle;
public String StringProp
{
get {
return _handle.GetProperty(PropId.StringProp);
}
set {
_handle.SetProperty(PropId.StringProp, value);
}
}
public int IntProp
{
get {
return _handle.GetProperty(PropId.IntProp);
}
set {
_handle.SetProperty(PropId.IntProp, value);
}
}
}
New version:
public class A
{
private Handle _handle;
[HandleProperty(PropId.StringProp)]
public String StringProp { get; set; }
[HandleProperty(PropId.IntProp)]
public int IntProp { get; set; }
}
The attribute HandleProperty should known to link the getter and setter to _handle.GetProperty and _handle.SetProperty.
I created two enums and some of the fields in one enum were mapped to another enums fields using attributes. I think you can do something like this...
[AttributeUsage(AttributeTargets.Field)]
public sealed class MapsToAttribute : Attribute
{
private string Text;
public string MapsToText
{
get
{
return Text;
}
}
public MapsToAttribute(string mapsToText)
{
Text = mapsToText;
}
public override string ToString()
{
return Text;
}
}

Use custom property attribute to map value to another type

I"m trying to put together an abstract class that various models in my MVVM will derive from. Part of this is for abstracting IEditableObject/IChangeTracking details.
For my IEditableObject, I want to store a shallow copy of "core data" (a struct that defines data that will be serialized, typically for database storage) so that it can be cancelled or committed. What I don't want to do is type this out for each new Model that I come up with.
I've defined a [DataCoreItem] custom attribute that I thought to use on the derived class's applicable properties. For some unrelated reasons, the abstract class takes a generic DataCoreType and IDType:
public abstract class ModelObject<T, DataCoreType, IDType> : INotifyPropertyChanged, IEditableObject
{
public abstract DataCoreType Load(IDType id);
public abstract bool Save(DataCoreType dataCore);
public abstract bool Delete(IDType id);
// etc...
Here's an example for my CompanyModel
the data core:
public struct CompanyDataCore
{
public int? ID;
public string Code;
public string Name;
public string PrimaryWebsite;
public string PrimaryPhone;
public string PrimaryEmail;
}
the derived class:
public class CompanyModel : ModelObject<CompanyModel, CompanyDataCore, int> {
CompanyDataCore dataCore;
[DataCoreMember]
public int? ID { get { return dataCore.ID; } set { SetProperty(ref dataCore.ID, value); } }
[DataCoreMember]
public string Name { get { return dataCore.Name; } set {SetProperty(ref dataCore.Name, value); } }
[DataCoreMember]
public string Code { get { return dataCore.Code; } set { SetProperty(ref dataCore.Code, value); } }
[DataCoreMember]
public string PrimaryPhone { get { return dataCore.PrimaryPhone; } set {SetProperty(ref dataCore.PrimaryPhone, value); } }
[DataCoreMember]
public string PrimaryEmail { get { return dataCore.PrimaryEmail; } set { SetProperty(ref dataCore.PrimaryEmail, value); } }
[DataCoreMember]
public string PrimaryWebsite { get { return dataCore.PrimaryWebsite; } set { SetProperty(ref dataCore.PrimaryWebsite, value); } }
Ok, finally... what I'd like for my abstract class is to use the BeginEdit(), EndEdit() and CancelEdit() methods to handle storage of a backup copy of the data core automatically. Here's how I envision it:
[DataCoreMember(MemberName="ID")]
public int? ID { get { return dataCore.ID; } set { SetProperty(ref dataCore.ID, value); } }
// etc etc
and in my abstract class:
public virtual void BeginEdit() {
Type t = typeof(T);
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(DataCoreMemberAttribute)));
// WHAT TO DO HERE??? everything else looks good up to here
foreach (object o in props) {
this.dataCoreBackup.???? = o.value;
}
IsEditing = true;
}
How to map the property to which the DataCoreMember is applied to the property of the struct as specified?
I'm inexperienced with reflection (and working generic types as well for that matter), but I gather that this can be done. I've found examples (as of yet untried) for how to get a list of those properties with the attribute applied to them, but I'm unsure how to ultimately reference the DataCore's property based on that. Can anyone show me how? Much appreciated.
Turns out it was a fairly easy task with Reflection. Explanation below (with much of the non-pertinent code stripped out)
This holds the data backup so CancelEdit is supported:
public struct CompanyDataCore
{
public int? ID;
public string Code;
public string Name;
public string PrimaryWebsite;
public string PrimaryPhone;
public string PrimaryEmail;
public string RootPath;
}
Here's the attribute class to denote which fields get backed up:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class DataCoreMemberAttribute : Attribute
{
public string MemberName { get; set; }
}
This is the derived class:
public class CompanyModel : ModelObject<CompanyModel, CompanyDataCore, int>
{
[Identifier]
[DataCoreMember(MemberName="ID")]
public int? ID { get { return dataCore.ID; } set { SetProperty(ref dataCore.ID, value); } }
[DataCoreMember(MemberName="Name")]
public string Name { get { return dataCore.Name; } set {SetProperty(ref dataCore.Name, value); } }
[DataCoreMember(MemberName="Code")]
public string Code { get { return dataCore.Code; } set { SetProperty(ref dataCore.Code, value); } }
[DataCoreMember(MemberName="PrimaryPhone")]
public string PrimaryPhone { get { return dataCore.PrimaryPhone; } set {SetProperty(ref dataCore.PrimaryPhone, value); } }
[DataCoreMember(MemberName="PrimaryEmail")]
public string PrimaryEmail { get { return dataCore.PrimaryEmail; } set { SetProperty(ref dataCore.PrimaryEmail, value); } }
[DataCoreMember(MemberName="PrimaryWebsite")]
public string PrimaryWebsite { get { return dataCore.PrimaryWebsite; } set { SetProperty(ref dataCore.PrimaryWebsite, value); } }
}
And here's the abstract class:
public abstract class ModelObject<T, DataCoreType, IDType> : INotifyPropertyChanged, IEditableObject
{
protected DataCoreType dataCoreBackup;
public virtual void BeginEdit() {
Type t = typeof(T);
// get a the properties with the attribute
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(DataCoreMemberAttribute)));
// backup needs to be boxed because it's a struct
object boxedBackup = this.dataCoreBackup;
foreach (var prop in props) {
foreach (CustomAttributeData attribData in prop.GetCustomAttributesData()) {
if (attribData.Constructor.DeclaringType == typeof(DataCoreMemberAttribute)) {
object origValue = prop.GetValue(this);
FieldInfo field = boxedBackup.GetType().GetField(attribData.NamedArguments[0].TypedValue.Value.ToString());
field.SetValue(boxedBackup, origValue);
}
}
}
this.dataCoreBackup = (DataCoreType)boxedBackup;
IsEditing = true;
}
... and now I can get INotifiyPropertyChanged and IEditbaleObject handled in an abstract class so I don't have to write a bunch of plumbing in each specific model that I'm going to use.
Hopefully someone else can find this useful.

C#, read / write separation and properties. Pattern required

Ok, so C# has properties
public int Prop {get;set;}
I can put the getter and the setter on separate interfaces like this:
public interface IRead
{ int AnInt { get; } }
public interface IWrite
{ int AnInt { set; } }
And then mix and match them like so:
public class WorkingClass : IRead, IWrite
{
public int AnInt { get; set; }
}
Where it starts to go wrong is where I might have a base object.
public class BaseClass : IRead
{
private int _anInt;
public BaseClass(int anInt)
{ _anInt = anInt; }
public virtual int AnInt
{ get { return _anInt; } }
}
I then want a derived class which can write as well.
public class Derived : BaseClass, IWrite //bits elided
{
public override int AnInt
{
get { return base.AnInt; }
set { throw new NotImplementedException(); } //<-- error
}
}
Which of course doesn't work.
This actually doesn't come up that often. I prefer to have methods with change state and have properties read only. This is design 101 I guess, but as a contrived example, I'd have an Age property with just a get and then a method called IncreaseAge.
So with that all in mind. If you did want to have a mutable object with seperate read and write interfaces how would you do it?
I could do it in a Java-esque way with separate getter/setter methods on each interface. But that negates the benefits of properties + one of the cop programs will yell at me.
You can have the base setter protected and have the derived class implement IWrite explicitly delegating to the base setter:
public class BaseClass : IRead {
public BaseClass(int anInt) { AnInt = anInt; }
public int AnInt {
get; protected set;
}
}
public class Derived : BaseClass, IWrite {
public Derived(int anInt) : base(anInt) { }
int IWrite.AnInt {
set { base.AnInt = value; }
}
}
(The keyword base can even be omitted and the base property doesn't need to be virtual.)

Calling FindAll on derived classes using Castle ActiveRecord class table inheritance

I'm implementing a type hierarchy using class table inheritance. However, I'm having trouble with the static methods returning the base type instead of the child type. I've found a way around this but it's not too pretty. Take the following classes
public class Entity : ActiveRecordBase<Entity> { }
public class Person : Entity {}
calling
Person.FindAll();
actually returns an Entity[] instead of a Person[]. I can get around this by implementing FindAll in all derived classes, but who wants to do that? I was also able to create a base class that all classes derive from and implement
public R[] FindAll<R>() {}
but I just don't like the look of
Person.FindAll<Person>()
Is there any way to be able to call FindAll() from the derived classes and actually get the derived classes instead of the base class?
That's how .net works: there's no polymorphism for static methods. You already found a couple of workarounds, another one is not to rely on these static methods inherited from ActiveRecordBase<T>, but instead use ActiveRecordMediator<T> directly.
Maybe you could do:
public class Entity<T> : ActiveRecordBase<T> { }
public class Person : Entity<Person> {}
That way FindAll() would return Person[]
Even the documentation of Castle.ActiveRecord uses the workaround that you found.
See here for a full example and some other solutions: http://docs.castleproject.org/Default.aspx?Page=Type%20hierarchy&NS=Active%20Record
I copied the code in case that site disappears.
Base class "Entity"
using Castle.ActiveRecord;
[ActiveRecord("entity"), JoinedBase]
public class Entity : ActiveRecordBase
{
private int id;
private string name;
private string type;
public Entity()
{
}
[PrimaryKey]
private int Id
{
get { return id; }
set { id = value; }
}
[Property]
public string Name
{
get { return name; }
set { name = value; }
}
[Property]
public string Type
{
get { return type; }
set { type = value; }
}
public static void DeleteAll()
{
DeleteAll(typeof(Entity));
}
public static Entity[] FindAll()
{
return (Entity[]) FindAll(typeof(Entity));
}
public static Entity Find(int id)
{
return (Entity) FindByPrimaryKey(typeof(Entity), id);
}
}
Derived classes "Person" and "Company"
using Castle.ActiveRecord;
[ActiveRecord("entitycompany")]
public class CompanyEntity : Entity
{
private byte company_type;
private int comp_id;
[JoinedKey("comp_id")]
public int CompId
{
get { return comp_id; }
set { comp_id = value; }
}
[Property("company_type")]
public byte CompanyType
{
get { return company_type; }
set { company_type = value; }
}
public new static void DeleteAll()
{
DeleteAll(typeof(CompanyEntity));
}
public new static CompanyEntity[] FindAll()
{
return (CompanyEntity[]) FindAll(typeof(CompanyEntity));
}
public new static CompanyEntity Find(int id)
{
return (CompanyEntity) FindByPrimaryKey(typeof(CompanyEntity), id);
}
}
[ActiveRecord("entityperson")]
public class PersonEntity : Entity
{
private int person_id;
[JoinedKey]
public int Person_Id
{
get { return person_id; }
set { person_id = value; }
}
public new static void DeleteAll()
{
DeleteAll(typeof(PersonEntity));
}
public new static PersonEntity[] FindAll()
{
return (PersonEntity[]) FindAll(typeof(PersonEntity));
}
public new static PersonEntity Find(int id)
{
return (PersonEntity) FindByPrimaryKey(typeof(PersonEntity), id);
}
}

How to increase the access modifier of a property

I'm trying to create a set of classes where a common ancestor is responsible for all the logic involved in setting various properties, and the descendants just change the access of properties depending on whether they are required in the particular descendant.
When I try to do it as shown below I get a compiler error: "cannot change access modifiers when overriding 'protected' inherited member"
Is there a way to achieve what I'm trying to do? Thanks
public class Parent
{
private int _propertyOne;
private int _propertyTwo;
protected virtual int PropertyOne
{
get { return _propertyOne; }
set { _propertyOne = value; }
}
protected virtual int PropertyTwo
{
get { return _propertyTwo; }
set { _propertyTwo = value; }
}
}
public class ChildOne : Parent
{
public override int PropertyOne // Compiler Error CS0507
{
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
// PropertyTwo is not available to users of ChildOne
}
public class ChildTwo : Parent
{
// PropertyOne is not available to users of ChildTwo
public override int PropertyTwo // Compiler Error CS0507
{
get { return base.PropertyTwo; }
set { base.PropertyTwo = value; }
}
}
You can do this by using "new" instead of "override" to hide the parent's protected property as follows:
public class ChildOne : Parent
{
public new int PropertyOne // No Compiler Error
{
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
// PropertyTwo is not available to users of ChildOne
}
public class ChildTwo : Parent
{
// PropertyOne is not available to users of ChildTwo
public new int PropertyTwo
{
get { return base.PropertyTwo; }
set { base.PropertyTwo = value; }
}
}
You can't change the access, but you can re-declare the member with greater access:
public new int PropertyOne
{
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
The problem is that this is a different PropertyOne, and inheritance / virtual might not work as expected. In the above case (where we just call base.*, and the new method isn't virtual) that is probably fine. If you need real polymorphism above this, then you can't do it (AFAIK) without introducing an intermediate class (since you can't new and override the same member in the same type):
public abstract class ChildOneAnnoying : Parent {
protected virtual int PropertyOneImpl {
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
protected override int PropertyOne {
get { return PropertyOneImpl; }
set { PropertyOneImpl = value; }
}
}
public class ChildOne : ChildOneAnnoying {
public new int PropertyOne {
get { return PropertyOneImpl; }
set { PropertyOneImpl = value; }
}
}
The important point in the above is that there is still a single virtual member to override: PropertyOneImpl.
NO. Still you can Hide the inherited property with Your's
public class ChildTwo: Praent {
public new int PropertyTwo {
// do whatever you want
}
}
ps: this is no longer virtual/override relationship (i.e. no polymorphic calls)

Categories

Resources