How to parameterize a reference c#? - c#

Is it possible to parameterize a reference in c#?
I'm using an external library (google.dfp) and i need to update it every year with the new version. The library name contains the version (for example: "using Google.Api.Ads.Dfp.v201708;").
I would like to set the version in the app/web.config and build the using directive with this value. Is there any possibility to set a placeholder or something like this?
Thank you

As per #Damien_The_Unbeliever's comment:
using directives are only made use of at compile time.
That's pretty much the end of the discussion; it can't be done because it requires recompilation.
At best, you can write a small console application that generates the correct usnig statement, but you would still have to update the code and recompile (and redeploy).
The code change is so minimal that I wouldn't even write a small code generator for this. Copy/pasting the generated code costs as much effort as simply updating the value manually, so you're not really gaining any efficiency.

Related

Change C# code inside DLL programmatically

I got .net dll (originally, written in C#) which is being updated / released from time to time. There's a small part of code I need to modify inside this dll which suits my usage needs.
I'm able to do these changes every time using dnSpy but I don't like doing it manually every time.
Is there possibility to automate the process of code change inside dll and how can it be done?
Is it easier to convert dll to IL and change IL instructions and then compile it back or should I do full decompile to C# and then recompile it back using Roslyn?
The code I change is always the same and is changed to the same result code.
A possible solution for what you want to achieve is Mono.Cecil.
With Cecil, you can load existing managed assemblies, browse all the
contained types, modify them on the fly and save back to the disk the
modified assembly.
This library is being used by tools like coverlet which change the assembly on the fly in order to be able to compute code coverage.
That being said, I highly agree with Marc Gravell comment that at the first glance this seems to be the wrong approach and a change in design would be more appropriate.

using c# like script in runtime

I want to learn if there is any library in .net to write c# scripts. Let me describe you with more detail, for example I have an application. When I run it, a c# editor will be opened end user will write some c# codes and when click run, this code should be evaluated and dom should be created after interpret my run time c# code will run. this is brief description of my mind...
I put together a little app called SimpleDevelop which uses CSharpCodeProvider to do what you describe. My understanding is that this (CodeDom) is deprecated and generally discouraged; however, it seems to work just fine for simple scenarios.
Basically, you want to use something like the CSharpCodeProvider. The Razor view engine in MVC essentially uses this to compile your code into an executable to run. If you want your user to be able to write code and then have it interpreted, you would start here. Please note though, this is an incredibly complicated and time intensive feat to get right; plus, linking in and executing foreign code dynamically is a security nightmare. Just be safe.
Are you looking for a test bench sort of?
I use LinqPad for that.
It is mostly a test bench for Linq queries, but I find it very useful for C# statements and mini programs and such.
Check out the System.CodeDom namespace.
This article contains lots of useful information: http://www.developerfusion.com/article/4529/using-net-to-make-your-application-scriptable/2/
You can use the Compiler namespace and compilate the code at runtime. Take a look here for an explanation on how to do it.
I have created an application which will run c# like script without using visual studio.
It is on https://sourceforge.net/projects/csharpquickcode/

c# compile source code from database

I would like to build an application framework that is mainly interpreted.
Say that the source code would be stored in the database that could be edited by the users and always the latest version would be executed.
Can anyone give me some ideas how does one implement sth like this !
cheers,
gabor
In .Net, you can use reflection and CodeDOM to compile code on the fly. But neither approach is really very simple or practical. Mono has some ability to interpret c# on the fly as well, but I haven't looked closely at it yet.
Another alternative is to go with an interpreted .Net language like Boo or IronPython as the language for your database code.
Either way, make sure you think long and hard about the security of your platform. Allowing users to execute arbitrary code is always an exercise fraught with peril. It's often too tempting to look for a simple eval() method, and even if one exists, that is not good enough for this kind of scenario.
Try Mono ( http://www.monoproject.org ). It supports many scripting languages including JavaScript.
If you don't want to use any scripting you can use CodeDOM or Reflection (see Reflection.Emit).
Here are really useful links on the topic :
Dynamically executing code in .Net (Here you can find a tool which can be very helpul)
Late Binding and On-the-Fly Code
Generation Using Reflection in C#
Dynamic Source Code Generation and
Compilation
Usually the Program uses a scripting language for the scriptable parts, i.e. Lua or Javascript.
To answer your technical question: You don't want to write your own language and interpreter. That's too much work for you to do. So pick some other language, say Python or Lua, and look for the documentation that lets your C program hand it blocks of code to execute. Of course, the script needs to be able to do something, so you'll need to find how to expose your program's objects to the script. Also, what will happen if a client is running the program when you update its source code in the database? Should the client restart? Are you going to store the entire program as a single row in this database, or did you want to store individual functions? That affects how you structure your updates.
To address other issues with your question: Why do you want to do this? Making "interpreted language" part of your design spec for a system is not often a good sign. Is the real requirement something like this: "I update the program often and I want users to always have the latest copy?" If so, there are other, better ways to go about this (just give us your actual scenario and requirements).

C# How to generate code from code

Is it possible to generate and build some c# code based on the code from the same project. I tried with T4 and Reflection, but there are some assembly locking issues. Is there any other way?
Reflection works fine for me. You can get around assembly locking issues by isolating your build task to a separate AppDomain within VS. When the task completes, any assemblies you need to use for code generation will be unloaded together with the task's AppDomain. See AppDomainIsolatedTask.
You can definitely write your own code generator, all in C# - after all, "code" that's being generated is just a text file you write out.
But what's wrong with T4 templates? They offer a lot of functionality that you don't have to reinvent yet again - why not use it? Can you tell us in more detail what problems you're having with T4?
T4 is really just a bunch of classes in .NET, too - so you could definitely write your own code generator handling some of the logic, and use T4 to do the templating & replacing those template values part. But again: in order to help you diagnose your T4 problems, we'd need to know more about those....
This example from Oleg Sych uses FXCop's introspection engine instead of reflection. That way, the assemblies do not get locked.
Unfortunately, Reflection is optimized
for code execution. One particular
limitation makes it ill-suited for
code generation - an assembly loaded
using Reflection can only be unloaded
with its AppDomain. Because T4
templates are compiled into .NET
assemblies and cached to improve
performance of code generation, using
Reflection to access the component
assembly causes T4 to lock it.
Alternatively, if you're only targeting Linq to SQL classes, you could generate code from the dbml file instead of the code that L2S generates from the dbml. I've got an example of something similar (an edmx file) on my own blog.
There is a third party C# .NET variant of JavaCC that we use at work.
Also an interesting article about how to make one:
http://msdn.microsoft.com/en-us/magazine/cc136756.aspx
It really depends on what exactly are you trying to achieve, but on a general case I'd recommend using T4 templates.
And yes, it is possible to use T4 templates inside your project to generate code in your project based on some local settings, but you should define what are you trying to do.
If you want to generate code based on some classes that you define in the same project - this doesn't sound like something easily achievable (after all you want to compile some of the classes in the current project, generate some code based on them and after that generate classes again... umm.. ?)
But if you want to store some settings and then run the T4 template and generate some code based on these settings - this is easily achievable. T4MVC is an example (they generate code based on a settings file that is copied and stored in the project alongside the T4 template). This template also looks at the current files available in the solution, and generates string constants based on each file. That kind of sounds like it would really help you with your problem, whatever it is :)
If you're still unsure - you can specify more details about what you want to do, and we'll try to help you :)

