Skip to content

Functions

Craig edited this page Mar 20, 2019 · 23 revisions

Nettle functions perform tasks and return a result; which can be an object of any type. Functions can take zero or more parameters; a string literal, number, boolean, property or variable. The syntax for using a function is {{@FunctionName(Param1, Param2, ...)}}.

For example:

{{@Truncate("Hello World!", 5)}}

Which would generate:

Hello

Core

The table below lists all of the core functions in Nettle.

Name Description Parameters Returns
Add Adds two numbers together. NumberOne (double), NumberTwo (double) The sum of the two numbers.
Average Computes the average from a sequence of numeric values. Array (double) The average of all numbers.
Count Counts the number of items in a collection. Collection (IEnumerable) The number of items found.
Concat Concatenates a collection of values into a single string. Array (object) The concatenated string.
Divide Divides two numbers. NumberOne (double), NumberTwo (double) The value calculated.
FormatDate Formats a date and time. Date (DateTime), Format (string) A string that contains the formatted date.
FormatString Converts the value of objects to strings based on the formats specified and inserts them into another string. Format (string), Array (object) A copy of format in which the format items have been replaced by the string representations of the corresponding arguments.
ParseDate Parses a date and time from a string. Date (DateTime), RawValue (string) A DateTime object.
GetDate Gets the current date and time. None A DateTime object.
AddDays Adds a specific number of days to a date and time. Date (DateTime), Value (double) A DateTime object.
AddHours Adds a specific number of hours to a date and time. Date (DateTime), Value (double) A DateTime object.
AddMilliseconds Adds a specific number of milliseconds to a date and time. Date (DateTime), Value (double) A DateTime object.
AddMinutes Adds a specific number of minutes to a date and time. Date (DateTime), Value (double) A DateTime object.
AddMonths Adds a specific number of months to a date and time. Date (DateTime), Value (double) A DateTime object.
AddSeconds Adds a specific number of seconds to a date and time. Date (DateTime), Value (double) A DateTime object.
AddYears Adds a specific number of years to a date and time. Date (DateTime), Value (double) A DateTime object.
ConvertTime Converts the value of a date to a specific time zone. Date (DateTime), TimeZoneId (string) A DateTime object.
ToLocalTime Converts the value of a date to local time. Date (DateTime) A DateTime object.
HtmlEncode HTML encodes a string. Text (string) The HTML encoded text.
Join Joins an array of items, using the specified separator between each element. Array (object) A string that consists of the elements in value delimited by the separator string.
LargestNumber Gets the largest number of a sequence. Array (double) The largest number found.
Multiply Multiplies two numbers together. NumberOne (double), NumberTwo (double) The sum of the two numbers.
PadLeft Left pads a string with a custom character to the width specified. Text (string), TotalWidth (int), PaddingChar (string) The text with padding.
RandomDouble Generates a random double between a range. MinValue (double), MaxValue (double) The random number generated.
RandomInteger Generates a random integer between a range. MinValue (int), MaxValue (int) The random number generated.
Replace Replaces text in a string with other text. OriginalText (string), FindText (string), ReplaceText (string) The updated text.
Reverse Reverses the order of a string. Text (string) The reversed text.
RightLeft Right pads a string with a custom character to the width specified. Text (string), TotalWidth (int), PaddingChar (string) The text with padding.
Round Rounds a number to a set number of decimal places. Number (double), Decimals (int) A double rounded to the number of decimals specified.
SmallestNumber Gets the smallest number of a sequence. Array (double) The smallest number found.
Subtract Subtracts two numbers from each other. NumberOne (double), NumberTwo (double) The sum of the two numbers.
Sum Computes the sum of a sequence of numeric values. Array (double) The sum of the numbers.
FromBase64String Converts a base-64 encoded string to a byte array. Data (string) A byte array.
ToBase64 Converts a byte array to a base-64 string. Data (byte[]) A base-64 encoded string.
ToBoolean Converts an object to a Boolean. Value (object) A Boolean representation of the value.
ToByte Converts an object to a byte. Value (object) A byte representation of the value.
ToChar Converts an object to a char. Value (object) A char representation of the value.
ToDateTime Converts an object to a DateTime. Value (object) A DateTime representation of the value.
ToDecimal Converts an object to a decimal. Value (object) A decimal representation of the value.
ToDouble Converts an object to a double. Value (object) A double representation of the value.
ToInt16 Converts a double to an equivalent 16-bit signed integer. Number (double) A 16-bit signed integer.
ToInt32 Converts a double to an equivalent 32-bit signed integer. Number (double) A 32-bit signed integer.
ToInt64 Converts a double to an equivalent 64-bit signed integer. Number (double) A 64-bit signed integer.
ToSingle Converts an object to a single. Value (object) A single representation of the value.
ToString Converts an object to a string. Value (object) A string representation of the value.
ToUpper Converts a string to upper case. Text (string) The converted string.
ToLower Converts a string to lower case. Text (string) The converted string.
ToTitleCase Converts a string to title case. Text (string) The converted string.
Truncate Truncates a string to the length specified. Text (string), Length (int) The truncated text.
IsDefined Determines if a property has been defined. Path (string) True, if the property has been defined; otherwise false.
GetEnvironmentVariable Retrieves the value of a Nettle environment variable. Name (string) The matching variable.

