!$-Expressions

Definitions

A !$-expression is a string expression whose evaluation can be used as value to configure some actions and assertions in the Page Action Web Part. More precisely, an !$-expression is a string containing one or more Fast Lightweight Expressions (Flee expressions) each of which contained between the !$ opening tag and the $ closing tag. The expression language that Flee uses is a mix of elements of C# and VB.Net, is strongly typed (same rules as C#) and is not case-sensitive.

The evaluation of a !$-expression is the same string constituting the expression with each Flee expression replaced with its evaluation. A !$-expression coincides with his evaluation if the original string has no Flee expression.

The following is a valid !$-expression whose evaluation is the string "12":

!$ (4 * 5) - 8 $
The following string is a valid !$-expression and its evaluation is the string “Good morning, Mr. Loria, how are you?”:

Good morning, Mr. !$ CurrentUser.Name $, how are you?
The parser used to evaluate !$-expressions in the Page Action Web Part (the class ExpressionInterpreter of the Evolution.Expression namespace) can also be used independently in custom code. The Web user control ExpressionPlayground.ascx, for example, can be inserted into a SharePoint page through a SmartPart and then used as a playground for testing !$-expressions in the examples below. The C # code in the .ascx file is a good example of how to use the extended Flee parser in your code.

Expression Playground Web user control

ASP.NET and SharePoint extensions

!$-Expressions are designed to be used within the context of ASP.NET and SharePoint 2007. For this reason the parser was extended, through the addition of variables, objects and functions Ruby-like, with what is necessary to enable a simple and efficient access to the properties of the current user, the site collection, the Web site, the ASP.NET page and the same Page Action Web Part where the expressions are used.

The following tables list the objects and functions that can be used in composing !$-expressions:
.NET Framework objects
Object Description
DateTime Gives access to static members of struct DateTime
String Gives access to static members of class String
Math Gives access to static class Math
Regex Gives access to static members of class Regex

SharePoint objects
Object Description
CurrentWeb Gets the Web site (instance of class SPWeb) that is associated with the Windows SharePoint Services context. The instance is equivalent to SPContext.Current.Web.
CurrentSite Gets the site collection (instance of class SPSite) that is associated with the Windows SharePoint Services context. The instance is equivalent to SPContext.Current.Web.Site.
CurrentWebApplication Gets the parent SharePoint Web application (instance of the class SPWebApplication) for the site collection that is associated with the Windows SharePoint Services context. The instance is equivalent to SPContext.Current.Web.Site.WebApplication.
CurrentUser Gets the current user of the site, instance of the class SPUser. The instance is equivalent to SPContext.Current.Web.CurrentUser.
CurrentFile Returns the SPFile object located at the URL of the Web page that contains the code that evaluates the expression. The instance is obtained by the invocation of method SPContext.Current.Web.GetFile.

ASP.NET objects
Object Description
Page Gets a reference to the Page instance that contains the code that evaluates the expression.
Request Gets the HttpRequest object for the page that contains the code that evaluates the expression.
Session Gets the current Session object provided by ASP.NET.
Application Gets the HttpApplicationState object for the current Web request.
Cookies Gets a collection of cookies sent by the client (see HttpCookieCollection).
Cache Gets the Cache object associated with the application in which resides the page that contains the code that evaluates the expression (see Cache).

!$-Expression objects
Object Description
Expression Gives access to the constants OpeningSymbol and ClosingSymbol of the static class Evolution.Expression. ExpressionInterpreter.Expression. The evaluation of the constants equals respectively to the opening tag (!$) and closing tag ($) used to define the !$-expressions.

The evaluation of the following expression is "This !$ 12 * 3 $ is a valid expression.".

This "!$ Expression.OpeningSymbol + " 12 * 3 " +  Expression.ClosingSymbol $" is a valid expression.
Variable functions
Function Description
object Let(string variableName, object val) Assign the value val to the variable variableName within the same expression. The first character of a variable name must be a letter or underscore and the following characters can be either letters, underscores, or numbers. If the variable does not exist, creates it. The function returns val.
object Remove(string variableName) Removes the variable variableName from the collection of variables usable in the expression. The function returns the last value assigned to the variable.

A variable created through the function Let does not exist at the time of parsing the expression and therefore can not be accessed directly by simply specifying its name in the body of the expression. The evaluation of the following expression causes an error:

