Accessing the Properties of a class dynamically - c#-4.0

Hi I have to different classes with Same properties and I want to access the peoperties of my classes Dynamically.
public Class1
{
public const prop1="Some";
}
public Class2
{
public const prop1="Some";
}
And in my code I am getting my class name like this
string classname="Session["myclass"].ToString();";//Say I have Class1 now.
And I want to get the prop1 value .
Something like
string mypropvalue=classname+".prop1";//my expected result is Some
///
Type typ=Type.GetType(classname);
Please help me in getting this

Reflection
var nameOfProperty = "prop1";
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
for static:
var nameOfProperty = "prop1";
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static);
var value = propertyInfo.GetValue(myObject, null);
Class reference from string
EDIT (I made example):
class Program
{
static void Main(string[] args)
{
var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList();
Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString());
//This works too: Type ty = Type.GetType("ConsoleApplication4.Foo");
var prop1
= ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public);
Console.WriteLine(prop1.GetValue(ty.Name, null));
Console.ReadLine();
}
}
public static class Foo
{
private static string a = "hello world";
public static string Temp
{
get
{
return a;
}
}
}
Msdn

you can use following function to get a property value fron an object dynamically:
just pass object to scan & property name
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}

Related

without resolveStrategy=DELEGATE_FIRST properties end up as binding variables

I'm trying to write java beans that can be loaded from a Groovy config file. The config format expects properties in closures and if I don't call c.setResolveStrategy(Closure.DELEGATE_FIRST) then all properties set inside the closures end up as binding variables. My program outputs:
In closure
confpojo.myTestProp: null
binding.myTestProp: true
confpojo.app.myOther.myTestSubProp: null
binding.myTestSubProp: true
In this answer https://stackoverflow.com/a/10761284/447503 they don't change the default resolveStrategy and it seems to work. What's the difference? configaaa.groovy:
app {
println 'In closure'
myTestProp = true
myOther {
myTestSubProp = true
}
}
_
public abstract class AaaTestGroovyConfig extends Script {
public static class App {
public void myOther(final Closure c) {
c.setDelegate(myOther);
// c.setResolveStrategy(Closure.DELEGATE_FIRST);
c.call();
}
private Boolean myTestProp;
private final Other myOther = new Other();
public Boolean getMyTestProp() {
return myTestProp;
}
public void setMyTestProp(final Boolean active) {
this.myTestProp = active;
}
}
public void app(final Closure c) {
c.setDelegate(app);
// c.setResolveStrategy(Closure.DELEGATE_FIRST);
c.call();
}
private App app = new App();
public static void main(final String[] args) throws Exception {
final CompilerConfiguration cc = new CompilerConfiguration();
cc.setScriptBaseClass(AaaTestGroovyConfig.class.getName());
// final ClassLoader cl = AaaTestGroovyConfig.class.getClassLoader();
final Binding binding = new Binding();
final GroovyShell shell = new GroovyShell(binding, cc);
final Script script = shell.parse(new File("configaaa.groovy"));
final AaaTestGroovyConfig confpojo = (AaaTestGroovyConfig) script;
// ((DelegatingScript) script).setDelegate(confpojo);
script.run();
System.out.println("confpojo.myTestProp: " + confpojo.app.myTestProp);
printBindingVar(binding, "myTestProp");
System.out
.println("confpojo.app.myOther.myTestSubProp: " + confpojo.app.myOther.myTestSubProp);
printBindingVar(binding, "myTestSubProp");
}
private static void printBindingVar(final Binding binding, final String name) {
System.out
.println(
"binding." + name + ": " + (binding.hasVariable(name)
? binding.getVariable(name)
: ""));
}
public static class Other {
private Boolean myTestSubProp;
public Boolean getMyTestSubProp() {
return myTestSubProp;
}
public void setMyTestSubProp(final Boolean myTestSubProp) {
this.myTestSubProp = myTestSubProp;
}
}
public App getApp() {
return app;
}
public void setApp(final App app) {
this.app = app;
}
}
because the default value is OWNER_FIRST
https://docs.groovy-lang.org/latest/html/api/groovy/lang/Closure.html#OWNER_FIRST
and you have 2 levels of closures so - owners are different for them
try something like this and you'll see the difference
app {
println "delegate=$delegate owner=${owner.getClass()}"
myOther {
println "delegate=$delegate owner=${owner.getClass()}"
}
}
PS: let me suggest you to make your code groovier:
//generic config class
class MyConf {
private HashMap objMap
static def build(HashMap<String,Class> classMap, Closure builder){
MyConf cfg = new MyConf()
cfg.objMap = classMap.collectEntries{ k,cl-> [k, cl.newInstance()] }
cfg.objMap.each{ k,obj->
//define method with name `k` and with optional closure parameter
cfg.metaClass[k] = {Closure c=null ->
if(c) {
// call init closure with preset delegate and owner
return c.rehydrate(/*delegate*/ obj, /*owner*/cfg, /*this*/cfg).call()
}
return obj //return object itself if no closure
}
}
cfg.with(builder) // call root builder closure with cfg as a delegate
return cfg
}
}
//bean 1
#groovy.transform.ToString
class A{
int id
String name
}
//bean 2
#groovy.transform.ToString
class B{
int id
String txt
}
//beans init
def cfg = MyConf.build(app:A.class, other:B.class){
app {
id = 123
name = "hello 123"
other {
id = 456
txt = "bye 456"
}
}
}
//get initialized beans
println cfg.app()
println cfg.other()

Object does not match target type with SetValue using Type

