Category Archives: ExpressionEvaluator

Cinchoo – Command Line Argument Parser, Part 12

Inside Command Line Argument Parser – Expression Evaluator

In some cases, you may want to pass some expression as command line arguments and assign them to command line arguments. Cinchoo framework covers this requirement as well.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

Let say, you want to pass 100 + 50 as command line argument (N), you can do so as below

N:{100 + 50} /I -O:C:\Log -D:%NOW%

Expressions are given in { and } braces. Please note that the symbols needs to have spaces

Cinchoo framework looks into the {100+50} command line argument value, evaluates and assigns the outcome value to corresponding member (Count).

[ChoCommandLineArgObject(ApplicationName = "Hello World", Copyright = "Copyright (c) Cinchoo Inc.")]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("D", DefaultValue = "%NOW%", Description = "Business Date.", ShortName = "Today")]
    public DateTime Today
    {
        get;
        set;
    }

    [ChoCommandLineArg("N", DefaultValue = 100, Description = "No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue = true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutFolder
    {
        get;
        set;
    }

    [ChoDefaultCommandLineArg(IsRequired = true, Description = "Semi-colon seperated list of folders")]
    [ChoTypeConverter(typeof(ChoStringToStringArrayConverter))]
    public string[] Folders
    {
        get;
        set;
    }
}

If the application containing above type executed with the below command line arguments

N:{100+50}/I -O:C:\Log -D:%NOW%

Or

N:"{100 + 50}"/I -O:C:\Log -D:%NOW%
When creating instance of MyCommandLineArgObject as below,
MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());

And run the application, the commandLineArgObject will contain the below values

Hello World [Version 1.0.0.0]
Copyright (c) Cinchoo Inc.

-- Cinchoo.Core.CommandLineArgs.Test.MyCommandLineArgObject Dump --
Today: 1/6/2012 12:32:00 PM
Count: 150
IncludeSubDir: True
OutFolder: C:\Log

Please visit ExpressionEvaluator section for more detailed information about expressions.


Cinchoo – String.Evaluate(), Extension Method

In this section, I’ll talk about Evaluate extension method. This method used to evaluate a mathematical expression string and returns final output as object. Please see the below samples on how to use it.

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace System

Sample:

static void Main(string[] args)
{
    //Numeric expression
    Console.WriteLine("Output of {100 + 20}: " + "{100 + 20}".Evaluate());
    Console.WriteLine("Output of {100 + 20 * 2 + 10}: " + "{100 + 20 * 2 + 10}".Evaluate());
    Console.WriteLine("Output of {100 + 20 * (2 + 10)}: " + "{100 + 20 * (2 + 10)}".Evaluate());
    Console.WriteLine("Output of {100.05 + 10.05}: " + "{100.05 + 10.05}".Evaluate());
    Console.WriteLine();

    //String expression
    Console.WriteLine("Output of {'First ' + 'Second'}: " + "{'First ' + 'Second'}".Evaluate());
    Console.WriteLine();

    //Expression contains properties
    Console.WriteLine("Output of {'%APPLICATION_NAME%'}: " + "{'%APPLICATION_NAME%'}".Evaluate());
    Console.WriteLine("Output of {'%NOW%'}: " + "{'%NOW%'}".Evaluate());
    Console.WriteLine("Output of {'%TODAY%'}: " + "{'%TODAY%'}".Evaluate());
    Console.WriteLine();
}

When you run the above code, the output will be

Output of {100 + 20}: 120
Output of {100 + 20 * 2 + 10}: 150
Output of {100 + 20 * (2 + 10)}: 340
Output of {100.05 + 10.05}: 110.1

Output of {'First ' + 'Second'}: First Second

Output of {'%APPLICATION_NAME%'}: Cinchoo.Core.ExpressionEvaluator.Test.exe
Output of {'%NOW%'}: 4:43 PM
Output of {'%TODAY%'}: 1/11/2012

Press any key to continue . . .

Happy coding!!!

PS: Please refer Property Replacer section for information about available properties and defining custom properties.



Cinchoo – String.ExpandProperties(), Extension Method

In this section, I’ll talk about ExpandProperties extension method. This method used to find and replace any system / user defined properties found in a string. Properties are string begins and ends in separatorPlease see the below samples on how to use it. This routine returns string value.

Sample Properties are

%APPLICATION_NAME%
%TODAY%

How to use

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace System

Sample:

static void Main(string[] args)
{
    //Simple property expansion
    Console.WriteLine("Output of '%%APPLICATION_NAME%%' property: %APPLICATION_NAME%".ExpandProperties());
    Console.WriteLine("Output of '%%TODAY%%' property: %TODAY%".ExpandProperties());
    Console.WriteLine("Output of '%%PROCESSOR_COUNT%%' property: %PROCESSOR_COUNT%".ExpandProperties());

    Console.WriteLine();

    //String containing properties
    Console.WriteLine("This machine has %PROCESSOR_COUNT% processors.".ExpandProperties());
}

When you run the above code, the output will be

Output of 'APPLICATION_NAME' property: Cinchoo.Core.Test.exe
Output of 'TODAY' property: 2/16/2012
Output of 'PROCESSOR_COUNT' property: 2

This machine has 2 processors.

Press any key to continue . . .

Formatting Property Value

Some cases, you may want to format the property value. It can be done by passing format specification along with property name. Property Name and format specification are separated by ^ character. All .NET specific format specifiers are valid.

PS: Please refer Formatting Types from MSDN for more information about format specifiers used in .NET

%PROPERTY_NAME^FORMAT_STRING%

Sample:

