views:

394

answers:

3

I am working on doing an aspx page to display code usage examples of a library.

So basically, I'd like to for example have: Description Source Code Button Output (in a datagrid)

Rather than copying and pasting the code from behind the button into the aspx page for display purposes, I was thinking it might be nice to be able to be able to read the actual source code at runtime and display it. Other than being slick, this would have the added benefit of ensuring that the source code displayed is up to date, whereas a copy and paste could get out of date if someone makes a change and forgets to update the aspx page with the new code.

I can think of 2 possible ways to do this: 1) (kludgy) - Deploy the code behind files, which can then be read at runtime and the proper function code can be parsed out and displayed. 2) (Preferred) Run time decompile the DLL (as reflector does) and display the code.

So I know how to do #1, but no idea about #2 (if it is even possible).

A: 

If you want to preserve comments and the original variable names then reflection isn't going to work. Parsing the code would probably be the most straight forward way to do this. There might also be an option of extracting the data out of the PDB files.

David
+3  A: 

Reading the actual source files is the way to go here, IMO - if you're really, really sure you don't mind everyone being able to see your server's source code. If you use something like Reflector you'll lose all comments, possibly local variables, and things like iterator blocks will become particularly odd.

I have a code formatter (as a control, in fact) which I use on the C# in Depth web site. It's relatively primitive, but you're welcome to it if you want. (You can use it via a page on the site itself, if you want to give it a try.)

Jon Skeet
+4  A: 

Decompiling the code at run time wouldn't yield you exact same code as what you wrote. At that point it becomes more of an interpretation.

A third option is to have your app work against your code repository to retrieve a specific file. You would then display that file's contents in the browser. It's similar to option 1 but you wouldn't be deploying the .cs files directly to the server.

Ian Suttle
+1 for retrieving source code from code repository.
Darin Dimitrov