Accessing generic object passed into generic class - c#

I'm trying to use a generic class to pass in a data object then uses the values within to complete CRUD operations.
class OrderState<TGrainState> : Grain, IState where TGrainState : class
{
protected TGrainState State { get; set; }
public Task Get()
{
using (var context = new SDbContext())
{
//Passing Null instance because not sure how to access the instance of the state object
var test = typeof(TGrainState).GetProperty("id").GetValue(null);
//int t = (int)test;
//var obj = context.orders.Where(x => x.Id == t);
//return Task.FromResult(obj);
}
return Task.CompletedTask;
}
}
TGrainState is the generic object I want to pass in.
public class State
{
public int Id { get; set; }
public DateTime Created { get; set; }
public string AssignedOrganization { get; set; }
public bool isComplete { get; set; }
public string assignedUser { get; set; }
}
This is the state class I'm attempting to pass into the generic class.
class OrderGrain : OrderState<State>, IOrder
{
public override Task OnActivateAsync()
{
//Should fill the State Object from the Db
Get();
//Sets the information contained in the State to the Object
this.orderInfo = new OrderInfo
{
Id = State.Id,
Created = State.Created,
AssignedOrganization = State.AssignedOrganization,
isComplete = State.isComplete,
assignedUser = State.assignedUser
};
return base.OnActivateAsync();
}
}
Class that inherits from the State Generic class that contains all of the CRUD operations.
So what I'm more or less trying to accomplish is how Microsoft Orleans has it's state setup where you create a state object, operate on that, then call Write(), Update(), Delete(), or Get() to perform the CRUD operation on the DB with Entity Framework using the state data declared.
The question is when I try to access the Values of the properties of the State object (State) inside the generic class (OrderState) I get the Error
System.Reflection.TargetException: 'Non-static method requires a
target.'
Link to the Orleans information that i'm trying to mimic.
Microsoft Orleans Grain Persistence
I might thinking about this wrong or just be completely wrong, so any help would be greatly appreciated.

I'm going to assume that this is a simple case of case-mismatching (pun not intended).
In this line:
var test = typeof(TGrainState).GetProperty("id").GetValue(null);
You are looking for the property id. However, your class declares it this way:
public int Id { get; set; }
The return value of the GetProperty method is "An object representing the public property with the specified name, if found; otherwise, null." Invoking GetValue on a null instance would result in the exception you're seeing.

Related

How to access the object's specific properties from a list of objects sharing the same interface

I have an application where i have say 10 objects of different types. I wish to have them in same list and iterate through them on many occasions. I cant push them into one list because they are of different types. So i created an interface and created a property that all objects share. Now i have the list of objects and type of the list is the "interface". When i iterate through the object, i can't access the specific properties of the object because the compiler will only know at runtime what object it is. So if i try to code Object_A.Name, visual studio will show error because it doesn't know they type of object. I can obviously do an if else or something similar to find the type of object and cast it, but i want to know of there is a better way, or if this whole approach of having an interface is wrong and if i should have begun in a different direction.
In the code below, i want to get the Devname, which i can't because its not part of the interface, but belongs to every object. I could make it part of the interface, but every now and then i may need to get a specific property. hence wanting to know if there is a way to do it.
foreach (ICommonDeviceInterface device in Form1.deviceList)
{
if (device.DevName.Equals(partnername))
{
return device.Port[portNo].PortRef;
}
}
One way you could do this is by using reflection to try to get the property value of a named property from an object, using a helper method like:
public static object GetPropValue(object src, string propName)
{
return src?.GetType().GetProperty(propName)?.GetValue(src, null);
}
Credit for above code goes to: Get property value from string using reflection in C#
This requires no checking types or casting, it just returns the value of the property, or null if it doesn't contain the property.
In use it might look like:
private static void Main()
{
// Add three different types, which all implement the same interface, to our list
var devices = new List<ICommonDeviceInterface>
{
new DeviceA {DevName = "CompanyA", Id = 1},
new DeviceB {DevName = "CompanyB", Id = 2},
new DeviceC {Id = 3},
};
var partnerName = "CompanyB";
foreach (var device in devices)
{
// Try to get the "DevName" property for this object
var devName = GetPropValue(device, "DevName");
// See if the devName matches the partner name
if (partnerName.Equals(devName))
{
Console.WriteLine($"Found a match with Id: {device.Id}");
}
}
}
Classes used for the sample above:
interface ICommonDeviceInterface
{
int Id { get; set; }
}
class DeviceA : ICommonDeviceInterface
{
public int Id { get; set; }
public string DevName { get; set; }
}
class DeviceB : ICommonDeviceInterface
{
public int Id { get; set; }
public string DevName { get; set; }
}
class DeviceC : ICommonDeviceInterface
{
public int Id { get; set; }
}
Use "as" and "is" to know what type of interface
public class A : ICommonDeviceInterface
{
public int AMember;
}
public class B :ICommonDeviceInterface
{
public int BMember;
}
foreach (ICommonDeviceInterface device in Form1.deviceList)
{
if(device is A)
{
A a = device as A;
a.AMember = 100;
}
else if(device is B)
{
B b = device as B;
b.BMember = 123;
}
}