!$ seq(let("x", 12), x) $
Access to a variable created by Let must be done by the function Eval as follows:

!$ seq(let("x", 12), eval("x")) $
Eval function
Function Description
object Eval(string text) Evaluate the content of the string text passed as an argument as if it were a Flee expression and returns its value.

The value resulting from evaluation of the following expression is 240.

!$ seq(
          let("x", 12),
          let("y", 20),
          eval("x * y")
) $
Text functions
Function Description
string Escape(string text) Replaces each occurrence of the character ' with the character " in the string text passed as argument.
string Format(string source) Replaces one or more format items in the string source passed as argument with the value of the corresponding variables. The syntax of a format item is as follows: {variableName}. If a specified variable does not exist, the corresponding format item will be replaced with an empty string.
string FormatExpression(string source) Returnes a string that when passed as argument to the function Eval, the Flee expressions in the original string source (enclosed in braces as follows: {Flee expression}) are replaced by the corresponding evaluations. Unlike the function Format, which replaces variable names with their values in the original string, FormatExpression does not evaluate the expressions contained in the string.
string ToString(IEnumerable e) Returns a string that is the concatenation of the elements of e. If e can be cast to IDictionary, the returned string is the concatenation of the values of the dictionary. Between an element and the next is put the string ", " as a separator.
string ToString(IEnumerable e, string sep) Returns a string that is the concatenation of the elements of e. If e can be cast to IDictionary, the returned string is the concatenation of the values of the dictionary. Between an element and the next is put the string sep as a separator.

The Escape function can be used as an alternative to the use of escape characters to insert quotes in strings. The evaluation of this expression:

!$ seq(
          let("x", 12), 
          let("y", 2),
          eval("\"x * y = \" + x * y")
) $
and this expression:

!$ seq(
          let("x", 12), 
          let("y", 2),
          eval(
                 escape("'x * y = ' + x * y")
          )
) $
is the same.

Below an example of use of the function Format. The evaluation of this expression is the string "The variable 'x' is equal to 12 and the variable 'y' is equal to "hello!". ":

!$ seq(
         let("x", 12),
         let("y", "hello!"),
         format("The variable 'x' is equal to {x} and the variable 'y' is equal to \"{y}\".")
) $
The following code examples show how to use the FormatExpression. For another example of use, see Concat.

The evaluation of the following Flee expression:
<BR /><BR />
!$ FormatExpression("The current user's name is {CurrentUser.Name} and his email is {CurrentUser.Email}.") $
<BR /><BR />
is the string:
<BR /><BR />
!$ Eval(
          FormatExpression("The current user's name is {CurrentUser.Name} and his email is {CurrentUser.Email}.")
) $
Array creation and conversion functions
Function Description
char[] FromRange(char from, char to) Returns a character array containing all possible values between a start value (from) and an end value (to).
int[] FromRange(int from, int to) Returns a int array containing all possible values between a start value (from) and an end value (to).
DateTime[] FromRange(DateTime from, DateTime to) Returns a DateTime array containing all possible values (varying the value of the day) between a start date (from) and an end date (to).
DateTime[] FromRange(DateTime from, DateTime to, DateTimePart part) Returns a DateTime array containing all possible values (varying the component of the date specified in the constant part) between a start date (from) and an end date (to).
object[] FromEnumerable(IEnumerable e) Returns an array of objects containing all the values of the instance of IEnumerable e used as an argument.
object[] FromEnumerable(IDictionary dict) Returns an array of objects containing all the keys and the values, both included in the array of destination alternately, of the instance of IDictionary dict used as an argument.
T[] FromList(params T[] args) Returns an array of elements of type T (with T equal to DateTime, Int16, Int32, Int64, object, string, SByte, Single, double, decimal, bool, byte or char) containing all the arguments passed in the invocation of the function.
string[] FromString(string text, params string[] args) Returns a string array that contains the substrings in the string text that are delimited by elements specified in the remaining arguments. This function omits empty array elements from the array returned. If no delimiters are specified, the space is used.
Hashtable ToDict(params object[] args) Returns an instance of Hashtable containing all the arguments passed in the invocation of the function, considered as a sequence of pairs (key / value).

Below is an example of use of the function ToDict:

