473,722 Members | 2,244 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with creating classes as runtime - PLEASE HELP

Hi

I need to create the following class at runtime:

public class MyCollection : CollectionBase
{
public void Add(MyItem item)
{
List.Add(item);
}
public MyItem this[int index]
{
get
{
return (MyItem)List[index];
}
}
}

(the type MyType will also be of a type created at runtime with the
TypeBuilder)

I thought a good plan would be to create such a class and use the
ILDASM.exe tool on it to look at the IL generated. I got this (for
the Add method):

.method public hidebysig instance void
Add(string item) cil managed
{
// Code size 15 (0xf)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call instance class
[mscorlib]System.Collecti ons.IList [mscorlib]
System.Collecti ons.CollectionB ase::get_List()
IL_0007: ldarg.1
IL_0008: callvirt instance int32
[mscorlib]System.Collecti ons.IList::Add( object)
IL_000d: pop
IL_000e: ret
} // end of method Class1::Add

and the code i've tried to write looks a little something like this:

methodBuilder = typeBuilder.Def ineMethod("Add" ,
MethodAttribute s.Public, null, new Type[] { collectionType } );
ILout = methodBuilder.G etILGenerator() ;
ILout.Emit(OpCo des.Nop);
ILout.Emit(OpCo des.Ldarg, 0);
ILout.Emit(OpCo des.Call, ????????);
ILout.Emit(OpCo des.Ldarg, 1);
ILout.Emit(OpCo des.Callvirt,
typeof(System.C ollections.ILis t).GetMethod("A dd", new Type[]
{typeof(Object) }));
ILout.Emit(OpCo des.Pop);
ILout.Emit(OpCo des.Ret);

You can see I've had a few problems with the OpCodes.Call - can anyone
help me please fill in the gaps?

Also, how do you interpret the following (IL_0013: br.s
IL_0015) to code, in this example:

.method public hidebysig specialname instance string
get_Item(int32 index) cil managed
{
// Code size 23 (0x17)
.maxstack 2
.locals init ([0] string CS$1$0000)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call instance class
[mscorlib]System.Collecti ons.IList
[mscorlib]System.Collecti ons.CollectionB ase::get_List()
IL_0007: ldarg.1
IL_0008: callvirt instance object
[mscorlib]System.Collecti ons.IList::get_ Item(int32)
IL_000d: castclass [mscorlib]System.String
IL_0012: stloc.0
IL_0013: br.s IL_0015

IL_0015: ldloc.0
IL_0016: ret
} // end of method Class1::get_Ite m

If anyone can help me i'd be very grateful.

Many thanks

Julia.

May 10 '07 #1
8 2215
Can I ask... why?

In 2.0 generics would be the answer; I assume this is 1.1?

You won't be able to write code against a runtime-only class, so a lot
of the type-safety goes out of the window anyway unless you are using
a ton of interfaces. The only useful property, then, is the typed
indexer (which can be used to infer metadata for lists) - but in this
case, and with 1.1, the ITypedList interface might be a better
option...

So what is this class required *for*? As this might change how best to
do it...

Marc

May 10 '07 #2
Another note; I find Lutz Roeder's .NET Reflector much easier to use
for reading IL; give it a whirl (it is free).

For the "call" methods, you need the MethodInfo object that you want
to invoke; some examples here (unlreated subject, and .Net 2.0 based,
but the Emit section should be similar):
http://www.codeproject.com/csharp/Hy...Descriptor.asp

Finally - are you compiling in debug mode? For reverse engineering IL,
I strongly suggest using release mode... those nops are looking mighty
suspicious ;-)

Marc

May 10 '07 #3
br.s is "branch, short form" - but it seems to transfer to the next
instruction anyway... perhaps see if it disappears in release mode...
I might try leaving it out... see what happens ;-p The runtime is very
good at spotting major goofs (stack abuse etc) - and minor gotchas
should show through testing.

And another thing : are you always handling classes? If you also deal
in structs then the IL changes to accomodate boxing and unboxing; see
that previous reference for an illustration.

Marc

May 10 '07 #4
Ok...

