Can't see properties from interface - c#

I'm having some interface woes!
Here's the code:
I expected to be able to access the properties Added and ID through my test template, but intellisense says No!
Am I misusing an interface? Have I made a silly error?
Any advice appreciated - this is driving me nuts.
namespace blah.blah.blah
{
public interface ITrackedItem
{
DateTime Added { get; set; }
int ID { get; set; }
}
public class TestTemplate<ITrackedItem>
where ITrackedItem : new()
{
public SortedSet<ITrackedItem> Set { get; set; }
public void Test()
{
Set = new SortedSet<ITrackedItem>();
foreach (var item in Set)
{
// cannot access any properties here
// var ID = item.ID; <=============|
}
}
}
}

This is the problem:
public class TestTemplate<ITrackedItem>
You've declared a type parameter called ITrackedItem, which is entirely different to the ITrackedItem interface. It's not clear that your type needs to be generic at all - can you not just use
public class TestTemplate
? If you want it to be generic in a type which must implement ITrackedItem, you should use something like:
public class TestTemplate<T>
where T : ITrackedItem, new()
{
public SortedSet<T> Set { get; set; }
public void Test()
{
Set = new SortedSet<T>();
foreach (var item in Set)
{
// now you can access any properties here
//
}
}
}

Related

C#: How to statically get property attribute

I am looking for an elegant way of statically referencing a property attribute in C#. To give you an example, say I have this class:
public class A
{
[Attribute(Name="myAttributeName")]
public string Property1 { get; set; }
}
Now, I see the attribute as quite similar to a static member of a class, so in my mind, there should be an easy way to access the attribute from outside the class; e.g. through a similar operator to typeof or nameof (but it would return a list of attributes, since there may be multiple attributes to fetch). The way I would like to use this operator is as follows:
public class B
{
// Through an attribute definition
[Attribute2(attrof(A.Property1))]
public string Property2 { get; set; }
// In a method
public void method()
{
var attrs = attrof(A.property1);
}
}
I think I have found one way to make it work with two parameters like the example below - at least for the method invocation. Passing variables to attributes doesn't seem to work in C#, but that's nevertheless the way I'd like to construct my code.
public class C
{
public static object[] GetAttrs(Type type, string propertyName)
{
return type.GetProperty(propertyName).GetCustomAttributes(true);
}
}
public class A
{
[Attribute1(Name="myAttributeName")]
public string Property1 { get; set; }
}
public class B
{
// Through an attribute definition
// Unfortunately, passing variable to attrs not supported
// so this does not work
[Attribute2(C.GetAttrs(typeof(A), nameof(A.Property1)))]
public string Property2 { get; set; }
// In a method
public void method()
{
var attrs = C.GetAttrs(typeof(A), nameof(A.Property1));
}
}
However, it feels tedious to pass references to both the class and property, when syntactically, A.Property1 contains information about both - something a compiler should be able to draw information from. Therefore, I wonder if any such operator exists today, or if there are any other ideas on how this functionality could be achieved?
EDIT: I just thought about the B.Property2 attribute definition one more time and thought that it should still be possible to get this working, since I think attributes are constant. Or am I missing something here?
There is no default operator for such case, but you could implement something similar. Code to extract value from A.Property1 attribute is in Main function
using System;
using System.Reflection;
namespace ConsoleApp16
{
public class CustomAttribute : Attribute
{
public string Name { get; }
public CustomAttribute(string name)
{
Name = name;
}
}
public class ReferenceAttribute : Attribute
{
public string PropertyName { get; }
public Type Type { get; }
public ReferenceAttribute(Type type, string propertyName)
{
Type = type;
PropertyName = propertyName;
}
}
public class A
{
[Custom("text")]
public string Property1 { get; set; }
}
public class B
{
[Reference(typeof(A), nameof(A.Property1))]
public string Property { get; set; }
}
class Program
{
static void Main(string[] args)
{
var referenceAttribute = typeof(B).GetProperty(nameof(B.Property))
.GetCustomAttribute<ReferenceAttribute>();
var customAttribute = referenceAttribute.Type.GetProperty(referenceAttribute.PropertyName)
.GetCustomAttribute<CustomAttribute>();
Console.WriteLine(customAttribute.Name);
}
}
}

Copy all properties of strongly typed object into DynamicObject