Prototype pattern: ensure clone is in a valid state

LogEvent represents information like log level, message, user, process name, ...
Some of these properties' values require pretty much effort for generation, e. g. the process name. Those properties' generated values are usually not changed, BUT despite this fact it should be possible to change them.
I considered the prototype pattern starting with a protoype, whose generic properties are pre-allocated. The protoype stays the same object during the lifetime of the application, but its properties' values might change as described above. New LogEvent objects should use the current prototype's values, objects created before the change should continue using the old values, that means, referencing the prototype from the "real" LogEvent object is not an option.
However the "real" LogEvent requires some properties to be not null, whereas this requirement is not useful for the prototype. I would like to prevent invalid objects of LogEvent. However if I use usual protoype pattern I would have to add a constructor to create the prototype, but this constructor would not create a valid object and I want to avoid, that an invalid object (the prototype itself or a clone of it) is used accidentally.
I spent some time on searching a solution, but the approaches listed below are pretty ugly. I hope, that there is an elegant solution. Meanwhile I tend to option 3, because 1 and 2 do not seem to be clean.
General structure
public interface ILogEvent
{
string PreAllocatedProperty1 { get; set; }
string PreAllocatedProperty2 { get; set; }
string IndividualProperty1 { get; set; }
string IndividualProperty2 { get; set; }
}
Option 1
Pros
LogEventPrototype can not be used as ILogEvent.
properties do not have to be declared in multiple classes
Cons
properties have to be mapped manually
static methods => interface for prototypes not possible
Code
class LogEventPrototype
{
public string PreAllocatedProperty1 { get; set; }
public string PreAllocatedProperty2 { get; set; }
public string IndividualProperty1 { get; set; }
public string IndividualProperty2 { get; set; }
public LogEventPrototype() { GeneratePreAllocatedProperties(); }
private void GeneratePreAllocatedProperties()
{
// if you invoke the helper functions later again,
// they might return different results (e. g.: user identity, ...)
PreAllocatedProperty1 = Helper.ComplexFunction();
PreAllocatedProperty2 = Helper.AnotherComplexFunction();
}
}
class LogEvent : LogEventPrototype, ILogEvent
{
// just for creating the prototype, object will be in an INVALID state
private LogEvent() : base() { }
// object will be in a VALID state
public LogEvent(string individualProperty2)
: this()
{
if (individualProperty2 == null)
throw new ArgumentNullException();
IndividualProperty2 = individualProperty2;
}
public static LogEvent FromPrototype(LogEventPrototype prototype)
{
// clone manually
return new LogEvent(prototype.IndividualProperty2)
{
IndividualProperty1 = prototype.IndividualProperty1,
PreAllocatedProperty1 = prototype.PreAllocatedProperty1,
PreAllocatedProperty2 = prototype.PreAllocatedProperty2
};
}
}
Option 2
Similar to option 1, but:
Pros
it is "ensured", that LogEventPrototype is never instantiated, it is just used as return type
no manual mapping
Cons: It seems to be hacky.
class LogEventPrototype
{
// properties ... (same as in option 1)
protected LogEventPrototype()
{
GeneratePreAllocatedProperties();
}
}
class LogEvent : LogEventPrototype, ILogEvent
{
// constructors same as in option 1; FromPrototype() removed
public static LogEventPrototype CreateProtoype()
{
return new LogEvent();
}
public static LogEvent FromPrototype(LogEventPrototype prototype)
{
if(prototype.IndividualProperty2 == null)
throw new ArgumentException();
return (LogEvent)prototype;
}
public static LogEventPrototype CreateProtoype()
{
return new LogEvent();
}
}
Option 3
Do not use a dedicated class for prototypes, but make the LogEvent constructor public and risk invalid LogEvent objects. Use a Validate() method instead and hope, that a client does not forget to use it.