Data Extension

The Nettle.Data extension provides the following functions:

Name Description Parameters Returns
ExecuteQuery Executes an SQL query against a database. ConnectionName (string), SQL (string) An IDataGrid containing the results of the query.
ExecuteStoredProcedure Executes a stored procedure in a database. ConnectionName (string), ProcedureName (string), An array of parameter values (key value pair) An IDataGrid containing the results of the stored procedure.
ReadCsv Reads a CSV file into a new data grid object. FilePath (string) An IDataGrid object containing the CSV data.
ReadJson Reads a JSON file into a new JObject object. FilePath (string) An JObject object containing the JSON data.
ReadText Reads the contents of a text file into a string. FilePath (string) A string containing the file contents.
ReadXml Reads an XML file into a new XML document. FilePath (string) An XmlDocument object containing the XML data.
ToCsv Converts an object to a CSV string. Object (object) A string containing the CSV data.
ToJson Converts an object to a JSON string. Object (object) A string containing the JSON data.
ToXml Converts an object to an XML string. Object (object) A string containing the XML data.

Web Extension

The Nettle.Web extension provides the following functions:

Name Description Parameters Returns
HttpGet Gets a single HTTP resource as a string. URL (string), Headers (optional array of key value pair) A string representation of the HTTP resource that was returned.
HttpGetAsJson Gets a single HTTP resource as a JSON object. URL (string), Headers (optional array of key value pair) A JSON object that represents the response.
HttpGetAsXml Gets a single HTTP resource as an XML document. URL (string), Headers (optional array of key value pair) An XML document that represents the response.
HttpPost Posts a single HTTP resource to a URL. URL (string), Body (string - optional), Headers (optional array of key value pair) A string representation of the HTTP response that was returned.
HttpPostForJson Posts a single HTTP resource to a URL. URL (string), Body (string - optional), Headers (optional array of key value pair) A JSON object representing the HTTP response that was returned.
HttpPostForXml Posts a single HTTP resource to a URL. URL (string), Body (string - optional), Headers (optional array of key value pair) An XML document representing the HTTP response that was returned.

NCalc Extension

The Nettle.NCalc extension provides the following functions:

Name Description Parameters Returns
Evaluate Evaluates a single mathematical expression. Expressions support {0} placeholders that work in the same way as FormatString. Each additional parameter is merged into the expression before it is evaluated. Expression (string), Array (object) The result that was evaluated.

Disabling Functions

By default, all functions are enabled. If you want to disable one or more functions, you can do so using the compilers DisableFunction(string functionName) method. There is also a DisableAllFunctions() method if you don't want to allow any functions to be used.

Custom Functions

Custom functions can be created by implementing the IFunction interface (there is also a base class FunctionBase that contains most of the scaffolding code needed). To make new functions available to Nettle, they can either be injected when creating a new compiler instance or registered individually using the compilers RegisterFunction method.

For example:

var userFunction = new GetUserFunction();
var addressFunction = new GetUserAddressesFunction();

var compiler = NettleEngine.GetCompiler
(
	userFunction,
	addressFunction
);

// OR

var compiler = NettleEngine.GetCompiler();

compiler.RegisterFunction(userFunction);
compiler.RegisterFunction(addressFunction);

Custom Function Example

The following example builds on the FunctionBase class to implement a function that removes all the 'a' characters from a string.

public sealed class RemoveAFunction : FunctionBase
{
    public RemoveAFunction() 
        : base()
    {
        DefineRequiredParameter
        (
            "Text",
            "The text to replace",
            typeof(string)
        );
    }

    public override string Description
    {
        get
        {
            return "Removes all instances of the character 'a' from a string.";
        }
    }

    protected override object GenerateOutput
        (
            TemplateContext context,
            params object[] parameterValues
        )
    {
        Validate.IsNotNull(context);

        var text = GetParameterValue<string>
        (
            "Text",
            parameterValues
        );

        text = text.Replace("a", String.Empty);
        text = text.Replace("A", String.Empty);

        return text;
    }
}

An example usage of this function could be:

{{@RemoveA("ABC abc")}}

Which would produce the following output:

BC bc

In reality, this isn't very useful, but it demonstrates how easy it is to create a custom function. To register the function above, we could either call the Nettle compilers RegisterFunction method or create a custom resolver that is registered using NettleEngine.RegisterResolvers.

Clone this wiki locally