Is there an easy way to copy everything from a strongly typed object into a dynamic one? The target has to be a DynamicObject as determined by a 3rd party library I'm using. Everything from TypedModel needs to go into MyDynamicObject at runtime.
public class MyDynamicObject : DynamicThirdPartyObject
{ }
public class TypedModel
{
public string text { get; set; }
public int number { get; set; }
public List<SomeOtherModel> someList { get; set; }
}
Existing solutions I found on SO all match up properties between typed classes.
EDIT
Found a simple solution based on FastMember:
public void CopyProperties(object source, DynamicObject target)
{
var wrapped = ObjectAccessor.Create(target);
foreach (var prop in source.GetType().GetProperties())
{
wrapped[prop.Name] = prop.GetValue(source);
}
}
I propoes to use reflection.
suppose you make following declaration:
public class MyDynamicObject : DynamicThirdPartyObject
{ }
public class TypedModel
{
public string text { get; set; }
public int number { get; set; }
public List<SomeOtherModel> ListOtherModel { get; set; }
}
Lets say you want to get properties of instance:
typedModel.GetType().GetProperties();
Another possible situation is if you want to copy type:
typeof(TypedModel).GetProperties();
TypedModel typeModel = new TypedModel {number = 1, text = "text1",
ListOhterModel = new List()
};
foreach(var prop in typeModel.GetType().GetProperties())
{
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(typeModel, null));
}
And if you need to go through hierarchy, maybe you need to use recursion, in order to go through nested types, I mean you can use reflection for copying all members of SomeOtherModel.

Dynamic cast behavior in loop

I'm trying to accomplish some hacking & slashing and was wondering how to approach the following.
There are 2 interfaces defined:
public interface IBase
{
string Name { get; }
void Run();
}
public interface ISecondBase<T> : IEntityTask
{
Thing<T> Thing { get; }
}
Somewhere else I have a list of IBase.
This list is filled ISecondBase. I would like to be able to loop through the list of Base, but using some reflection tricks and hacks als be able to call Thing on the items. I know they're there, the compiler doesn't.
So I'd have to cast it to its concrete type at runtime, but this cast has to be dynamic, based on reflected information in the loop... So all type information is dynamic... I'm starting to think in circles :)
Since I know on beforehand that everything inside it is always of the SecondBase type, I decided to use the dynamic keyword and just let it resolve at runtime. This seems to me like an easy way out. Is there some best practice for these cases? Should I redesign, without loss of generality, and how?
foreach(var x in y)
{
dynamic melp = x;
melp.Thingy;
}
Where to start?
Edit: Perhaps some more code to make the example less contrived.
I have the base classes as mentioned. In real life they look like this:
public interface IEntityTask
{
string Name { get; }
void Run();
}
public interface IEntityTask<T> : IEntityTask
{
Task<T> Task { get; }
}
//Then there are classes that implement these:
public class CreateEntityTask<T> : IEntityTask<Guid>
{
public T Entity { get; private set; }
public Func<T, Guid> EntityMethod { get; private set; }
public Task<Guid> Task { get; private set; }
public void Run()
{
Task = Task<Guid>.Run(() => entityAccess.CreateEntity<T>(Entity, EntityMethod));
}
}
public class ReadEntityTask<T> : IEntityTask<T>
{
public Guid EntityId { get; private set; }
public Func<Guid, T> EntityMethod { get; private set; }
public Task<T> Task { get; private set; }
public void Run()
{
Task = Task<T>.Run(() => entityAccess.ReadEntity<T>(EntityId, EntityMethod));
}
}
//Furthermore there is a class called EntityTaskManager, which holds a list of these things and runs, awaits & collects the results on them.
public class EntityTaskManager
{
public List<IEntityTask> EntityTasks { get; set; } // I want tasks of Guid and bool in here!!!!
public Dictionary<string, object> EntityTaskResults { get; set; }
}
In a calling class I construct a new EntityTask and add it to the list. And then call RunTasks on the manager.
I'd modify IEntityTask like this:
public interface IEntityTask
{
string Name { get; }
void Run();
object Result { get; }
}
If EntityTaskManager is the only place, where you work with IEntityTask type, the implementation of Result would be explicit:
public class CreateEntityTask<T> : IEntityTask<Guid>
{
/* The rest of code here */
object IEntityTask.Result
{
get { return Task.Result; }
}
}
Then fetching task results should be trivial:
var results = entityTasksManager
.EntityTasks
.Select(t => t.Result);

How to allow nested class instances modification in PropertyGrid not having access to inspected classes code?