I'm trying to dynamically build set objects based on a user input document. For some reason SetValue is throwing Object does not match target type, despite that it does.
Is what im trying to achieve even possible?
private void MapProp(string prop, string invalue)
{
var currType = _userAssembly.GetType(_className);
var property = currType.GetProperty(prop, BindingFlags.Public | BindingFlags.Instance);
var value = Convert.ChangeType(invalue, property.PropertyType);
property.SetValue(styleType, value, null);
}
}
Currently its attempting to map to said object:
public class TestObject: ITestObj
{
public string PropertyA {get;set;}
public string PropertyB {get;set;}
}
Calling Code
MapProp("PropertyA", "testValue");
and the getType classname = .Assembly.TestObject
#user4550364 ,I dont know what does your _user assembly does ,so I am gonna put my sample code ,this might help you to adapt the idea to your code.This is also an example of late binding.
Class file
public class TestObject: ITestObj
{
public string PropertyA {get;set;}
public string PropertyB {get;set;}
void Print(string PropertyA,string PropertyB)
{
//Assuming that interface ITestObj has this method definition and hence implementing here.
}
}
Main code
using System.Reflection;
static void Main(string[] args)
{
Assembly executingassembly = Assembly.GetExecutingAssembly();
Type TestObjecttype = executingassembly.GetType("ur_namespace.TestObject");
object instance = Activator.CreateInstance(TestObjecttype );
string[] parameters = new string[2];
parameters[0] = "PropertyA ";
parameters[1] = "PropertyB ";
//To get properties
PropertyInfo[] properties = TestObjecttype .GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.PropertyType.Name+" "+property.Name);
}
MethodInfo method = customertype.GetMethod("Print");
//Object created ,now invoke using its instance
string printMethodInvoked= (string)method.Invoke(instance, parameters);
Console.WriteLine(printMethodInvoked);
Console.Read();
}
}

Need of New keyword in multilevel inheritance c#

Hello this question is regarding when exactly New keyword i;e Method hiding in base class can be done.
static void Main(string[] args)
{
A a = new A();
a.calculatebnft();
a = new B();
a.calculatebnft();
a = new C();
a.calculatebnft();
a = new Program();
a.calculatebnft();
Console.ReadKey();
}
public new string calculatebnft()
{
string bnft = "";
Console.WriteLine("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
return bnft;
}
}
class A
{
//my code here
public virtual string calculatebnft()
{
string bnft = "";
Console.WriteLine("A");//my code here
return bnft;
}
}
class B : A
{
//my code here
public override string calculatebnft()
{
string bnft = "";
Console.WriteLine("B");//my code here
return bnft;
}
}
class C : B
{
public new string calculatebnft()
{
string bnft = "";
Console.WriteLine("C");
return bnft;
}
}
When above program is executed output is
A
B
B
B
in this case New Keyword in class C not hiding method in class B? what is the reason behind it.
Sorry am new to .Net and if my question is too basic

How to get values of passed in object using C#

I have a following code
public void ShowForm(String EName, String phoneNumber, String dnis, String mode, String callid)
{
objCallParams.EventName = EName;
objCallParams.ANI = phoneNumber;
objCallParams.DNIS = dnis;
objCallParams.Mode = mode;
objCallParams.CallId = callid;
UIThreadContext.Post(InComing_Callback, (object)objCallParams);
}
private void InComing_Callback(object objCallParams)
{
/*want to access phone number i.e.objCallParams.ANI*/
}
How do I access phoneNumber in InComing_Callback(object objCallParams) method?
If you know the type of the object you can use casting
private void InComing_Callback(object objCallParams)
{
// If you know that objCallParams will always be of the type FormParameters:
var params = (FormParameters)objCallParams;
// if you are not so sure about that
var notSoSureParams = objCallParams as FormParameters;
if (notSoSureParams != null)
{
}
}

create sort on list for web API controller

I am writing my first web API controller so I am a bit of a noob in this area. I am trying to retrieve a list of data through a static class called CustomerDataSource:
public static class CustomerDataSource
{
public static List<Customer> customerData
{
get
{
Customer customer1 = new Customer() { name = "Bert", address = "London" };
Customer customer2 = new Customer() { name = "Jon", address = "New York" };
List<Customer> listCustomers = new List<Customer>();
listCustomers.Add(customer1);
listCustomers.Add(customer2);
return listCustomers;
}
}
}
public class Customer
{
public string name { get; set; }
public string address { get; set; }
}
I am a bit stuck with my ApiController because I am trying to sort the list either on 'name' or 'address' but using a string called 'field' does not compile. What would be a good implementation for a WebAPI controller GETmethod which provides for sorting on one of the Customer properties ?
public class ValuesController : ApiController
{
// GET api/values
public List<Customer> Get(string field)
{
var list = CustomerDataSource.customerData.OrderBy(field);
}
}
Create an extension method like below, then you can use it anywhere within the same namespace in your project.
public static class extensionmethods
{
public static IQueryable<T> OrderByPropertyName<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var rs = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(rs);
}
}
Then you can use it like:
public List<Customer> Get(string PropertyName)
{
var list = CustomerDataSource.customerData.AsQueryable().OrderByPropertyName("PropertyName",true).ToList();
}
Note:
Because the extension method uses IQueryable and returns IQuerybale, so you need to convert your List to IQueryable. Also you can order the list by ascending and descending order, just pass the boolean type value to the second parameter. The default is ascending.
You need to use a lambda expression.
if (field == "name")
var list = CustomerDataSource.customerData.OrderBy(d => d.name);
else if (field == "address")
var list = CustomerDataSource.customerData.OrderBy(d => d.address);

Resources