Method to handle objects with properties in common, but different object types

I have a large collection of automatically generated objects. Although they are all of different, non-related classes, all of the objects share some basic properties (name, id, etc.). I do not control the generation of these objects, so unfortunately I cannot take the ideal approach of implementing an interface. I would like to create a method in which I pass an arbitrary one of these objects and do something using these common properties.
The general idea would be something like:
someObj a = new someObj();
a.name = "sara";
diffObj b = new diffObj();
b.name = "joe";
string phrase = string.Format("I am with {0} and {1}",
getName(a), getName(b));
private string getName(object anyObjWithName)
{
return anyObjWithName.name;
}
though naturally this does not work.
I thought a generic method might hold the answer, but the only way I can see to call it with the current type is using genericMethod.Invoke , which still carries the same issue of not being able to resolve the properties of the passed object in the method. This is unlike Calling generic method with a type argument known only at execution time or How to call generic method with a given Type object? where only the type, or properties of the type, are used in the method, as opposed to properties of the object.
I am aware that this would be (very) prone to error, but I can guarantee that all objects encountered will have the common properties being manipulated.
I can guarantee that all objects encountered will have the common properties being manipulated
If that's the case, you can use dynamic:
private string getName(dynamic anyObjWithName)
{
return anyObjWithName.name;
}
Be aware that using any object that does not have a name property will not fail until run-time.
If you want to add a little bit of safety you can catch the RuntimeBinderException that gets thrown if the property does not exist:
private string getName(dynamic anyObjWithName)
{
try {
return anyObjWithName.name;
}
catch(RuntimeBinderException) {
return "{unknown}";
}
}
If you're unhappy with the performance using dynamic as mentioned by D Stanley, you could always try FastMember.
All you need to know to start using it is pretty much shown in the first 2 code examples.
You are creating a Rube Goldberg device there. You should just have all your data objects classes implement a single interface, then you can work on that. Much simpler and less error prone than fiddling with reflection.
The very fact that a lot of objects have common properties but don't share the same ancestry, on in the very least a common interface, shows that something is wrong with your design. Do rethink it.
Multiple ways to accomplish this, simplest probably is to create Interface and declare common methods there, have your object implement it, then change "getName" method take interface object
private string getName(IMyInterface anyObjWithName)
{
return anyObjWithName.name;
}
The correct way to do this is with an interface, if you own the types that you're working with
public interface IEntity
{
int ID { get; set; }
string Name { get; set; }
}
public class TypeOne : IEntity
{
public int ID { get; set; }
public string Name { get; set }
public string BespokePropertyOne { get; set;}
}
public class TypeTwo : IEntity
{
public int ID { get; set; }
public string Name { get; set; }
public float BespokePropertyTwo { get; set; }
}
static void Main(string[] args)
{
List<IEntity> entities = new List<IEntity>();
entities.Add(new TypeOne() { ID = 1, Name = "Bob", BespokePropertyOne = "blablabla" });
entities.Add(new TypeTwo() { ID = 2, Name = "Alice", BespokePropertyTwo = 5.4f });
foreach (IEntity entity in entities)
{
Console.WriteLine("ID: {0} Name: {1}", entity.ID, entity.Name);
}
}
This answer was written before the edit to the question stating that interfaces weren't possible in this case. Perhaps it can help someone else reading this question.
Interface:
interface Iname
{
string Name { get; set; }
}
Use interface:
class A : Iname
{
public string Name { get; set; }
}
class B : Iname
{
public string Name { get; set; }
}
The method:
string GetName(Iname o)
{
return o.Name;
}
Use:
A a = new A { Name = "First" };
B b = new B { Name = "Last" };
Text = GetName(a) + " " + GetName(b);

