473,598 Members | 3,344 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Reflection--anybody use it lately?

What good is C# Reflection, other than to find out what types are in
an assembly? And to dynamically invoke methods in an assembly (.dll
or .exe)?

Also, bonus question, can you use Reflection to build a compiler? One
that will construct a user defined class "on the fly" (literally, the
user defines a class, instantiates it, and runs it from the console
mode, all the while prompted by the program)?

I guess so, but my final question is whether anybody has used
Reflection. Seems that some people use reflection to dynamically
invoke methods in an assembly (.dll or .exe), which might be useful
for using old non-C# unmanaged code.

RL

The Reflection API allows a C# program to inspect and manipulate
itself. It can be used to effectively find all the types in an
assembly and/or dynamically invoke methods in an assembly. It can at
times even be used to emit Intermediate Language code on the fly so
that the generated code can be executed directly.
Jul 16 '08 #1
17 2298
Google for PostSharp, then you will see that reflection isn't all about
creating instances and invoking methods. Additionally I used an object
persistence framework which describes the UML model using .NET attributes
(www.capableobjects.com) so I find reflection very useful there too.

As for creating classes you want to use AssemblyBuilder etc.

Pete

Jul 16 '08 #2
On Jul 16, 1:49 am, "Peter Morris" <mrpmorri...@SP AMgmail.comwrot e:
Google for PostSharp, then you will see that reflection isn't all about
creating instances and invoking methods. Additionally I used an object
persistence framework which describes the UML model using .NET attributes
(www.capableobjects.com) so I find reflection very useful there too.

As for creating classes you want to use AssemblyBuilder etc.

Pete
Thanks "Pete Morris". I checked out the page on AOP in
http://en.wikipedia.org/wiki/Aspect-...ed_programming, and it seems
like gobblygook. A specific example would have helped, but it seems
that the concern is over security. For example, somebody who
maliciously hacks into a system should be stopped from doing other bad
stuff if the programs written therein are written in AOP, which uses
reflection a lot to dynamically examine, akin to packet sniffing, all
translation units, classes, blocks of code etc being run in real
time. The hacker can then be stopped because he might not have the
right permission (i.e., thread permission) to do anything bad after
successfully logging into a network.

In short, much ado about nothing. I'll cross it off my list of things
to study.

RL

Jul 16 '08 #3
On Jul 16, 12:34*pm, raylopez99 <raylope...@yah oo.comwrote:
What good is C# Reflection, other than to find out what types are in
an assembly? *And to dynamically invoke methods in an assembly (.dll
or .exe)?
You don't dynamically invoke methods in an assembly, you dynamically
invoke methods of a class (or, more often, of an object).

And yes, this is useful. A few things in the standard library that use
it are data binding (all of it - WinForms, ASP.NET, WPF) and
serialization (both binary and XML). Third-party inversion of control
containers (such as Unity) also typically use it

On my own side, I once wrote code that displayed a tree of objects
(all of different types) in a TreeView via reflection - it read custom
attributes off properties to figure out which properties were supposed
to be displayed in a tree and how, and which properties could be used
to retrieve visible children of object.
Also, bonus question, can you use Reflection to build a compiler? *One
that will construct a user defined class "on the fly" (literally, the
user defines a class, instantiates it, and runs it from the console
mode, all the while prompted by the program)?
Yes. See System.Reflecti on.Emit.
I guess so, but my final question is whether anybody has used
Reflection. Seems that some people use reflection to dynamically
invoke methods in an assembly (.dll or .exe), which might be useful
for using old non-C# unmanaged code.
You cannot use reflection to invoke "methods" (you mean, functions) in
an unmanaged DLL.
Jul 16 '08 #4
raylopez99 wrote:
What good is C# Reflection, other than to find out what types are in
an assembly? And to dynamically invoke methods in an assembly (.dll
or .exe)?

Also, bonus question, can you use Reflection to build a compiler? One
that will construct a user defined class "on the fly" (literally, the
user defines a class, instantiates it, and runs it from the console
mode, all the while prompted by the program)?

I guess so, but my final question is whether anybody has used
Reflection. Seems that some people use reflection to dynamically
invoke methods in an assembly (.dll or .exe), which might be useful
for using old non-C# unmanaged code.

RL

The Reflection API allows a C# program to inspect and manipulate
itself. It can be used to effectively find all the types in an
assembly and/or dynamically invoke methods in an assembly. It can at
times even be used to emit Intermediate Language code on the fly so
that the generated code can be executed directly.
Hi there, I use Reflection to dynamically add TabPages to a TabControl -
I scan a known directory for Dll's , check whether a class implements a
known Interface, and, if it does, load it using Reflection - very useful
in my book

regards
Jul 16 '08 #5
Eps
I have seen reflection used to good effect in a database access layer
(think nhibernate and you will be close). It was actually used to save
different objects (each representing a table with the properties mapping
to the fields). It was very cool cos it handled saving pretty much any
object without any hassles in one code file.

Its worth saying that if you were to approach the same problem today you
are probably better off using a different approach, LINQ springs to mind.

--
Eps
Jul 16 '08 #6
Hi,