Say we have a simple class model with classes as feilds (inside compiled, not modifiable Dll):
public class SubSubClassTest {
public int Data { get; set; }
}
public class SubClassTest {
public string InnerStr { get; set; }
public int InnerInteger { get; set; }
public SubSubClassTest InnerLoad { get; set; }
public SubClassTest() {
InnerLoad = new SubSubClassTest();
}
}
public class Test {
public string Str { get; set; }
public int Integer { get; set; }
public SubClassTest Load { get; set; }
public Test() {
Load = new SubClassTest();
}
}
And we want to edit it using PropertyGrid.
public partial class ApplicationForm : Form {
public ApplicationForm() {
InitializeComponent();
var test = new Test();
propertyGrid.SelectedObject = test;
}
}
And I do not have abilety to change classes (as I get them from Dll) and they have no [TypeConverter(typeof(ExpandableObjectConverter))] attribute on all members that are classes I get sush picture:
And members that are from my namespace class type are not editable.
If all such members havd [TypeConverter(typeof(ExpandableObjectConverter))] attribute I would have another picture and all would be fine:
I wonder how to make PropertyGrid use PropertyGrid for all nested classes?
You could try changing the TypeConverterAttribute value using PropertyDescriptor and Reflection. I wouldn't recommend to do this but to show that its possible I have added the sample code. I verified with your example and it works. But I cannot assure that it would work in all scenarios. Food for thought...
var test = new Test();
SetTypeConverterAttribute(test);
propertyGrid.SelectedObject = test;
private void SetTypeConverterAttribute(Test test)
{
foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(test))
{
TypeConverterAttribute attribute = item.Attributes[typeof(TypeConverterAttribute)] as TypeConverterAttribute;
if (attribute != null && item.PropertyType == typeof(SubClassTest))
{
FieldInfo field = attribute.GetType().GetField("typeName", BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
field.SetValue(attribute, typeof(ExpandableObjectConverter).FullName);
}
}
}
}
If you have control over the classes, you can create a common base class and decorate this base class with the TypeConverterAttribute. In that case, any property that will reference any instance of this type will use the ExpandableObjectConverter, unless this behavior is overridden by the property (using another TypeConverterAttribute).

Using Reflection and GetValue problems

I have an abstract class that looks like so:
public abstract class PageObjectsBase
{
public abstract string FriendlyName { get; }
public abstract string PageObjectKeyPrefix { get; }
public abstract string CollectionProperty { get; }
}
And a class that derives from PageObjectsBase:
public class PageRatingList : PageObjectsBase
{
public IList<PageRating> PageRatings { get; set; }
public PageRatingList()
{
this.PageRatings = new List<PageRating>();
}
public override string CollectionProperty
{
get
{
var collectionProperty = typeof(PageRatingList).GetProperties().FirstOrDefault(p => p.Name == "PageRatings");
return (collectionProperty != null) ? collectionProperty.Name : string.Empty;
}
}
public override string FriendlyName
{
get
{
return "Page feedback/rating";
}
}
public override string PageObjectKeyPrefix
{
get
{
return "pagerating-";
}
}
}
And a PageRating class which PageRatingList.PageRatings is holding a collection of:
public class PageRating : PageObjectBase
{
public int Score { get; set; }
public string Comment { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
The PageRatingList is being stored in a database (EPiServer's Dynamic Data Store, more specifically using the Page Object Manager). I need to create some reporting functionality and am essentially loading all reports that derive from PageObjectBase. When it comes to returning the data, the code will never know at compile time what type of data it is to load, so I am using Reflection. In my reporting class I have:
//this gives me the right type
var type = Type.GetType("MyNameSpace.PageRatingList", true);
var startPageData = this._contentRepository.Get<PageData>(startPage);
PageObjectManager pageObjectManager = new PageObjectManager(startPageData);
//this loads the instances from the DB
var props = pageObjectManager.LoadAllMetaObjects()
.FirstOrDefault(o => o.StoreName == "Sigma.CitizensAdvice.Web.Business.CustomEntity.PageRatingList");
//this gives me 4 PropertyInfo objects (IList: PageRatings, string : CollectionProperty, string :FriendlyName, string : PageObjectKeyPrefix)
var properties = props.Value.GetType().GetProperties();
I can then iterate through the PropertyInfo objects using:
foreach (var property in properties)
{
//extract property value here
}
The issue I am having is that I cannot figure out how to get the value of each of the propertyinfo objects. In addition, one of those properties is type List and again we wont know the type of T until runtime. So I also need some logic that checks if one of the PropertyInfo objects is of type List and then provides access to each of the properties in the List - the List being of type PageRating.
Can anyone help here? I've not really used reflection in the past so I am winging my way through it, rightly or wrongly!
Many thanks
Al
I may be missunderstanding the problem, but i think you may use something like this:
var props = new PageRatingList(); /*actual instanse of the object, in your case, i think "props.Value" */
var properties = typeof(PageRatingList).GetProperties();
foreach (var property in properties)
{
if (property.PropertyType == typeof(IList<PageRating>))
{
IList<PageRating> list = (IList<PageRating>)property.GetValue(props);
/* do */
}
else
{
object val = property.GetValue(props);
}
}
Hope this helps to find your solution.

Categories