How to define type of a property at runtime in .NET?

In Winform application I have a class with 2 properties and I want the user to be able to choose the type of those properties.
This is what I made so far:
Class with the properties:
static public class DataGridColumnData
{
public static object SearchColumn { get; set; }
public static object ResultColumn { get; set; }
}
And the user can choose the type of the properties using a Combobox with DropDownList Style which has values like
System.String
System.Double
System.Int32
System.Boolean
System.DateTime
Is there a way to make those properties to be types the ones that user chooses?
You can make your class generic:
static public class DataGridColumnData<T>
{
public static T SearchColumn { get; set; }
public static T ResultColumn { get; set; }
}
Then, in your code, you can create a class of the desired type:
object myDataGridColumnData;
if (userSelection == "String") {
myDataGridColumnData = new DataGridColumnData<string>();
} else if (userSelection == "Double") {
myDataGridColumnData = new DataGridColumnData<double>();
} ...
Note that, technically, DataGridColumnData<string> is a completely different type than DataGridColumnData<int>, so object is the only common supertype. Thus, to be able to access the values of myDataGridColumnData in code, you might need to use a dynamic variable or (prefered) use some common interface or base class that returns the values typed as objects.
There are ways to make the properties strongly typed in runtime using generics, but I am not sure how useful it is. Here is a solution either way:
Create an interface that is not strongly typed to facilitate interaction with the object:
public interface IDataGridColumnData
{
object SearchColumnAsObject { get; set; }
object ResultColumnAsObject { get; set; }
}
Create generic class that allows for the creation of strongly typed versions at runtime (and in code as well, of course), and that implements the interface:
public class DataGridColumnData<TSearch, TResult> : IDataGridColumnData
{
public TSearch SearchColumn { get; set; }
public static TResult ResultColumn { get; set; }
public object SearchColumnAsObject
{
get { return SearchColumn; }
set { SearchColumn = (TSearch)value; }
}
public object ResultColumnAsObject
{
get { return ResultColumn; }
set { ResultColumn = (TResult)value; }
}
}
Create a factory method that will manufacture strongly typed versions of the class, returning it as the object-typed interface:
private static IDataGridColumnData GetDataGridColumnData(
Type searchType, Type resultType)
{
var typedColumnDataType = typeof(DataGridColumnData<,>)
.MakeGenericType(new[] { searchType, resultType });
return (IDataGridColumnData)Activator.CreateInstance(typedColumnDataType);
}
...and put it to use:
IDataGridColumnData instance = GetDataGridColumnData(
Type.GetType("System.Int32"),
Type.GetType("System.String"));
// use the properties
instance.SearchColumnAsObject = 42; // works well
instance.SearchColumnAsObject = "42"; // throws exception
No, ther is not. A class is statically compiled. No wy to change the property for a static class at runtime.
You can create a subclass nd override it, via bytecode emission, though.
You can use the is keyword
if (x.SearchColumn is Double)
{
}
See also MSDN: Is (C# Reference)

Generic Object Creation Always Returning Nulls

EDIT I updated my question for completeness.
I have incoming REST calls from an iPHone client. It is meant to consume type-specific objects
in response to generic requests. For example:
http://localhost:81/dashboard/group/id/0
returns data from the Regions type
http://localhost:81/dashboard/group/id/1
returns data from the Customers type
http://localhost:81/dashboard/group/id/2
returns data from the Users type
and so on.
The WCF Dashboard.svc service exposes a base method GetGroupById
which I use to determine and return the type-specific response:
public class Dashboard : GroupBase, Contracts.IDashboardService
{
private string name = String.Empty;
public Dashboard() : base()
{
if (!ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated)
throw new WebException("Unauthorized: Class: Dashboard, Method: Dashboard()",
System.Net.HttpStatusCode.Forbidden);
name = ServiceSecurityContext.Current.PrimaryIdentity.Name;
}
public override System.IO.Stream GetGroupById(string id)
{
return base.GetGroupById(id);
}
}
Now, inside my abstract base class the GetGroupById has a switch/case statement that populates
and returns unique data transfer objects based on the corresponding groupid parameter:
public abstract class GroupBase
{
protected GroupBase () { }
public virtual Stream GetGroupById(string id)
{
// I have tried assigning response to null or, in this case,
// assigning it to a random service object. I have also tried
// IObjectFactory response; The last fails at compile-time and
// the other two always produce null
IObjectFactory response =
ObjectFactory<IObjectFactory, UserService>.Create();
var groupId = System.Convert.ToInt32(id);
var serializer = new JavaScriptSerializer();
byte[] bytes = null;
var message = String.Empty;
try
{
switch (groupId)
{
case 0: // regions
response = ObjectFactory<IObjectFactory, RegionService>.Create();
break;
case 1: // customers
response = ObjectFactory<IObjectFactory, CustomerService>.Create();
break;
case 2: // users
response = ObjectFactory<IObjectFactory, UserService>.Create();
break;
}
}
catch (EngageException oops)
{
message = oops.Message;
}
bytes = Encoding.UTF8.GetBytes(serializer.Serialize(response));
return new MemoryStream(bytes);
}
}
A customer ObjectFactory class is used to create the type-specific object:
public static class ObjectFactory where T : F, new()
{
public static F Create()
{
return new T();
}
}
WHERE I AM HAVING PROBLEMS IS what is going on under the hood of my ObjectFactory. I am always
getting ** null ** back. For example, consider the following REST HTTP GET:
http://localhost:81/dashboard/group/id/2
The above command is asking for a JSON string of all Users in the database. Accordingly, the
UserService class is passed into the ObjectFactory method.
public class UserService : IObjectFactory
{
DomainObjectsDto IObjectFactory.Children
{
get
{
return new Contracts.DomainObjectsDto(UserRepository
.GetAllUsers().Select
(p => new Contracts.DomainObjectDto
{
Title = GroupTypes.Customer.ToString(),
Id = p.CustomerId.ToString(),
Type = p.GetType().ToString()
}));
}
}
string IObjectFactory.Method
{
get;
set;
}
string IObjectFactory.Status
{
get;
set;
}
etc...
And, the readonly Get property gets data from the UserRepository, populates the Data Transfer Object
(illustrated below)
[DataContract]
public class DomainObjectDto
{
[DataMember]
public string Title { get; set; }
[DataMember]
public string Id { get; set; }
[DataMember]
public string Type { get; set; }
}
[CollectionDataContract]
public class DomainObjectsDto : List<DomainObjectDto>
{
public DomainObjectsDto() { }
public DomainObjectsDto(IEnumerable<DomainObjectDto> source) : base(source) { }
}
And should return the serialized JSON string of User data to the client. But, my generic type T in my object factory class is always null:
public static F Create()
{
return new T(); // <-- always null!
}
Any ideas??
Hard to tell without seeing the invocation of your factory in context, but my gut feel is that groupId is not in the switch range and thus you are getting the null you defaulted it to. I would add a default case and throw an out of range exception and see if that's your problem.
It's a good idea to add default cases to your switch statements, like:
default:
throw new Exception( "groupId " + groupId + " not found" );
Change the line IObjectFactory response = null; to remove the default, i.e. IObjectFactory response;. Now the compiler will tell you if there is a branch that doesn't assign it (of course, it can't tell you if you assign to null somehow). Note also that there are at least 2 ways of getting null from a new (etc), but these are edge cases - I doubt they are contributing (mentioned for completeness only).

Categories