!$ seq(
          let("x", ToDict("a", 101, "b", 202, "c", 303)), 
          eval(
                 escape("x['b']")
          )
) $
Concat functions
Function Description
string Concat(IEnumerable a, string variableName, string expression) Evaluates expression once for each element of a and returns the string resulting from the concatenation of the evaluations. At each step, the current element is assigned to the variable variableName. If the variable does not exist prior to the evaluation of Concat, it is initially created and destroyed at the end. All elements of a must be of the same type.
string Concat(IEnumerable a, string variableName, string expression, string separator) As Concat, but the string separator is concatenated between a evaluation and the subsequent.
string ConcatDist(IEnumerable a, string variableName, string expression) As Concat with the same signature, but the elements of a can be of different types.
string ConcatDist(IEnumerable a, string variableName, string expression, string separator) As Concat with the same signature, but the elements of a can be of different types.
string ConcatDict(IDictionary a, string variableName, string expression) As Concat but iterating over a IDictionary. In the expression, the key and the value of the current element are obtained by "variableName.Key" and "variableName.Value".
string ConcatDict(IDictionary a, string variableName, string expression, string separator) As Concat but iterating over a IDictionary. In the expression, the key and the value of the current element are obtained by "variableName.Key" and "variableName.Value".

The following code samples show how to create an HTML table showing the list of SharePoint site users and, for each, the list of groups to which it belongs:

<table cellspan="0" colspan="0" border="1" width="100%">
    <tr>
        <td width="30%">User name</td>
        <td width="70%">Groups</td>
    </tr>
  !$ concat(
                CurrentWeb.SiteUsers, 
                "x", 
                FormatExpression(
                                escape(
                                       "<tr valign=top><td>{x.Name}</td><td>{ToString(x.Groups, '<br/>')}</td></tr>"
                                )
                )             
  ) $
</table>
Select and Reject functions
Function Description
object[] Select(IEnumerable a, string variableName, string expression) Evaluates expression once for each element of a and returns a objects array that contains any element where the evaluation returns true. At each step, the current element is assigned to the variable variableName. If the variable does not exist prior to the evaluation of Select, it is initially created and destroyed at the end. All elements of a must be of the same type.
object[] SelectDist(IEnumerable a, string variableName, string expression) As Select, but the elements of a can be of different types.
DictionaryEntry[] SelectDict(IDictionary a, string variableName, string expression) As Select but iterating over a IDictionary. In the expression, the key and the value of the current element are obtained by "variableName.Key" and "variableName.Value".
object[] Reject(IEnumerable a, string variableName, string expression) Evaluates expression once for each element of a and returns a objects array that contains any element where the evaluation returns false. At each step, the current element is assigned to the variable variableName. If the variable does not exist prior to the evaluation of Reject, it is initially created and destroyed at the end. All elements of a must be of the same type.
object[] RejectDist(IEnumerable a, string variableName, string expression) As Reject, but the elements of a can be of different types.
DictionaryEntry[] RejectDict(IDictionary a, string variableName, string expression) As Reject but iterating over a IDictionary. In the expression, the key and the value of the current element are obtained by "variableName.Key" and "variableName.Value".

The following code samples show how to use Select and Reject .

List of odd numbers between 1 and 10:
   
!$ Concat(
              Select(
                       FromRange(1, 10), 
                       "x", 
                       "x % 2 = 1"
              ), 
              "y", 
              "y", 
              ", "
) $
<br/>List of even numbers between 1 and 10:
   
!$ Concat(
               Reject(
                         FromRange(1, 10), 
                         "x", 
                         "x % 2 = 1"
               ), 
               "y", 
               "y", 
               ", "
) $
The following code samples show how to use SelectDict:

!$ Concat(
               SelectDict(
                         ToDict(
                                   "John", "male", 
                                   "William", "male", 
                                   "Daniel", "female", 
                                   "Carl", "male", 
                                   "Katia", "female"
                         ), 
                         "x", 
                         "x.Value = \"female\""
               ), 
               "y", 
               "y.Key + \" = \" + y.Value", 
               "<br/>"
) $
Iterate functions
Function Description
object[] Iterate(IEnumerable a, string variableName, string expression) Returns a new array with the results of evaluating expression once for every element in a. At each step, the current element is assigned to the variable variableName. If the variable does not exist prior to the evaluation of Iterate, it is initially created and destroyed at the end. All elements of a must be of the same type.
object[] IterateDist(IEnumerable a, string variableName, string expression) As Iterate, but the elements of a can be of different types.
object[] IterateDict(IDictionary a, string variableName, string expression) As Iterate but iterating over a IDictionary. In the expression, the key and the value of the current element are obtained by "variableName.Key" and "variableName.Value".

