Category Archives: String

Cinchoo – Delegate.WaitFor(), Extension Method

Here I’ll talk about WaitFor extension method. This extension method used to run a method with finite number of retries if it failed to run at first time and/or in a finite time frame. It provides most of Action and Func delgates overloads.

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace Cinchoo.Core

Sample 1:

Below are the list of overloads for Func<T> delegate, Cinchoo provides these overloads almost all the Func’s and Action’s.

public static TResult WaitFor(this Func func);
public static TResult WaitFor(this Func func, int timeout);
public static TResult WaitFor(this Func func, int timeout, int maxNoOfRetry);
public static TResult WaitFor(this Func func, int timeout, int maxNoOfRetry, int sleepBetweenRetry);

Below sample shows you how to run a  Func<T> delegate method using WaitFor() extension method.

class Program
{
    static void Main(string[] args)
    {
		Func f1 = () =>
			{
				System.Threading.Thread.Sleep(1);
                Console.WriteLine("Running method...");
				return 1;
			};

        Console.WriteLine("Output: {0}".FormatString(f1.WaitFor()));
	}
}

When you run the above code, the output will be

Running method...
Output: 1
Press any key to continue . . .

Sample 2:

In this example, I’ll show you the way of invoking a method with timeout (1000ms) parameter. It throws a timeout exception, as the method takes more time to execute than timeout (1000 ms) period.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Func f1 = () =>
                {
                    System.Threading.Thread.Sleep(5000);
                    Console.WriteLine("Running method...");
                    return 1;
                };

            Console.WriteLine("Output: {0}".FormatString(f1.WaitFor(1000)));
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: {0}".FormatString(ex.Message));
        }
	}
}

When you run the above code, the output will be

Error: Timeout [1000 ms] elapsed prior to completion of the method [Target: , Metho
d: Int32 b__0()].
Press any key to continue . . .

Sample 3:

In here, we will see how a method with an error is executed for number of times with one of the WaitFor overload.

static void Main(string[] args)
{
    try
    {
        Func<int> f1 = () =>
            {
                System.Threading.Thread.Sleep(10);
                throw new ApplicationException("Communication error.");
            };

        Console.WriteLine("Output: {0}".FormatString(f1.WaitFor(Timeout.Infinite, 3)));
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: {0}".FormatString(ex.Message));
    }
}

When you run the above code, the output will be

Error: Exception(s) occurred : The method failed to execute after 3 retries..
[ System.ApplicationException: Communication error.
   at Cinchoo.Core.ChoWaitForTest.Program.<Main>b__0() in C:\Personal\Cinchoo.Fr
amwork\Cinchoo.Core.Test\Cinchoo.Core.ChoWaitFor.Test\Program.cs:line 18
   at Cinchoo.Core.ChoWaitFor.WaitFor[TResult](Func`1 func, Int32 timeout, Int32
 maxNoOfRetry, Int32 sleepBetweenRetry) in C:\Personal\Cinchoo.Framwork\Cinchoo.
Framework\Cinchoo.Core\WaitFor\ChoWaitFor.cs:line 148 ]

[ System.ApplicationException: Communication error.
   at Cinchoo.Core.ChoWaitForTest.Program.<Main>b__0() in C:\Personal\Cinchoo.Fr
amwork\Cinchoo.Core.Test\Cinchoo.Core.ChoWaitFor.Test\Program.cs:line 18
   at Cinchoo.Core.ChoWaitFor.WaitFor[TResult](Func`1 func, Int32 timeout, Int32
 maxNoOfRetry, Int32 sleepBetweenRetry) in C:\Personal\Cinchoo.Framwork\Cinchoo.
Framework\Cinchoo.Core\WaitFor\ChoWaitFor.cs:line 148 ]

