Monthly Archives: January 2012

Cinchoo – ChoConsole, Part 1

Cinchoo framework provides one another helper class, ChoConsole. It is a static class, exposes lot of methods to help to build Console application.

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace Cinchoo.Core.Shell.Console

Below are the following methods

Write() Overloads:

This class provides various Write methods to write values to application console window. Here I’m going to walk over one set of Write methods,

public static void Write(string msg);
public static void Write(string msg, ConsoleColor foregroundColor);
public static void Write(string msg, ConsoleColor foregroundColor, ConsoleColor backgroundColor);
public static void Write(string msg, ChoPoint cursorLocation);
public static void Write(string msg, ChoPoint cursorLocation, ConsoleColor foregroundColor, ConsoleColor backgroundColor);
public static void Write(string msg, int cursorLeft, int cursorTop);
public static void Write(string msg, int cursorLeft, int cursorTop, ConsoleColor foregroundColor, ConsoleColor backgroundColor);

There are number other Write overloads to handle other datatype variables (int, long, char etc). Please explore yourself.

WriteLine() Overloads:

This class provides various WriteLine methods to write values followed by NewLine to application console window. Here I’m going to walk over one set of WriteLine methods,

public static void WriteLine(string msg);
public static void WriteLine(string msg, ConsoleColor foregroundColor);
public static void WriteLine(string msg, ConsoleColor foregroundColor, ConsoleColor backgroundColor);
public static void WriteLine(string msg, ChoPoint cursorLocation);
public static void WriteLine(string msg, ChoPoint cursorLocation, ConsoleColor foregroundColor, ConsoleColor backgroundColor);
public static void WriteLine(string msg, int cursorLeft, int cursorTop);
public static void WriteLine(string msg, int cursorLeft, int cursorTop, ConsoleColor foregroundColor, ConsoleColor backgroundColor);

There are number other WriteLine overloads to handle other datatype variables (int, long, char etc). Please explore yourself.

Pause() Overloads:

This method writes the default/specified string value to the standard output stream. Reads the next character from the standard input stream.

public static void Pause();
public static void Pause(string msg);

PauseLine() Overloads:

This method writes the default/specified string value, followed by the current line terminator,  to the standard output stream. Reads the next character from the standard input stream.

public static void PauseLine();
public static void PauseLine(string msg);

Read() Overloads:

This method reads the next character from the standard input stream either within the specified timeout period or infinity.

public static int Read();
public static int Read(int timeoutInMilliSeconds);
public static int Read(int timeoutInMilliSeconds, int? defaultValue);
public static int Read(int timeoutInMilliSeconds, int? defaultValue, string errMsg)

ReadLine() Overloads:

This method reads the next line of characters from the standard input stream either within the specified timeout period or infinity.

public static int ReadLine();
public static int ReadLine(int timeoutInMilliSeconds);
public static int ReadLine(int timeoutInMilliSeconds, int? defaultValue);
public static int ReadLine(int timeoutInMilliSeconds, int? defaultValue, string errMsg)

ReadKey() Overloads:

This method reads the next character from the standard input stream either within the specified timeout period or infinity.

public static ConsoleKeyInfo ReadKey();
public static ConsoleKeyInfo ReadKey(int timeoutInMilliSeconds);
public static ConsoleKeyInfo ReadKey(int timeoutInMilliSeconds, int? defaultValue);
public static ConsoleKeyInfo ReadKey(int timeoutInMilliSeconds, int? defaultValue, string errMsg)

ReadPassword() Overloads:

This method reads the next line of characters from the standard input stream. Typed characters will be masked with maskChar in the console window.

public static string ReadPassword();
public static string ReadPassword(int maxLength);
public static string ReadPassword(char maskChar, int maxLength);

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!!!


Cinchoo – Nested Xml files

ChoXmlDocument

.NET provides standard XmlDocument object that represents a XML document. But lacks to support multiple sub documents inside a Xml document. Cinchoo addresses this feature through ChoXmlDocument class, where you can specify multiple nested Xml files. It provides an opportunities to break a large Xml document into small manageable sub-documents.

For a sample Xml document as below

<?xml version="1.0" encoding="utf-8" ?>
<employees>
 <employee name="Top-Tom" state="NY" />
 <employee name="Include1-Mark" state="NM" />
 <employee name="Include11-Tom" state="MD" />
 <employee name="Include1-Tom" state="AZ" />
 <employee name="Top-Mark" state="NJ" />
</employees>

I’m going to break them down to 3 xml files as below (just for illustrative purpose)

1. XmlTop.xml