The following code samples show how to use IterateDist to display the types of array elements:

!$ Concat(
               IterateDist(
                               FromList(
                                            "some text", 
                                            1, 
                                            true, 
                                            String.Empty, 
                                            DateTime.Now, 
                                            false
                               ),
                               "item",
                               "TypeOf(item).FullName"
               ), 
               "X", 
               "X", 
               "<br/>"
) $
Inject functions
Function Description
T Inject(IEnumerable<T> a, T initValue, string acc, string currentElement, string expression) The function loops over all elements of a, by assigning the value of the current element to the variable currentElement and then evaluating the expression. The evaluation result is then saved in the variable acc (the "accumulator" of the function). For each cycle, therefore, the value of the accumulator can be determined by the value given by the current element and by the previous value of the same accumulator. At the first step the accumulator is set with the value specified by initValue. The function's return value is the final value assumed by the variable acc. If variables currentElement and acc do not exist prior to the evaluation of Inject, they are initially created and destroyed at the end. The types allowed for T are DateTime, string, SByte, Single, Int16, Int32, Int64, double, decimal, bool, byte or char.

The following code samples show how to use Inject to calculate the sum of the first 10 numbers.

!$ inject(
            FromRange(1, 10), 
            0, 
            "acc", 
            "elem", 
            "acc + elem"
) $
The following code samples show how to use Inject to determine the longest word.

!$ inject(
            FromString("Lorem ipsum dolor sit amet, consectetur adipiscing elit"), 
            "", 
            "acc", 
            "elem", 
            "if(acc.Length > elem.Length, acc, elem)"
) $
Conditional functions
object Choose(int index, params object[] args) Returns a value from the list of choices based on the value of index. If index is 1, Choose returns the first choice in the list; if index is 2, it returns the second choice, and so on. If index is greater than the number of choices listed, the function always returns the last choice.
object[] When(object test, object[] toTest, object[] values) For each element of toTest, checks if the element is equal to test and, if so, inserts the element of values placed on the same index in the array of objects returned by the function. If the test fails for each element of toTest, the function returns an empty array. The dimensions of toTest and values must coincide.
object[] When(object test, object defaultValue, object[] toTest, object[] values) For each element of toTest, checks if the element is equal to test and, if so, inserts the element of values placed on the same index in the array of objects returned by the function. If the test fails for each element of toTest, the function returns an array with the only element defaultValue. The dimensions of toTest and values must coincide.
object[] When(object test, params object[] args) The function checks what arguments of args in odd position are equal to test and returns an array formed by the arguments in even position that follow those that meet the check. The number of elements of args must be even.

The following code samples use when to return the list of SharePoint groups to which the current user does not belong.

!$ ToString(
                 when(
                          false, 
                          iterate(
                                    CurrentWeb.SiteGroups, 
                                    "x", 
                                    "x.ContainsCurrentUser"
                          ), 
                          iterate(
                                    CurrentWeb.SiteGroups, 
                                    "x", 
                                    "x.Name"
                          )
                 ), 
                 "<BR />"
) $
The following code samples indicate how many groups the current user belongs.

The current user 
!$ when(
            CurrentUser.Groups.Count,
            "belongs to " + CurrentUser.Groups.Count + " groups.",
            FromRange(0, 1),
            FromList("does not belong to any group.", "belongs to one group.")
)[0]
$
Miscellaneous functions
Function Description
Type TypeOf(object value) Gets the System.Type of the passed argument.
object Seq(params object[] args) The function causes the evaluation of the expressions passed as arguments and returns the value of the last as a return value. The function returns 0 if it is invoked with no arguments.

References to the Fast Lightweight Expression Evaluator

To obtain detailed information about the parser used in the evaluation of the !$-expressions (a language reference on the expression language, FAQ and examples), see the project Fast Lightweight Expression Evaluator. The version of Flee used in the Page Action Web Part is 0.9.26.0.
See also
  • Introduction to Page Action Web Part.
  • Project Description, for a more detailed overview.
  • Action list, to get information about the available actions.
  • Assertion list, to get information about the assertions that can be used to create a condition (this documentation is not ready yet).
  • !$-expressions, ie this page.

Last edited May 25, 2010 at 2:30 PM by DavideLoria, version 128

Comments

No comments yet.