Advice on C# Expression Trees - c#

I'm working on a method that accepts an expression tree as a parameter, along with a type (or instance) of a class.
The basic idea is that this method will add certain things to a collection that will be used for validation.
public interface ITestInterface
{
//Specify stuff here.
}
private static void DoSomething<T>(Expression<Func<T, object>> expression, params IMyInterface[] rule)
{
// Stuff is done here.
}
The method is called as follows:
class TestClass
{
public int MyProperty { get; set; }
}
class OtherTestClass : ITestInterface
{
// Blah Blah Blah.
}
static void Main(string[] args)
{
DoSomething<TestClass>(t => t.MyProperty,
new OtherTestClass());
}
I'm doing it this way because I'd like for the property names that are passed in to be strong typed.
A couple of things I'm struggling with..
Within DoSomething, I'd like to get a PropertyInfo type (from the body passed in) of T and add it to a collection along with rule[]. Currently, I'm thinking about using expression.Body and removing [propertyname] from "Convert.([propertyname])" and using reflection to get what I need. This seems cumbersome and wrong. Is there a better way?
Is this a specific pattern I'm using?
Lastly, any suggestions or clarifications as to my misunderstanding of what I'm doing are appreciated and / or resources or good info on C# expression trees are appreciated as well.
Thanks!
Ian
Edit:
An example of what expression.Body.ToString() returns within the DoSomething method is a string that contains "Convert(t.MyProperty)" if called from the example above.
I do need it to be strongly typed, so it will not compile if I change a property name.
Thanks for the suggestions!

I rely heavily on expression trees to push a lot of what I want to do with my current application to compile-time, i.e. static type checking.
I traverse expression trees to translate them into something else which "makes sense".
One thing I've ended up doing a lot is that instead of URLs I rely on a MVC like approach where I declare lambda functions, and translates that... interpret, the compiler generated expression tree into an URL. When this URL is invoked, I do the opposite. This way, I have what I call compile-time checks for broken links and this works great with refactoring and overloads as well. I think it's cool to think about using expression trees in this way.
You might wanna check out the visitor pattern, it's a pain to get started with because it doesn't make much sense in the beginning but it ties everything together and it's a very formal way to solve type checking in compiler construction. You could do the same, but instead of type checking emit what ever you need.
Something which I'm currently pounding my head against is the ability to build a simple framework for translating (or actually I should say interpret) expression tress and emit JavaScript. The idea is that the compiler generated expression trees will translate into valid JavaScript which interfaces with some object model.
What's exciting about this is the way the compiler is always able to tell me when I go wrong and sure the end result is just a bunch of strings but the important part is how these strings got created. They went through some verification and that means something.
Once you get that going there is little you can't do with expression trees.
While working with the System.Reflection.Emit stuff I found myself using expression trees to create a light-weight framework for dynamic compilation, which at compile time could basically say if my dynamically created assemblies would compile as well, and this worked seamlessly with reflection and static type checking. It took this further and further and ended up with something which in the end saved a lot of time and proved to be very agile and robust.
So I love this kind of stuff, and this is what meta programming is all about, writing programs in your programs that do programs. I say keep it coming!

Collecting PropertyInfo objects from Expression.Body seems similar to my solution to another question.

I appreciate what you are trying to do with the property here. I have run into this conundrum. It always feels weird to write:
DoSomething("MyProperty", new OtherClass());
If the property ever changes name, or the text is mistyped in the call, then there will be a problem. What I have come to learn is that this is something you probably have to deal with via testing. Specifically, unit testing. I would write unit tests to enforce that the "DoSomething" calls work correctly.
The other thing you might try is to decorate your properties with attributes, and then reflect against your class when it is constructed looking for properties with the attribute, and load rules.
[DoSomething(typeof(OtherClass), typeof(OtherClass2))]
public int MyProperty
{
get;
set;
}
In this case the constructor (perhaps in a base class?) would dynamically create an OtherClass object and a OtherClass2 object, and load them into a collection along with the name of the property.

Related

Find usages of a generic class with specific constraint

As per title, how can I find usages of the method Process for Processor<int> rather than Processor<string>?
internal class Program
{
private static void Main()
{
var processorInt = new Processor<int>();
var processorString = new Processor<string>();
processorInt.Process();
processorString.Process();
}
}
internal class Processor<T>
{
public void Process() => Console.WriteLine(typeof(T).Name);
}
ReSharper can handle this out of the box. If you try to perform a search for references, it'll actually ask you what you want to look for. Just declare a dummy variable of the type you want to look for, and call Find Usages, on the type name.
Note that this works for generic classes and generic methods, but it won't help you if you're looking for usages of a method in a generic class with a given type parameter.
Or just use Right click -> Find usages advanced:
You can't using standard tools.
You either have to:
Press Ctrl+K, Ctrl+R to find all references to Processor<T>.
Visually filter on Processor<int> yourself.
Or:
Find all using text search on Processor<int>. This is not very useful when you have SomeOtherProcessor<int> too, since that would match too.
This are the only options I have come up with. Other developer tools, like Resharper, might have an option that is better.
I fear the only way to achieve this is by directly searching for Processor<int>() within the search-and-replace-tool. Quite annoying though. However this won´t help ypu much if your generic class has a generic interface-parameter instead of a struct or class. Thus you cannot search for usages of Processor<MyInterface>() when you are interested on occurences of all Processor with a generic parameter of that interface.
You can use my tool built with Roslyn APIs:
https://github.com/UnoSD/SubTypeReferencesAnalysis

