|
Hi
I am trying to modify class instance members using reflection. I am having problem when trying to add/remove/display elements related to List<int> member.
Following is the code.
[CODE]
class TestClass
{
public int i = 0;
public int IValue
{
get
{
return i;
}
set
{
i = value;
}
}
public List<int> m_intList = new List<int>();
}
class Program
{
static void Main(string[] args)
{
TestClass tcObject = new TestClass();
tcObject.i = 1;
tcObject.m_intList.Add(1);
tcObject.m_intList.Add(2);
{
FieldInfo fieldInfo = tcObject.GetType().
GetField(
"i",
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
fieldInfo.SetValue(tcObject, 2);
System.Console.WriteLine("I value '{0}'", fieldInfo.GetValue(tcObject));
}
{
PropertyInfo propertyInfo = tcObject.GetType().
GetProperty(
"IValue",
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
MethodInfo propertySetMethodInfo =
propertyInfo.GetSetMethod(true);
propertySetMethodInfo.Invoke(tcObject, new Object[] { 3 });
System.Console.WriteLine("Property IValue '{0}'", tcObject.i);
}
{
FieldInfo fieldInfo = tcObject.GetType().
GetField(
"m_intList",
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
foreach (int intItem in tcObject.m_intList)
{
System.Console.WriteLine("List Item value '{0}'", intItem);
}
}
}
}
</string></int></int></int> [/CODE]
Thanks
Chandra
modified on Thursday, October 16, 2008 1:56 AM
|
|
|
|
|
At compile time I do not know whether the type is List<int> or List<string>. At runtime I should interpret it from the fieldInfo.FieldType.
|
|
|
|
|
I even tried the following code
MethodInfo addMethodInfo = fieldInfo.FieldType.GetMethod("Add");
object[] intValue = { 5 };
addMethodInfo.Invoke(tcObject, new Object[] { 5 });
But the above code gives me error "Unhandled Exception: System.Reflection.TargetException: Object does not match target type." when executing the "invoke"
|
|
|
|
|
chandrap wrote: I am trying to modify class instance members using reflection.
Why?
led mike
|
|
|
|
|
Its a requirement in my application. Given an instance of class and values for the members, we should be able to update the members with the corresponding values.
|
|
|
|
|
chandrap wrote: Given an instance of class and values for the members, we should be able to update the members with the corresponding values.
Where in there is the requirement to use Reflection?
led mike
|
|
|
|
|
Hello everyone, thanks for your help. I was able to find the solution for my requirement. Following is the code
class ListElement
{
public ListElement()
{
m_element = 0;
}
public ListElement(int element)
{
m_element = 1;
}
public int m_element;
}
class TestClass
{
public int i = 0;
public int IValue
{
get
{
return i;
}
set
{
i = value;
}
}
public List<int> m_intList = new List<int>();
public List<listelement> m_lstElement = new List<listelement>();
}
class Program
{
static void Main(string[] args)
{
TestClass tcObject = new TestClass();
tcObject.i = 1;
tcObject.m_intList.Add(1);
tcObject.m_intList.Add(2);
tcObject.m_lstElement.Add(new ListElement(1));
{
FieldInfo fieldInfo = tcObject.GetType().
GetField(
"i",
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
fieldInfo.SetValue(tcObject, 2);
System.Console.WriteLine("I value '{0}'", fieldInfo.GetValue(tcObject));
}
{
PropertyInfo propertyInfo = tcObject.GetType().
GetProperty(
"IValue",
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
MethodInfo propertySetMethodInfo =
propertyInfo.GetSetMethod(true);
propertySetMethodInfo.Invoke(tcObject, new Object[] { 3 });
System.Console.WriteLine("Property IValue '{0}'", tcObject.i);
}
{
FieldInfo fieldInfo = tcObject.GetType().
GetField(
"m_intList",
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
MemberInfo[] listMemberInfoArray = tcObject.GetType().GetMember("m_intList");
MemberInfo listMemberInfo = listMemberInfoArray[0];
MethodInfo addMethodInfo = fieldInfo.FieldType.GetMethod("Add");
object[] elementValue = { 5 };
addMethodInfo.Invoke(fieldInfo.GetValue(tcObject), elementValue);
foreach(int currElement in tcObject.m_intList)
{
System.Console.WriteLine("INt List element {0}", currElement);
}
Console.WriteLine();
}
{
FieldInfo fieldInfo = tcObject.GetType().
GetField(
"m_lstElement",
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
MethodInfo addMethodInfo = fieldInfo.FieldType.GetMethod("Add");
Object listElementObject = Activator.CreateInstance(fieldInfo.
FieldType.
GetGenericArguments()[0]);
FieldInfo listElementFieldInfo = listElementObject.GetType().
GetField(
"m_element",
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public);
listElementFieldInfo.SetValue(listElementObject, 2);
object[] elementValue = { listElementObject };
addMethodInfo.Invoke(fieldInfo.GetValue(tcObject), elementValue);
foreach (ListElement currListElement in tcObject.m_lstElement)
{
System.Console.WriteLine("List Item value '{0}'", currListElement.m_element);
}
}
}
}
</listelement></listelement></int></int>
|
|
|
|
|
Hello,
This might be an easy question! But I was wondering if there is any library in .net for simulation?
If I want to simulate a Network of a few computer nodes in C#, what is the best way?
Thanks a lot for your help.
|
|
|
|
|
Sareh khanoom wrote: But I was wondering if there is any library in .net for simulation
Nope. This would have to be provided by you or some other third party library.
Sareh khanoom wrote: If I want to simulate a Network of a few computer nodes in C#, what is the best way?
That's determined by your simulation requirements. You'll have to limit this by asking yourself "What aspects of a network are am I going to simulate and for what purpose?"
|
|
|
|
|
I have a database which has a unique primary key defined key on two columns, in the example below the columns are type and data.
type | value | data | 9 | 0 | 'ABC' | 9 | 0 | 'ABC ' |
When I read in a datatable and then set the PrimaryKey collection with the designated columns I get an exception saying that 'These columns don't currently have unique values'.
So, to me it appears that ADO is ignoring the spaces with respect to determining uniqueness (although the whitespace appears in the rows collection).
I started looking into the DataTable and DataColumn object to see if there was anything that jumped out, but nothing so far.
Can anyone confirm this behavior and/or offer any assistance?
Thanks!
|
|
|
|
|
calhuskerfan wrote: I have a database
calhuskerfan wrote: So, to me it appears that ADO is
ADO is NOT a database. If you are setting up the keys and constraints in the database it is the database product that will contain your answer not ADO.
led mike
|
|
|
|
|
The constraints in the database are fine. They allow the described scenario where 'ABC' and 'ABC ' are considered unique.
When I read, with ADO, from the database into a datatable object ADO does not bring along the primary key identified in the database. So it allows at this point the two above rows to exist.
When I set the PrimaryKey property on the DataTable object (after the rows have been read) to include the column containing the above data I get the constraint exception.
Edit - The exception is actually an ArgumentException stating that the values are not unique.
|
|
|
|
|
calhuskerfan wrote: The constraints in the database are fine. They allow the described scenario where 'ABC' and 'ABC ' are considered unique.
What database are you using? I cannot reproduce that behavior using SQL Express 2005.
led mike
|
|
|
|
|
Sybase SQL Anywhere 10.
Thanks.
|
|
|
|
|
Here is a very quick (and sloppy) example that reproduces the behavior.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Test1();
}
public static void Test1()
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("col0");
dt1.Columns.Add("col1");
dt1.Columns.Add("col2");
dt1.Columns[0].DataType = typeof(Int32);
dt1.Columns[1].DataType = typeof(String);
dt1.Columns[2].DataType = typeof(String);
DataRow dr = dt1.NewRow();
dr["col0"] = 1;
dr["col1"] = "Column 2";
dr["col2"] = "Column 3";
dt1.Rows.Add(dr);
dr = dt1.NewRow();
dr["col0"] = 1;
dr["col1"] = "Column 2";
dr["col2"] = "Column 3 ";
dt1.Rows.Add(dr);
try
{
dt1.PrimaryKey = new DataColumn[] { dt1.Columns[0], dt1.Columns[2] };
}
catch (ArgumentException ae)
{
MessageBox.Show(ae.Message);
}
}
}
}
|
|
|
|
|
calhuskerfan wrote: Here is a very quick (and sloppy) example that reproduces the behavior.
You didn't understand my post. Using SQL Express 2005 with a Table1 designed as your example with the two column primary key constraint.
One row in the table as follows:
Type Value Data
------ ------ --------------------------------------------------
1 2 ABC
Executing the following SQL
insert into Table1 (Type, Value, Data) VALUES(1, 3, 'ABC ')
Produces this error:
Cannot insert duplicate key row in object 'dbo.Table1' with unique index 'IX_Table1'.
led mike
|
|
|
|
|
I tried your test case and ran into the same problem. Seems that when the values are compared, the trailing spaces are removed (or added until the length is the same).
Actually the same effect can happen in SQL Server when varchar data type is used so this may be by design.
Quickly cannot think anything else than replacing trailing spaces with a special character that can be later removed (like ascii 255).
The need to optimize rises from a bad design.
My articles[ ^]
|
|
|
|
|
My application working fine in the dev environment.But in the testing /production environment
it is not working because that environment has only
windows server 2003
IIS
.net2.0 framework
In my application I have Used some microsoft VC++ dll's also along with .net dll's.
Now Iam getting "RUNTime Error" pop-up screen message as below
" The Application has been terminated in an Unusual Way"
On googling i came to know that some dll's like msvcrt.dll of windows server 2003 has to be changed...But Iam not pretty sure about it..
In Production/test environment there is only framework installed ,but there is no visual studio installed on it.may be due that this error may occur...
So kindly post your suggestions and views to help me
I tried the following as suggested by you:
1. I have installled the redistributable package suggested by you.
after installing i restarted the PC even now also I got the same runtime pop-up error.
2. Then I checked even with the dependency walker for the dll.
I found that there is no miising dll.
3. Then I tried by installing Visual C++ express edition..even then also i got the same pop-up error.
Kindly help me.....
|
|
|
|
|
Please don't cross post, it's considered rude and isn't going to help you get an answer any faster. The original post is here[^].
Scott Dorman Microsoft® MVP - Visual C# | MCPD
President - Tampa Bay IASA
[ Blog][ Articles][ Forum Guidelines] Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai
modified on Tuesday, October 14, 2008 2:38 PM
|
|
|
|
|
Scott Dorman wrote: The original post is here[^].
From my point of view, it's here[^].
Mark Salsbery
Microsoft MVP - Visual C++
|
|
|
|
|
Yep, you're right. I didn't see that one.
Scott Dorman Microsoft® MVP - Visual C# | MCPD
President - Tampa Bay IASA
[ Blog][ Articles][ Forum Guidelines] Hey, hey, hey. Don't be mean. We don't have to be mean because, remember, no matter where you go, there you are. - Buckaroo Banzai
|
|
|
|
|
Hi all!
My application is having a strange behavior and I can't find how to solve it.
I have a thread that executes an application using AppDomain.CurrentDomain.ExecuteAssembly(app);. I have a try/catch block surrounding this statement and catch for any Exceptions (assuming this are Unhandled exceptions from the application I'm executing.
Here is the code:
try
{
AppDomain.CurrentDomain.ExecuteAssembly(AUT.File);
}
catch (Exception excp)
{
logger.Warn("an exception was unhandled: " + excp.ToString());
}
The thing is that when I'm executing this code with debugger (in Visual Studio) the behavior is as I expected, i.e, the try/catch block catches unhandled exceptions inside the assembly I'm executing. But If I run it without a debugger the try/catch block doesn't catches unhandled exceptions. But a message box is shown informing of the thrown exception.
Why this behavior? How can make it have always the same behavior?
Thanks
José Tavares
|
|
|
|
|
Well the reason this happens is because all Windows Forms applications handle all unhandled exceptions by default in the Application.Run loop. If I add
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
all unhandled exceptions that occur in this application are re-thrown and my application code catches the exceptions.
The problem is that I want to use my application to test 3rd party apps sometimes don't having the code. Is there any other way to reproduce this behavior from outside the application or will I have to use Reflection to add that line to every application that I will test?
Thanks
José Tavares
|
|
|
|
|
Hi!
i have to zip a folder, when i use ZipPackage, it creates a [Content_Types].xml in the created zip file. I don't want it and can not find a way to omit it.
Help me pleaaaase
|
|
|
|
|
I am also getting same problem..if you find any solution please let me know..
thak's In advance.
ramanakant.
|
|
|
|