static void Main(string[] args)
{
    //Formatted property expansion
    Console.WriteLine("Output of %%TODAY^yyyyMMdd%% property: %TODAY^yyyyMMdd%".ExpandProperties());
    Console.WriteLine("Output of %%PROCESSOR_COUNT^#,#.00#;(#,#.00#)%% property: %PROCESSOR_COUNT^#,#.00#;(#,#.00#)%".ExpandProperties());
    Console.WriteLine("Output of %%RANDOM_NO^C%% property: %RANDOM_NO^C%".ExpandProperties());
}

When you run the above code, the output will be

Output of TODAY^yyyyMMdd property: 20120216
Output of PROCESSOR_COUNT^#,#.00#;(#,#.00#) property: 2.00
Output of RANDOM_NO^C property: ($92,640,205.00)

Press any key to continue . . .

Handling of Unknown Property

Cinchoo framework gracefully skips any unknown properties specified in the input string. Look below the sample

Sample:

static void Main(string[] args)
{
    Console.WriteLine("Output of %%UNKNOWN_PROPERTY^C%% property: %UNKNOWN_PROPERTY^C%".ExpandProperties());
}

When you run the above code, the output will be

Output of UNKNOWN_PROPERTY^C property: %UNKNOWN_PROPERTY^C%

Press any key to continue . . .

How to resolve Unknown Property

Cinchoo framework provides a event handler to resolve any unknown properties failed to resolve. The event is exposed in ChoApplication.PropertyResolve event. Look at the sample below on how to handle this situation

Sample:

static void Main(string[] args)
{
    //Hook up the event handler
    ChoApplication.PropertyResolve += new EventHandler<Property.ChoUnknownProperyEventArgs>(PropertyResolve);

    Console.WriteLine("Output of %%UNKNOWN_PROPERTY^C%% property: %UNKNOWN_PROPERTY^C%".ExpandProperties());
}

//Event handler
private static void PropertyResolve(object sender, Property.ChoUnknownProperyEventArgs e)
{
    if (e.PropertyName == "UNKNOWN_PROPERTY")
    {
        e.PropertyValue = null;
        e.Resolved = true;
    }
}

When you run the above code, the output will be

Output of UNKNOWN_PROPERTY^C property: RESOLVED_VALUE

Press any key to continue . . .

Try it out! Happy coding!!!


Cinchoo – String.ExpandProperties(), Part 2

Here I’ll show you how you can mix expressions and properties together and resolving the input string.

ExpandProperties will do the expression evaluation along with property replacement in a string. Please see the below samples on how to use it. Expressions are given with { and } delimiters.

How to use

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace System

Sample:

static void Main(string[] args)
{
    Console.WriteLine("Output of %%PROCESSOR_COUNT%% : {%PROCESSOR_COUNT% * 2}".ExpandProperties());
    Console.WriteLine("Output of {{%%TICK_COUNT%% / (60 * 60)}} : {%TICK_COUNT% / (60 * 60)}".ExpandProperties());
    Console.WriteLine(@"Output of {{'%%SYSTEM_DIRECTORY%%' + '\Logs'}} : {'%SYSTEM_DIRECTORY%' + '\Logs'}".ExpandProperties());
}

In the above sample code, all the properties are resolved before expressions evaluated.

When you run the above code, the output will be

Output of PROCESSOR_COUNT : 4
Output of {TICK_COUNT / (60 * 60)} : -393593
Output of {'SYSTEM_DIRECTORY' + '\Logs'} : C:\WINNT\system32\Logs

Press any key to continue . . .

Try it out! Happy coding!!!


Cinchoo – String.Evaluate(), Part 2

Using system library routines

In some cases, you may want to use system library routines while evaluating expression. Library routines are specified with ~ delimiter. When specifying library routine, please give full namespace type name.

Please see the sample below

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace System

Sample:

static void Main(string[] args)
{
    try
    {
        object x1 = "{~System.DateTime.Now.Ticks~ * 10}".Evaluate();
        Console.WriteLine("Output of {~System.DateTime.Now.Ticks~ * 10}: " + x1 + ", ObjectType:" + x1.GetType());

        object x2 = "{2 + ~System.Math.Sin(10)~ * 10}".Evaluate();
        Console.WriteLine("Output of {2 + ~Math.Sin(10)~ * 10}: " + x2 + ", ObjectType:" + x2.GetType());
    }
    finally
    {
        ChoAppDomain.Exit();
    }
}

When you run the above code, the output will be

Output of {~System.DateTime.Now.Ticks~ * 10}: 6346500617481320790, ObjectType: System.Int64
Output of {2 + ~Math.Sin(10)~ * 10}: -3.4402111088937, ObjectType: System.Double

Press any key to continue . . .

Happy coding!!!



Cinchoo – String.Evaluate(), Part 3

Using custom library routines

You may ask, how to use my own custom routines while evaluating expressions? Here I’m will show you how. All you need to do is to write the routine, reference it to the current project if it was in separate assembly.

Please see the sample below

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace System

Sample:

namespace Cinchoo.Core.Test
{
    public class Utilities
    {
        public static int Sqrt(int x)
        {
            return x * x;
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            try
            {
                object x1 = "{~Cinchoo.Core.Test.Utilities.Sqrt(10)~ * 10}".Evaluate();
                Console.WriteLine("Output of {~Cinchoo.Core.Test.Utilities.Sqrt(10)~ * 10}: " + x1 + ", ObjectType:" + x1.GetType());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                ChoFramework.Shutdown();
            }
        }
    }
}

When you run the above code, the output will be

Output of {~Cinchoo.Core.Test.Utilities.Sqrt(10)~ * 10}: 1000, ObjectType:System.Int32

Press any key to continue . . .

Happy coding!!!



Follow

Get every new post delivered to your Inbox.