What does the syntax seen when decompiling c# dynamic operations actually mean?

I've recently had to make a forray into decompiling a colleague's code while they're away, and found that most of it looks surprisingly nice (thanks ILSpy), with the notable exception of a couple of places where we needed to use dynamic - these got mangled into several parts:
A call site container - i.e. what resembles a class in definition, but let's say the method in which dynamic was used was DoStuff, would have a declaration along the lines of public /* static? I forget */ class <DoStuff>CallSiteContainer_Plus_Some_Weirdness { /* bunch of CallSite fields */ }
A lot of code that checks whether various CallSites within the container have been assigned and assigns them before usage as required using approaches I really don't get yet.
My question is regarding the syntax of the class declaration in the 1st point. It looks like a generic class, but it clearly isn't. Can anyone explain what's going on there?
Please note, I'm not looking for help in working out the original code - I've already managed to do that by judicious use of find and replace, and breaking out the autogenerated code from everything else. But I'd like to understand how the CallSite container syntax is a valid class name!
Here's an example of such auto-generated class:
private static class <>o__0
{
public static CallSite<Action<CallSite, Type, object>> <>p__0;
}
If you are worried about the <>o__0 class name and the <>p__0 field name, then you are right, those are not valid C# names but this doesn't mean that they are not valid IL names which is what the compiler generates. The reason why it uses such special symbols is to ensure that they will never conflict with class names that you as a developer might have written.

What is the motivation of C# ExpressionVisitor's implementation?

I have to design a solution for a task, and I would like to use something theoretically similar to C#'s ExpressionVisitor.
For curiosity I opened the .NET sources for ExpressionVisitor to have a look at it. From that time I've been wondering why the .NET team implemented the visitor as they did.
For example MemberInitExpression.Accept looks like this:
protected internal override Expression Accept(ExpressionVisitor visitor) {
return visitor.VisitMemberInit(this);
}
My - probably noob - question is: does it make any sense? I mean shouldn't the Accept method itself be responsible of how it implements the visiting within itself? I mean I've expected something like this (removing the internal visibility to be overridable from outside):
protected override Expression Accept(ExpressionVisitor visitor) {
return this.Update(
visitor.VisitAndConvert(this.NewExpression, "VisitMemberInit"),
visitor.Visit(this.Bindings, VisitMemberBinding)
);
}
But this code is in the base ExpressionVisitor's VisitMemberInit method, which gets called from MemberInitExpression.Accept. So seems like not any benefit of the Accept implementation here.
Why not just process the tree in the base ExpressionVisitor, and forget about all the Accept methods?
I hope you understand my points, and hope someone could shed some light on the motivation behind this implementation. Probably I don't understand the Visitor pattern at all?...
A visitor can override the way any expression is visited. If your proposal was implemented in all places the visitor never would be called. All the visitation logic would be in the overrides of Accept. Non-BCL code cannot override this method.
If you write visitor.Visit((Expression)this.SomeExpression) (like you do in the question) then how are you going to perform dynamic dispatch on the type of SomeExpression? Now the visitor has to perform the dynamic dispatch. Note, that your 2nd code snippet makes the simplifying assumption that all sub-expressions to be visited have known type. Try to write the code for BinaryExpression to see what I mean.
Maybe I did not understand something but this proposal does not make sense.
The purpose of the Accept method is a performance optimization. Each accept is a virtual call which is rather cheap. The alternative would be to have a huge switch in the visitor over the expression type (which is an enum). That's probably slower.
The visitor pattern allows the algorithm to essentially be separated from the structure it's operating on. In this case the structure it operates on is the expression tree.
Notice that the Accept method in the visitor is virtual. This means we could conceivably write different implementations of ExpressionVisitor that do different things to an expression tree (and, indeed, there are different implementations). And we can do this without changing any code in the expression tree classes themselves.
Examples of different visitor implementations might be something like having one visitor that turns the expression tree back into a string representing C# code (or perhaps code in another language).

Checking custom attribute parameters at design/build time