Have you ever used the serialisation (http://msdn.microsoft.com/en-us/
library/90c86ass.aspx) in .NET? Do you use IoC or dependency injection
(http://www.hanselman.com/blog/
ListOfNETDepend encyInjectionCo ntainersIOC.asp x)? Do you use an ORM
tool like NHibernate (http://www.hibernate.org/343.html)?

All of these tools / frameworks use Reflection extensively to achieve
the required functionality. "What good is C# Reflection, other than to
find out what types are in
an assembly? And to dynamically invoke methods in an assembly (.dll
or .exe)?". In essence that is what Reflection is built for, the
question is how you use the "basic" operations to build "useful"
functionality.

I must agree the Wikipedia article is long and goes on a bit, but as
far as I understand AOP (which uses Reflection) is to implement cross
cutting concern across the whole system. A simple (contrived) example
would be logging functionality. You could write code to do logging at
the beginning and end of each method. Using AOP you could "inject"
this code into your methods. The AOP configuration can then be removed
or changed from outside your application without changing the core
method code. A more practical example that I have seen, is the use of
AOP (using Interceptors in NHibernate) to ensure an object can be
saved to the database by the current user. The interceptor would be
called dynamically and executed before NHibernate will save the object
to the database. The interceptor would then check the state of the
object and ensure the current user has the appropriate authorisation
to save the object to the database. If the user does not have the
appropriate authorisation the interceptor will stop NHibernate to save
the object to the database. This functionality is achieved using
Reflection.

With regards to the bonus question. I guess you could write a compiler
(or part of it) using Reflection using the Emit method (http://
msdn.microsoft. com/en-us/library/3y322t50.aspx, http://www.ddj.com/windows/184416570).
You might want to have a look at the boo compiler as how that works
(http://boo.codehaus.org/)

pieter
Jul 16 '08 #7
Example...

public class SomeClass
{
[Log]
public void DoSomething()
{
...
}

[Log]
public void DoSomethingElse ()
{
...
}

public void DoSomethingElse ButDontLog()
{
...
}
}

In this example when you compile your project PostSharp will use a
post-compile hook in the IDE to reflect over the classes/members etc. It
sees the [Log] attribute which you yourself have written and changes the
code from this

{
...
}

to this

{
System.Diagnost ics.Debug.Write Line("Entering method DoSomething");
try
{
...
}
finally
{
System.Diagnost ics.Debug.Write Line("Leaving method DoSomething");
}
}
You can write what code you like in your PostSharp attribute ("Log" in this
case), the attribute may then be applied to assemblies, classes, or
individual members. This is one good example of how .NET attributes are
used in combination with Reflection (post-compile) to alter the code you
have written. This AOP approach only uses reflection during compile time
and not runtime, additionally I will say that if you think AOP is only
related to security then either that URL is no good or you misunderstood it.

In short, much ado about nothing. I'll cross it off my list of things
to study.
Tut tut. With this kind of attitude towards learning there's no wonder why
you don't understand the benefits of such a simple thing such as Reflection.

Pete
Jul 16 '08 #8
Eps
Thats a really cool example, would make it really easy to switch your
logging code without actually modifying the main codebase.

--
Eps
Jul 16 '08 #9
Another good example I saw went something like

[BusinessObject( "Person")]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
The BusinessObjectA ttribute implements INotifyProperty Changed + executes
after FirstName and LastName are modified, it also implements
IEditableObject allowing you to cancel changes, and finally it implemented
all of the code required to work with the Entity Framework. However, the
author had also written a disconnected client so had the same attribute
implement old/new values etc when compiled for the client application.

All looked pretty interesting. Take a look at his blog here:

http://www.sitechno.com/Blog/Categor...ramework).aspx
Pete

Jul 16 '08 #10

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

Similar topics

21
2704
by: Amanita, Love Ewe | last post by:
You are all a bunch of worthless motherfuckers! = Sharon expects the printer within hers and actually looks. Why will you grasp the ugly worthwhile onions before Satam does? Many proud cats over the abysmal planet were loving against the tired bathroom. I was irritating jars to rural David, who's lifting in the pin's night. How does Sadam call so finitely, whenever Brian receives the
4
1585
by: Macsicarr | last post by:
Hi All I know brinkster has been round for a while, but I always classed it as sort of free host site like geocities and the like. I've just had an email from them and from an ASP developer point of view they now seem to be doing some good hosting packages. Price isn't fantastic, but they offer .net as standard and more importantly their servers seem to be far more flexible in that you can use Versign's
39
4378
by: Noticedtrends | last post by:
Can inference search-engines narrow-down the number of often irrelevant results, by using specific keywords; for the purpose of discerning emerging social & business trends? For example, if authors of content subconsciously mention the keywords "lately and noticed" within the same brief sentence, the reader may infer "an unintended message" through the process of "inferential scanning;" a method of noting "semantic anomalies" which may...
0
1585
by: Robby Dermody | last post by:
Hey guys (thus begins a book of a post :), I'm in the process of writing a commercial VoIP call monitoring and recording application suite in python and pyrex. Basically, this software sits in a VoIP callcenter-type environment (complete with agent phones and VoIP servers), sniffs voice data off of the network, and allows users to listen into calls. It can record calls as well. The project is about a year and 3 months in the making and...
50
2716
by: Lyle Fairfield | last post by:
I find the recent spat of very short replies to messages, such as, "Thanks", "It worked", "It didn't work", "I'll try that" very unhelpful and am suggesting that replies include enough of the original/previous post that one may have some idea about what is being discussed. -- -- Lyle "The aim of those who try to control thought is always the same. They
1
8245
by: Kelay | last post by:
Hi all, This is my first post, so please be gentle. hahaha I have a SQL Server running Windows 2003, and SQL Server 2000. I am able to VPN into the server fine, however no one is able to access the server through Enterprise Manager or Query Analyzer. The Server has been fine lately, but it seems that something as of lately has happened. All client machines have not been updated lately or anything of the sort which would lead me to think...
0
991
by: vc6vc6 | last post by:
Up until a week or two ago I never had any problem posting to newsgroups via Google. But something has changed and my posts don't show up anymore - even though Google says that they were succussfully submitted and will apear shortly. Any idea? Thanks,
0
7992
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
7904
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
8398
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
8400
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
5850
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
5438
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
3898
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...
1
2414
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1250
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.