Thanks for your reply and all the info, Generics looks interesting,
i'll look into that. Also i'll look into IL generated in release mode
- just for my own better understanding if nothing else!!! Hopefully
something you've suggested will allow me to move forward.

Just for your information the reason I want to do this is as
follows...

I want to parse an XMLSchema object, create runtime classes to
represent the data and set a propertyGrid control's SelectedObject to
an instance of the class. The user can then populate the propertyGrid
with data. Then I can serialize the runtime class to create my XML
file that conforms to the schema I was originally given.

The reason for the Collection class is for nested elements in the XML
schema. I've had some success, but please, if you think this is just
crazy, or if you can suggest a better way to do this, please say. I'm
always ready to listen to better ways of doing stuff!

Many thanks

Julia

May 11 '07 #5
Well, it *really* depends on your runtime. If you are 2.0 (or above),
then *absolutely* generics will simplify most of the collection side
of things; heck, List<Tdoes everything there and more; all you'd
need to do is use reflection to define T for an unknown (at
compile-time), which is easy enough.

However, I wonder if you are doing things the damned hard way...
creating a type is not the only way to define "properties " (quoted, as
I don't necessarily mean *class* properties); the
System.Componen tModel (used by all well-behaved binding controls)
allows you to declare virtual properties at runtime.

A little while ago (2nd May, "How to emulate missing property in
object", with a "Long post warning!") I posted a complete example of
this - a property-bag implementation that allowed you *at runtime* to
declare virtual properties against a type, using a bag to hold the
values. They don't appear in intellisense (because this is the model),
but they appear the view. Honest ;-p I have a more complete
implementation of this that supports multiple classes (and a likewise
list), but it is quite lengthy. But it perhaps easier to follow than
Reflection.Emit .

Of course, a third alternative is to build a DataSet that represents
the data; I'm not much of a DataSet fan myself, but for this type of
scenario it may be very useful - same concept: add properties at
runtime (but to an Instance (DataTable), not a Type as in my example).

Marc
May 11 '07 #6
One other off-the-wall thought... perhaps another pragmatic approach
here is to use "xsd.exe" to parse the schema, and then use "csc.exe"
to compile the resultant class/dataset to a temp assembly... load it
and then treat as before. I will use Reflection.Emit when pushed, but
I try to look at simpler solutions first, because my debugging time is
valuable to me, and I know my limitations; I'm an IL dabbler - not an
expect.

csc is part of the runtime, but unfortunately xsd is part of Visual
Studio and isn't listed in redist.txt, so not sure how you'd stand re
using it off your dev box...
<ju************ *@hotmail.comwr ote in message
news:11******** *************@l 77g2000hsb.goog legroups.com...
Ok...

Thanks for your reply and all the info, Generics looks interesting,
i'll look into that. Also i'll look into IL generated in release
mode
- just for my own better understanding if nothing else!!! Hopefully
something you've suggested will allow me to move forward.

Just for your information the reason I want to do this is as
follows...

I want to parse an XMLSchema object, create runtime classes to
represent the data and set a propertyGrid control's SelectedObject
to
an instance of the class. The user can then populate the
propertyGrid
with data. Then I can serialize the runtime class to create my XML
file that conforms to the schema I was originally given.

The reason for the Collection class is for nested elements in the
XML
schema. I've had some success, but please, if you think this is
just
crazy, or if you can suggest a better way to do this, please say.
I'm
always ready to listen to better ways of doing stuff!

Many thanks

Julia

May 11 '07 #7
I'm having a lot of success with the Generics approach, so thank you
for pointing me in that direction. It's new in version 2.0 and i
didn't even know it existed, it's very interesting.

The xsd.exe tool is a good idea but i have had problems in the past
where the classes generated are not 100% correct - although this was
on a very lengthy complicated schema. I'm going to run some tests on
my example schemas because I like the idea of having a backup plan
should i run into more issues with the Emit stuff.

And yes, i too avoid using DataSets, and i'm not even sure why. I
must have had a bad experience with one once :-s

Thank you again for your help and suggestions.

Julia.

May 11 '07 #8
I independently thought of Marc's suggestion of using XSD /c to
generate a class file before reading down to his comments and I agree
with him. If your schemas are somewhat stable (say on a daily basis
at least) then it's trivial to create classes using xsd /c. In
VS2003, it created some cluttered source code but in VS2005, it's very
clean and easy to incorporate into other projects. I would suck in
the generated code and perhaps even pipe the output of shell executing
xsd /c into either a stream or a directory that has a File System
Watcher http://msdn2.microsoft.com/en-us/lib...emwatcher.aspx
attached so that it automatically reads the generated source and makes
the class available in your source code. The watcher is also pretty
simple to integrate into your app.

I was also thinking that this is something that would be cool for the
Jasper team to take up in addition to dynamically creating entity
classes out of Sql Databases. Another neat idea would be to push the
XML schema into Sql Server automatically using the
SQLXMLBULKLOADL ib.SQLXMLBulkLo ad4Class. That way, you could expose
your C# class as a web service [WebMethod] and use the generated
schema (a la hibernate) as your repository for the incoming data or
the outgoing response data.

Jun 5 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3592
by: Tom Williams | last post by:
I'm posting this to the newsgroup for archival purposes. :) In this thread: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=jibqb.308193%24pl3.47126%40pd7tw3no&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3Djibqb.308193%2524pl3.47126%2540pd7tw3no I had problems getting DB2 UDB 8.1 installed on my HP-UX 11i system. I was able to get through the installation mostly, but it hung while creating the instance. ...
13
4228
by: Lee | last post by:
Hello All, First of all I would like to say thank you for all of the help I have received here. I have been teaching myself Access for about 4 years now and I've always been able to find a solution here - until now. This one is driving me crazy. I am making my first attempt at creating a runtime application. I am using Access 2003 Developer Extensions. Initially I developed the database without planning on creating a runtime app...
28
5219
by: Jon Davis | last post by:
If I have a class with a virtual method, and a child class that overrides the virtual method, and then I create an instance of the child class AS A base class... BaseClass bc = new ChildClass(); .... and then call the virtual method, why is it that the base class's method is called instead of the overridden method? How do I fix this if I don't know at runtime what the child class is? I'm using Activator.CreateInstance() to load the...
8
5966
by: Nanda | last post by:
hi, I am trying to generate parameters for the updatecommand at runtime. this.oleDbDeleteCommand1.CommandText=cmdtext; this.oleDbDeleteCommand1.Connection =this.oleDbConnection1; this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ApplicantName", dataset.Tables.Columns.DataType, 50,
6
1796
by: Tony Maresca | last post by:
Given: public class MyClass { private MyClass() {} static MyClass() { //.. }
3
3351
by: Dan | last post by:
Hi, I have a problem using an aspx page with a Control on it. I get the following error message Compiler Error Message: CS1595: 'Test.Class2' is defined in multiple places; using definition from 'c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files\root\1f575646\ad3a161b\assembly\dl2\57ca505e\044565c0_f84fc401\Test1.DLL' The problem is that the control is defined in two different assemblies
5
4088
by: Segfahlt | last post by:
I need a little help here please. I have 2 win forms user controls in 2 different projects that I'm hosting in 2 different virtual directories. The controls have been test and operate okay in both projects. Both controls(dlls) have been signed using SN.exe and I've set up the appropriate .Net assembly permissions using those Strong Names The DLL's have been copied to the /bin directory in both web virtual directories.
6
2345
by: TPJ | last post by:
Help me please, because I really don't get it. I think it's some stupid mistake I make, but I just can't find it. I have been thinking about it for three days so far and I still haven't found any solution. My code can be downloaded from here: http://www.tprimke.net/konto/PyObject-problem.tar.bz2. There are some scripts for GNU/Linux system (bash to be precise). All you need to know is that there are four classes. (Of course, you may...
31
3192
by: JoeC | last post by:
I have read books and have ideas on how to create objects. I often create my own projects and programs. They end up getting pretty complex and long. I often use objects in my programs they are some of the most powerful programming tools I have found. Often times as my program grows so do my objects. Often times I look back and see that my objects could be broken down int several smaller more re-usable module pieces of code. Is it a...
0
8860
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8738
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9381
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9234
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9151
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6680
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5994
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4501
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4762
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.