<?xml version="1.0" encoding="utf-8" ?>
<employees xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework">
 <employee name="Top-Tom" state="NY" />
 <cinchoo:include path="XmlIncludeFile1.xml" />
 <employee name="Top-Mark" state="NJ" />
</employees>

2. XmlIncludeFile1.xml

<?xml version="1.0" encoding="utf-8" ?>
<employee name="Include1-Mark" state="NM" />
<cinchoo:include xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework" path="XmlIncludeFile11.xml" />
<employee name="Include1-Tom" state="AZ" />

3. XmlIncludeFile11.xml

<?xml version="1.0" encoding="utf-8" ?>
<employee name="Include11-Tom" state="MD" />

How to load and use the document

1. Add reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Xml

using (ChoXmlDocument xmlDocument = new ChoXmlDocument("C:\XmlTop.xml"))
{
    Console.WriteLine(ChoXmlDocument.IndentXMLString(xmlDocument.XmlDocument.OuterXml));
}

Output of the above code would be

<?xml version="1.0" encoding="utf-8"?>
<employees xmlns:cinchoo="http://schemas.cinchoo.com/cinchoo/01/framework">
 <employee name="Top-Tom" state="NY" />
 <!--DO NOT REMOVE - BEGIN INCLUDE C:\XmlIncludeFile1.xml-->
 <employee name="Include1-Mark" state="NM" />
 <!--DO NOT REMOVE - BEGIN INCLUDE C:\XmlIncludeFile11.xml-->
 <employee name="Include11-Tom" state="MD" />
 <!--DO NOT REMOVE - END INCLUDE C:\XmlIncludeFile11.xml-->
 <employee name="Include1-Tom" state="AZ" />
 <!--DO NOT REMOVE - END INCLUDE C:\XmlIncludeFile1.xml-->
 <employee name="Top-Mark" state="NJ" />
</employees>

Or you can use the XmlDocument object exposed as member from ChoXmlDocument object to do other operation on the document.


Cinchoo – Property Replacer, Part 2

Customizing Property Replacer – Dynamic Properties

We have learnt about defining and using static property in the previous section. In this section, I’m going to talk about defining and using Dynamic properties in your application. Dynamic properties are properties their values are resolved at the time of calling.

Below is the sample Property Replacer,

public class ChoDynamicPropertyReplacer : IChoKeyValuePropertyReplacer
{
    #region Instance Data Members

    private readonly Dictionary<string, string> _availPropeties = new Dictionary<string, string>()
        {
            { "HOME_PAGE", "Cinchoo framework website." },
            { "LAST_VISIT", "The last visit to the home page." }
        };

    #endregion Instance Data Members

    #region IChoKeyValuePropertyReplacer Members

    //Called by framework to see it is valid property replacer for the passed propertyName
    public bool ContainsProperty(string propertyName)
    {
        return _availPropeties.ContainsKey(propertyName);
    }

    //Yes it is, then framework calls this method to find the value for the property
    public string ReplaceProperty(string propertyName, string format)
    {
        switch (propertyName)
        {
            case "HOME_PAGE":
                return "http://www.cinchoo.com";
            case "LAST_VISIT":
                return ChoObject.Format(DateTime.Now, format);
            default:
                return null;
        }
    }

    //This method will be used to generate help
    public string GetPropertyDescription(string propertyName)
    {
        if (_availPropeties.ContainsKey(propertyName))
            return _availPropeties[propertyName];
        else
            return null;
    }

    #endregion

    #region IChoPropertyReplacer Members

    //Name of the property replacer
    public string Name
    {
        get { return "Dynamice Property Replacer"; }
    }

    //This property used to get list of supported properties and their descriptions
    public IEnumerable<KeyValuePair<string, string>> AvailablePropeties
    {
        get
        {
            foreach (KeyValuePair<string, string> keyValue in _availPropeties)
                yield return keyValue;
        }
    }

    #endregion
}

Here is the code to plug-in the above property replacer to the framework and using it.

static void Main(string[] args)
{
    ChoPropertyManagerSettings.Me.Add(new ChoDynamicPropertyReplacer());

    Console.WriteLine("Output of %%HOME_PAGE%% : %HOME_PAGE%".ExpandProperties());
    Console.WriteLine("Output of %%LAST_VISIT%% : %LAST_VISIT%".ExpandProperties());

    return;
}

When you run the above statements in an application, the output will be

Output of HOME_PAGE : http://www.cinchoo.com
Output of LAST_VISIT : 1/17/2012 1:07:23 PM

Hope this helps.


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.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.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.



Follow

Get every new post delivered to your Inbox.