How it works

QInjection receives a lambda expression and evaluate it on your datas in oredr to filter them.
Usually, the result got using QInjection is the same got with the statement:

	var filtereddata = datacollection.Where(<lambda expression>)


Inputs of QInjection are the lambda expression and "your data collection".
From a psychological point of view it's hard for a programmer to allow someone to inject every kind of lambda expression inside its code. So QInjection allow you to define syntax of the lambda expression to accept as input.

Let's me to explain.
A lambda expression can be simple as "x => x == 1" or something more complex like "x => x.Count() > 0 && x0 % 2 == 1 && x.Sum() > 100".
Here the main question is how you can restrict the execution of malicious code.

Current version of QInjection allow to define the "syntax" of the lambda expression, and this is done using Roslyn API.
Lambda expression can be parsed using Roslyn and it's translated into an Abstract Syntax Tree (AST).

Consider following expression "x => x == 1".
It's Roslyn AST is the following one:

SimpleLambdaExpressionSyntax:
	Parameter:
		IdentifierToken
	Body: BinaryExpressionSyntax
			Left: IdentifierNameSyntax
			Right: LiteralExpressionSyntax


QInjection helps you to set up the syntax of the lambda expression using code like this:

injector = injector.Support(Node.SimpleLambdaExpression).As(Branch.Input)
    .Support(Node.BinaryExpression).As(Branch.Body)
    .Support(Node.IdentifierName).As(Branch.LeftMember)
    .Support(Node.LiteralExpression).As(Branch.RightMember)
    .Support(Node.Parameter).As(Branch.Parameter);


The pair of methods "Support" and "As" allow you to build a simple Syntax Validator.
For each kind of attribute of a Roslyn Node (represented by the TreeProperty enumeration) you define what exaclty you will accept as Syntax Node.

You can see how you have to define step by step the syntax of the expression ... and maybe this is the most hard task because you have to know how c# AST is made.
Note also that current version of the QInjection has a limited support but I'll improve it in the future.

After you set up the syntax validation engine you have to validate the expression using a simple statement:

	injector.Validate();


The validate method builds the AST and it walks through it by validating each tree's branch. An exception is thrown if you have a syntax mismatch.

At the end of the process you have to inject the expression:

	var genericdata = injector.WhereOn<Int32>(provider4injector);


Here you have to note two things: your class "provider4injector" have to implement the interface QInjectio<Int32> and the generic method "WhereOn" have to use the same Int32 type. Inside it the WhereOn method builds a Roslyn Script and runs it using your class as Container.

Last edited Dec 27, 2013 at 1:36 PM by SamNium, version 2