Using reflection for code gen?

I'm writing a console tool to generate some C# code for objects in a class library. The best/easiest way I can actual generate the code is to use reflection after the library has been built. It works great, but this seems like a haphazard approch at best. Since the generated code will be compiled with the library, after making a change I'll need to build the solution twice to get the final result, etc. Some of these issues could be mitigated with a build script, but it still feels like a bit too much of a hack to me.
My question is, are there any high-level best practices for this sort of thing?
Its pretty unclear what you are doing, but what does seem clear is that you have some base line code, and based on some its properties, you want to generate more code.
So the key issue here are, given the base line code, how do you extract interesting properties, and how do you generate code from those properties?
Reflection is a way to extract properties of code running (well, at least loaded) into the same execution enviroment as the reflection user code. The problem with reflection is it only provides a very limited set of properties, typically lists of classes, methods, or perhaps names of arguments. IF all the code generation you want to do can be done with just that, well, then reflection seems just fine. But if you want more detailed properties about the code, reflection won't cut it.
In fact, the only artifact from which truly arbitrary code properties can be extracted is the the source code as a character string (how else could you answer, is the number of characters between the add operator and T in middle of the variable name is a prime number?). As a practical matter, properties you can get from character strings are generally not very helpful (see the example I just gave :).
The compiler guys have spent the last 60 years figuring out how to extract interesting program properties and you'd be a complete idiot to ignore what they've learned in that half century.
They have settled on a number of relatively standard "compiler data structures": abstract syntax trees (ASTs), symbol tables (STs), control flow graphs (CFGs), data flow facts (DFFs), program triples, ponter analyses, etc.
If you want to analyze or generate code, your best bet is to process it first into such standard compiler data structures and then do the job. If you have ASTs, you can answer all kinds of question about what operators and operands are used. If you have STs, you can answer questions about where-defined, where-visible and what-type. If you have CFGs, you can answer questions about "this-before-that", "what conditions does statement X depend upon". If you have DFFs, you can determine which assignments affect the actions at a point in the code. Reflection will never provide this IMHO, because it will always be limited to what the runtime system developers are willing to keep around when running a program. (Maybe someday they'll keep all the compiler data structures around, but then it won't be reflection; it will just finally be compiler support).
Now, after you have determined the properties of interest, what do you do for code generation? Here the compiler guys have been so focused on generation of machine code that they don't offer standard answers. The guys that do are the program transformation community (http://en.wikipedia.org/wiki/Program_transformation). Here the idea is to keep at least one representation of your program as ASTs, and to provide special support for matching source code syntax (by constructing pattern-match ASTs from the code fragments of interest), and provide "rewrite" rules that say in effect, "when you see this pattern, then replace it by that pattern under this condition".
By connecting the condition to various property-extracting mechanisms from the compiler guys, you get relatively easy way to say what you want backed up by that 50 years of experience. Such program transformation systems have the ability to read in source code,
carry out analysis and transformations, and generally to regenerate code after transformation.
For your code generation task, you'd read in the base line code into ASTs, apply analyses to determine properties of interesting, use transformations to generate new ASTs, and then spit out the answer.
For such a system to be useful, it also has to be able to parse and prettyprint a wide variety of source code langauges, so that folks other than C# lovers can also have the benefits of code analysis and generation.
These ideas are all reified in the
DMS Software Reengineering Toolkit. DMS handles C, C++, C#, Java, COBOL, JavaScript, PHP, Verilog, ... and a lot of other langauges.
(I'm the architect of DMS, so I have a rather biased view. YMMV).
Have you considered using T4 templates for performing the code generation? It looks like it's getting much more publicity and attention now and more support in VS2010.
This tutorial seems database centric but it may give you some pointers: http://www.olegsych.com/2008/09/t4-tutorial-creatating-your-first-code-generator/ in addition there was a recent Hanselminutes on T4 here: http://www.hanselminutes.com/default.aspx?showID=170.
Edit: Another great place is the T4 tag here on StackOverflow: https://stackoverflow.com/questions/tagged/t4
EDIT: (By asker, new developments)
As of VS2012, T4 now supports reflection over an active project in a single step. This means you can make a change to your code, and the compiled output of the T4 template will reflect the newest version, without requiring you to perform a second reflect/build step. With this capability, I'm marking this as the accepted answer.
You may wish to use CodeDom, so that you only have to build once.
First, I would read this CodeProject article to make sure there are not language-specific features you'd be unable to support without using Reflection.
From what I understand, you could use something like Common Compiler Infrastructure (http://ccimetadata.codeplex.com/) to programatically analyze your existing c# source.
This looks pretty involved to me though, and CCI apparently only has full support for C# language spec 2. A better strategy may be to streamline your existing method instead.
I'm not sure of the best way to do this, but you could do this
As a post-build step on your base dll, run the code generator
As another post-build step, run csc or msbuild to build the generated dll
Other things which depend on the generated dll will also need to depend on the base dll, so the build order remains correct

Categories

Resources