I apologize in advance if this gets a little convoluted.
I have an attribute class like so:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class RepositoryCollectionMethodAttribute : Attribute
{
public string MethodName { get; set; }
public RepositoryCollectionMethodAttribute(string methodName)
{
MethodName = methodName;
}
}
I am traversing my class domain using EnvDTE, collecting classes for code generation. Finding a class that decorates one or more properties with the RepositoryCollectionMethod.
This part was relatively easy, so for each class with some of these properties decorated, I now have an IEnumerable<CodeProperty> I call properties.
Now I'm stuck. Due to the nature of these EnvDTE objects (which seem to have an aversion to strong typing and good documentation/ examples) I cannot figure out how to extract a distinct list of MethodName property values from the collection of properties, at least one of which will have a RepositoryCollectionMethod decorating it.
In other words, if I have a class `Foo' like this:
public class Foo
{
public Guid FooId { get; set; }
[RepositoryCollectionMethod("GetFoosByCategory")]
public string Category { get; set; }
[RepositoryCollectionMethod("GetFoosByClass")]
[RepositoryCollectionMethod("GetFoosByClassAndLot")]
public string Class { get; set; }
[RepositoryCollectionMethod("GetFoosByLot")]
[RepositoryCollectionMethod("GetFoosByClassAndLot")]
public string Lot { get; set; }
}
...given an IEnumerable<CodeProperty> of Foo's properties, I would like to generate the following list:
GetFoosByCategory
GetFoosByClass
GetFoosByClassAndLot
GetFoosByLot
Can anyone help me with this?
Related
In my ASP.NET Core API, I have a DTO class BaseBDto and another DerivedBDto that inherits from it, and hides some of its properties, because they're required in DerivedBDto. The properties of BaseBDto and DerivedBDto are objects of another classes, BaseADto and DerivedADto respectively, that follow the same logic as the first ones. I also have a BaseModel class to which both BaseBDto and DerivedBDto will be mapped through another class Mapper.
Something like the following code:
using System.ComponentModel.DataAnnotations;
public class BaseADto
{
public string Name { get; set; }
}
public class DerivedADto : BaseADto
{
[Required]
public new string Name { get; set; }
}
public class BaseBDto
{
public BaseADto A { get; set; }
}
public class DerivedBDto : BaseBDto
{
[Required]
public new DerivedADto A { get; set; }
}
public class BaseModel
{
public string NameModel { get; set; }
}
public static class Mapper
{
public static BaseModel MapToModel(BaseBDto dto) => new BaseModel
{
NameModel = dto.A.Name
};
}
But it turns out, when passing a DerivedBDto object to the MapToModel method, it's trying to access the values of the BaseBDto (which are null) instead of the DerivedBDto ones.
Is there any way I can achieve this behavior?
I can only think of declaring BaseBDto as abstract, but that would prevent me from instantiating it, which I need to do.
PS: I already asked a similar question here, but I oversimplified my code sample, so I felt another question was necessary.
Also, the solution provided there doesn't work because I can't override the A property at DerivedBDto with a DerivedADto since it must have the same type as the A property at BaseBDto.
Have you tried changing the MapToModel signature to be generic. The below
public static BaseModel MapToModel<T>(T dto) where T : BaseBDto => new BaseModel
{
NameModel = dto.A.Name
};
I have a generic class with a single argument that represents an Element of a third party DLL for the purpose of serialization of objects of T kind. What I would like to do is add a 'Dirty' map to my class and lazily trigger it whenever one of my Element's nested properties are changed.
Is it possible to when the property is accessed catch the request and identify what property is changing? That if a SET is being performed I can log that sub-property P is now dirty and needs to be saved? Or at least a single bit that indicates that SOMETHING has changed?
public class ResourceSerializer<T>
where T : Base, new()
{
T element;
Dictionary<String,Boolean> dirtyMap;
public T Element { get { return this.getElement(); } }
public Boolean IsDirty { get; private set; }
public ResourceSerializer()
{
dirtyMap = new Dictionary<string,bool>();
element = new T();
// code to reflect back upon T's Properties and build out the dirtyMap.
// I already can do this I just omitted it.
// in my Person example there would be keys: 'FirstName', 'LastName', 'Age', 'Gender', 'PrimaryAddress'
}
// how can I call this programmatically?
void flagDirty(String property)
{
dirtyMap[property] = true;
this.IsDirty = true;
}
T getElement()
{
// In case I need to do a thing before returning the element.
// Not relevant to the question at hand.
return this.element;
}
}
a somewhat advanced example of 'Base'. You can see how I need to recurse my actions as not everything is a primitive. I have a manager level class that logs all of these ResourceSerializer objects.
public class Base
{
public Base()
{
}
}
public enum gender
{
Male,
Female,
Other,
Unspecified,
}
public class Address : Base
{
public String Street { get; set; }
public String State { get; set; }
public String Zip { get; set; }
public Address() : base()
{
}
}
public class Person : Base
{
public String FirstName { get; set; }
public String LastName { get; set; }
public Int16 Age { get; set; }
public gender Gender { get; set; }
public Address PrimaryAddress { get; set; }
public Person() : base()
{
}
}
public class Patient : Person
{
public Person PrimaryContact { get; set; }
public Patient() : base()
{
}
}
and a small class i would turn into a test method later..
public class DoThing
{
public DoThing()
{
ResourceSerializer<Person> person = new ResourceSerializer<Person>();
person.Element.Age = 13; // catch this and mark 'Age' as dirty.
}
}
Without a custom setter no, there's nothing to do that.
The usual pattern for what you're trying to do is implement the INotifyPropertyChanged interface, that interface is precisely created for classes (or structs) which need to track and inform about changes on their properties.
If you're lazy as me, I would create an analyzer which at the beginning of my app scans all my classes which are tagged with an attribute and with all properties created as virtual, then using codedom I would create a new class which would inherit from the found class and it implements the INotifyPropertyChanged, then you can have a generic Factory which returns instances of these new classes when the type of the generic call is of a known registered type.
I've used this before for classes which I wanted to have remote properties, just tagged the class and my scan system rewrote the getter/setter to do the remote calls transparently, the concept at the end is the same.
It's a lot of work at the begining, but if you have a ton of classes it will be a lot less of code to write than implementing INotifyPropertyChanged on all your classes.
I have a bunch of settings that can be one of many types. For example, URL, text, number, etc. Based on other posts I came up with the following that seems to work okay:
public abstract class SettingViewModel
{
public string Name { get; set; }
public string Description { get; set; }
public SettingType Type { get; set; }
public string DefaultValue { get; set; }
public Module? Module { get; set; }
}
public class SettingViewModel<T> : SettingViewModel
{
[Required]
public T Value { get; set; }
}
My biggest problem with this is that when it comes time to read the values in Value for each setting I want to do have a method like. I wouldn't want to change the shape of this method really, because I want to keep it generic and it will be exposed as a Controller Method in MVC
public void Update(SettingViewModel Setting)
{
GS_SysConfig setting = new GS_SysConfig();
//might also just use a util function to convert to string based on the type of Value
setting.ConfigVal = Setting.Value.ToString(; //Value is not a field in the abstract class
db.SaveChanges();
}
This won't work because Value is not a field in the parent class, and I suppose I could come up with some way of doing casting and and getting types and such, but it seems messy and not very elegant. Is there a better approach to tryign to accomplish what I'm trying to do?
Update:
ConfigVal is of type String
I'm looking for a class structure or design pattern to implement a base class that has a list of "base items", where several derived classes have the same list but that list is of derived "base items".
Here's a vastly stripped down example (ignore the accessibility of properties, they wouldn't actually all have public setters and default constructors):
public class BaseTransaction {
public List<BaseTransactionItem> Items { get; set; }
public void AddItem(string description, int quantity, decimal price)
{
// Add a new BaseTransactionItem to Items
}
}
public class BaseTransactionItem {
public string Description { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
public class OrderTransaction : BaseTransaction {
public List<OrderTransactionItem> Items { get; set; }
public int Deposit { get; set; }
public void SetDeposit(int depositAmount)
{
// Do some stuff to set the deposit.
}
}
public class OrderTransactionItem : BaseTransactionItem
{
public int QuantityFulfilled { get; set; }
}
public class RetailTransaction : BaseTransaction {
public List<RetailTransactionItem> Items { get; set; }
public List<Tender> Tenders { get; set; }
public void AddTender(Tender tender)
{
// Add a tender to the RetailTransaction
}
public decimal TotalTax
{
get { return Items.Sum(i => i.Tax); }
}
}
public class RetailTransactionItem : BaseTransactionItem
{
public decimal Tax { get; set; }
}
The way I need to work with these classes is that you start with a BaseTransaction and add some items to it, and then it can become either an OrderTransaction or a RetailTransaction. These both share most of their logic and properties with a BaseTransaction but have specific extra fields and methods, as well as the List<BaseTransactionItem> becoming a List<OrderTransactionItem> or a List<RetailTransactionItem> respectively.
Further more, after a BaseTransaction is "promoted" to a RetailTransaction, it may be "demoted" back to a BaseTransaction and then "promoted" to an OrderTransaction (but never from a RetailTransaction to an OrderTransaction in this case).
I've tried several approaches to this, with generics, the Decorator pattern (which doesn't seem appropriate), TypeConverters, and yet nothing seems to fit. The only possible solution I've thought of that works is having the RetailTransaction class have a constructor that takes a BaseTransaction and copying over all the properties and converting the list using .Cast<RetailTransactionItem> but this will make maintaining the derived classes pretty difficult.
If it wasn't for the list type needing to change this would be a simple case of using inheritance. I'm completely open to alternative approaches such as those favouring composition over inheritance but since the RetailTransaction and OrderTransaction classes truely are more specific versions of BaseTransaction, inheritance seems to fit - at least in my mind.
I have 5 Properties within my class that are all very similar; I want to group them. The class they are contained in used to look like this:
class Car
{
public string PropA { get; set; }
public string PropB { get; set; }
public string PropC { get; set; }
public Car() { }
}
So with Intellisense, I would be presented with:
Car car = new Car();
car.PropA
.PropB
.PropC
..I would be presented with the 3 properties. What I want is for it to be contained within it's own little group, so I would have to do:
car.Props.PropA = "example";
I created a partial class to hide them in, but I am not sure if this is the correct way to do it:
class Car
{
public Props { get; set; }
public Car() { }
}
partial class Props
{
public string PropA { get; set; }
public string PropB { get; set; }
public string PropC { get; set; }
}
Is there a better way to go about this? I ask because I am creating a class library and usability is very important.
The partial keyword is used to split a class's implementation among multiple files. Knowing that, it doesn't help (or hurt) in this situation.
Without knowing more about your design, your solution seems reasonable. Just get rid of the partial keyword, it's not appropriate here.
Agreed with what Patrick said. I had a question about your public setters though, and this is something I've been curious about how to handle myself.
if you're hoping for other people to use thing class (and assuming this wasn't just a mocked up example) are you sure you want people to just be able to willy nilly be able to set properties in your classes without going through a method/function that validates and/or handles the setting of the property?
this can be done like:
public class Props
{
public string PropA { get; private set; }
public string PropB { get; private set; }
public string PropC { get; private set; }
}
public Props() { }
public SetProps(string propA, string propB, string propC)
{
this.PropA = propA;
this.PropB = propB;
this.PropC = propC;
}
Now obviously doing something like this would depend on the nature of the requirements around the props (and this is an extremely simple example - all props have to be set at the same time). But with public setters a user of the class would not necessarily know the nature of the requirements, and the public setters could potentially allow them a way around how it was intended the class be used.