[ System.ApplicationException: Communication error.
   at Cinchoo.Core.ChoWaitForTest.Program.<Main>b__0() in C:\Personal\Cinchoo.Fr
amwork\Cinchoo.Core.Test\Cinchoo.Core.ChoWaitFor.Test\Program.cs:line 18
   at Cinchoo.Core.ChoWaitFor.WaitFor[TResult](Func`1 func, Int32 timeout, Int32
 maxNoOfRetry, Int32 sleepBetweenRetry) in C:\Personal\Cinchoo.Framwork\Cinchoo.
Framework\Cinchoo.Core\WaitFor\ChoWaitFor.cs:line 148 ]
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!!!



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.Unindent(), Extension Method

In this section, I’ll talk about Unindent extension method. This method used to find and remove the padding characters from input text. Please see the below samples on how to use it.

1. Add reference to Cinchoo.Core.ExtensionMethods.dll assembly

2. Namespace System

Sample:

static void Main(string[] args)
{
    string msg = "\tHello World!{0}\tWelcome to Cinchoo.com".FormatString(Environment.NewLine);

    Console.WriteLine("Before Unindent:");
    Console.WriteLine(msg);
    Console.WriteLine();

    Console.WriteLine("After Unindent:");
    Console.WriteLine(msg.Unindent());
}

When you run the above code, the output will be

Before Unindent:
        Hello World!
        Welcome to Cinchoo.com

After Unindent:
Hello World!
Welcome to Cinchoo.com
Press any key to continue . . .

Unindent() method has several overloads, they are

//Unindent with 1 tab char
Unindent();
//Unindent with 'totalWidth' number of tab chars
Unindent(int totalWidth);
//Unindent with 'totalWidth' number of paddingChars
Unindent(int totalWidth, char paddingChar);

PS: totalWidth should be positive. In case if you pass negative value, this routine will invoke Indent() method to add any leading pad characters from each line of input text.

Happy coding!!!


Cinchoo – Enum.ToDescription(), Extension Method

In this section, I’ll talk about ToDescription<T> extension method. This method used get enum description from enum value.

1. Add reference to Cinchoo.Core.ExtensionMethods.dll assembly

2. Namespace System

Sample:

public enum Color
{
    [Description("Red Color")]
    Red,
    [Description("Green Color")]
    Green,
    [Description("Yellow Color")]
    Yellow
}

static void Main(string[] args)
{
    Console.Write("Description of 'Color.Green' enum value is: ");
    Console.WriteLine(Color.Green.ToDescription());
}

When you run the above code, the output will be

Description of 'Color.Green' enum value is: Green Color
Press any key to continue . . .

Happy coding!!!


Cinchoo – String.ToEnum(), Extension Method

In this section, I’ll talk about ToEnum<T> extension method. This method used get enum value from enum description.

1. Add reference to Cinchoo.Core.ExtensionMethods.dll assembly

2. Namespace System

Sample:

public enum Color
{
    [Description("Red Color")]
    Red,
    [Description("Green Color")]
    Green,
    [Description("Yellow Color")]
    Yellow
}

static void Main(string[] args)
{
    Console.Write("Enum value for 'RED Color' is: ");
    Console.WriteLine("RED Color".ToEnum<Color>());
}

When you run the above code, the output will be

Enum value for 'RED Color' is: Red
Press any key to continue . . .

Happy coding!!!


Cinchoo – String.Indent(), Extension Method

In this section, I’ll talk about Indent extension method. This method used to indent a string with the padding characters. Please see the below samples on how to use it.

1. Add reference to Cinchoo.Core.ExtensionMethods.dll assembly

2. Namespace System

Sample:

static void Main(string[] args)
{
    string msg = "Hello World!{0}Welcome to Cinchoo.com".FormatString(Environment.NewLine);

    Console.WriteLine("Before Indent:");
    Console.WriteLine(msg);
    Console.WriteLine();

    Console.WriteLine("After Indent:");
    Console.WriteLine(msg.Indent());
}

When you run the above code, the output will be

Before Indent:
Hello World!
Welcome to Cinchoo.com

After Indent:
        Hello World!
        Welcome to Cinchoo.com

Press any key to continue . . .

Indent() method has several overloads, they are

//Indent with 1 tab char
Indent();
//Indent with 'totalWidth' number of tab chars
Indent(int totalWidth);
//Indent with 'totalWidth' number of paddingChars
Indent(int totalWidth, char paddingChar);

PS: totalWidth should be positive. In case if you pass negative value, this routine will invoke Unindent() method to remove any leading pad characters from each line of input text.

Happy coding!!!


Follow

Get every new post delivered to your Inbox.