I have a CustomAuthorize attribute that checks to see if a user has access to functionality (a user or role can be associated with items from a hierarchical set of functions).
For a given action method...
[CustomAuthorize("Security.Admin.ManageWidgets.Update")]
This works but I'm concerned that changes to the Security object could cause problems that won't be detected until run-time. I realize that I can write unit tests to mitigate this risk but I would like to know if it is possible to check the attribute parameter at compile time. I also like having Intellisense help me type this expression.
Ideally, I could pass a lambda expression.
[CustomAuthorize(i => i.Admin.ManageWidgets.Update)]
Unfortunately this is not currently possible (additional info from Microsoft).
I also tried encapsulating the expression hoping it would be evaluated and then passed to the attribute as a string, but this also failed to compile with the same error (Expression cannot contain anonymous methods or lambda expressions).
[CustomAuthorize(LambdaToString(i => i.Admin.ManageWidgets.Update))]
How can I add some design-time / build-time support for my custom attribute parameters?
A Static class with constants.
public static class Rights
{
public const string UpdateWidgets = "UpdateWidgets";
}
Also include unittests for the methods which are decorated with them and you'll be pretty good.
[CustomAuthorize(Rights.UpdateWidgets)]
You can use T4 templates to create custom classes with string properties, ending up with code similar to BennyM's, but generated automatically.
No you can't check these sorts of things at compile time - the best you could hope for is a post-build step that checks this via reflection.
You could instead supply a type and a method name, like this:
[CustomAuthorize(typeof(Security.Admin.ManageWidgets), "Update")]
But seeing as you still need to type the name of the method its debatable what benefit this really gains you.

What is the intent of dynamics in C# 4.0? What are some "neat" uses of it?

Just as the title states... is it primarily for instances where you don't know precisely what type will be returned from a method call (COM interop maybe)?
Here is an example that i consider a nice improvement, it doesn't change a great deal, but it's the little things in life that make a difference :)
http://weblogs.asp.net/gunnarpeipman/archive/2010/07/27/asp-net-mvc-3-new-viewmodel-is-dynamic-viewdata.aspx
As you mention, it makes it easier to interoperate with dynamic languages.
For me, that usually means javascript. One of my favorite uses is consuming JSON on the server without defining DTOs - which also enables LINQ to JSON:
JsonObject body;
string[] favoriteToys =
(from child in (JsonValue)body.AsDynamic().Children
where child.Value.AsDynamic().Name.ReadAs<string>(string.Empty).StartsWith("J")
select child.Value.AsDynamic().BestToy.ReadAs<string>("No favorite toy"))
.ToArray();
(Sample code lifted from "Okay, WCF, we can be friends now", and be sure to see "WCF support for jQuery on wcf.codeplex.com")
If you didn't exactly know the type of a variable, or you wanted to allow the user to specify a class to load at runtime and use the C# reflection API to load it, then you could use dynamic typing so that the user does not need their class to derive from anything, but just needs to define certain methods (an exception would be thrown if not and an error printed from the exception to tell the user what happened).
The advantage of this is that there would be less typing by the user, and therefore less space for user error.
They are useful in scenarios where you don't know the return type, or you don't know at compile-time what members will be available on an object, so you can defer it until run-time. Another neat use of dynamic is ExpandoObject. This allows you to added members to an object at run-time. I've used it to replace Dictionary<string, object> style code.
Yes, COM interop is probably the most common place where dynamics will be incredibly useful. I've used it in conjunction with IronPython to make calls to python methods (which are dynamic scripts by nature) much cleaner and easier. These are the kinds of things it was intended for.
That said, the overall effect of introducing dynamics is to enable C# to become a kind of scripting language, and there is a strong likelihood that it will be used for a number of other purposes along those lines (much to the horror of language purists). For example, the ViewBag property in MVC 3 is just a dynamic wrapper for the ViewData collection. It makes syntax look just a tad "cleaner" (ViewBag.FirstName instead of ViewData["FirstName"]), but at the potential cost of clarity: At a glance, a C# developer might assume that the former is an access to a property on a strongly-typed object of some kind, which can give them a false sense of security when there are no compiler errors.
I've also heard of frameworks that can deserialize a JSON string into a dynamic object, so your .NET system could handle dynamic javascript objects from AJAX requests in much the same way javascript handles them. It's really cool to some people and at least a little creepy to others.
one of the "cool" things you get with dynamic is multiple dispatch without the visitor pattern.
public class Fruit {}
public class Apple : Fruit {}
public class GrannySmith : Apple {}
public class FruitSalad
{
public void Mix(Apple apple) {
Console.WriteLine("mixing a apple");
}
public void Mix(GrannySmith apple) {
Console.WriteLine("mixing a Granny-Smith apple");
}
public void Mix(Fruit fruit) {
Console.WriteLine("unknown fruit, can't mix!");
}
}
public static void Main(string[] args)
{
var salad = new FruitSalad();
Fruit fruit = new Apple();
salad.Mix(fruit); // unknown fruit, can't mix
// (can't resolve onm the type of parameter)
dynamic fruit2 = new Apple();
salad.Mix(fruit2); // mixing a apple
// with dynamic, the parameter's resolution
// is deferred to runtime, so now we know it's an apple
}

Categories

Resources