Tag Archives: Shell

Cinchoo – Read from console with timeout

You have a console application in which you want to give the user number of seconds to respond to the prompt. If no input is made after a certain period of time, program should continue.

Cinchoo framework provides this through ChoConsole class.

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace Cinchoo.Core.Shell.Console

Below are the following methods

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(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(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(int timeoutInMilliSeconds);
public static ConsoleKeyInfo ReadKey(int timeoutInMilliSeconds, int? defaultValue);
public static ConsoleKeyInfo ReadKey(int timeoutInMilliSeconds, int? defaultValue, string errMsg)
Advertisements

Cinchoo – ChoConsolePercentageProgressorEx

Cinchoo framework provides another elegant console progress bar indicator to perform lengthy operation in the console application. The feature is very useful when you want to give a visual indicator of how a task is performing.

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace Cinchoo.Core.Shell.Console

Below is the sample code

using (ChoConsolePercentageProgressorEx cp = new ChoConsolePercentageProgressorEx("Calculating..."))
{
    cp.ErrorOccured += (sender, eventArg) => cp.Write(eventArg.Exception.Message);

    cp.Start((sender, runningPercentage, state) =>
    {
        Thread.Sleep(1000);
        if (runningPercentage == cp.MinPercentage)
            return new Tuple<int, string>(10, "Step 1 - Status Msg");

        switch (runningPercentage)
        {
            case 10:
                //Do the custom operation here
                return new Tuple<int, string>(25, "Step 2 - Status Msg");
            case 25:
                //Do the custom operation here
                return new Tuple<int, string>(90, "Step 3 - Status Msg");
            default:
                //Do the custom operation here
                return new Tuple<int, string>(cp.MaxPercentage, "Complete");
        }
    }
    );
}

When you run the above code, you can see the below output

For any exception occurred during the operation, can be captured by subscribing to ErrorOccured event.

cp.ErrorOccured += (sender, eventArg) => Console.WriteLine(eventArg.Exception.ToString());

The custom operation can be terminated in couple of ways

1. Stop() – Graceful termination

2. Abort() – Abnormal termination

Happy coding!!!

Cinchoo – ChoConsoleSpinProgressor

Using Cinchoo framework, you can perform lengthy operation with the spin progress indicator in the console window. The feature is very useful when you want to give a visual indicator of how a task is performing.

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace Cinchoo.Core.Shell.Console

Below is the sample code

int x = 0;
using (ChoConsoleSpinProgressor cp = new ChoConsoleSpinProgressor("Calculating...", ConsoleColor.Red))
{
    cp.ErrorOccured += (sender, eventArg) => cp.Write(eventArg.Exception.Message);
    cp.Start((sender, state) =>
        {
            cp.ConsoleSession.WriteLine("Processing Step" + x++);
            Thread.Sleep(1000);

            if (x > 5)
                return false; //To indicate the completion of the operation
            else
                return true; //To indicate continuation of the operation
        }
    );
}

When you run the above code, you can see the below output

For any exception occurred during the operation, can be captured by subscribing to ErrorOccured event.

cp.ErrorOccured += (sender, eventArg) => ((ChoConsoleSpinProgressor)sender).Write(eventArg.Exception.Message);

The custom operation can be terminated in couple of ways

1. Stop() – Graceful termination

2. Abort() – Abnormal termination

Happy coding!!!

Cinchoo – ChoConsolePercentageProgressor

Using Cinchoo framework, you can perform lengthy operation with the percentage progress indicator in the console window. The feature is very useful when you want to give a visual indicator of how a task is performing.

1. Add reference to Cinchoo.Core.dll assembly

2. Namespace Cinchoo.Core.Shell.Console

Below is the sample code

using (ChoConsolePercentageProgressor cp = new ChoConsolePercentageProgressor("Calculating...", ConsoleColor.Green))
{
    cp.ErrorOccured += (sender, eventArg) => cp.Write(eventArg.Exception.Message);

    cp.Start((sender, runningPercentage, state) =>
        {
            cp.Write("Completed: " + runningPercentage);
            switch (runningPercentage)
            {
                case 0:
                    //Do the custom operation here
                    return 10;
                case 10:
                    //Do the custom operation here
                    return 25;
                case 25:
                    //Do the custom operation here
                    return 90;
                default:
                    //Do the custom operation here
                    return cp.MaxPercentage;
            }
        }
    );
}

When you run the above code, you can see the below output

For any exception occurred during the operation, can be captured by subscribing to ErrorOccured event.

cp.ErrorOccured += (sender, eventArg) => ((ChoConsolePercentageProgressor)sender).Write(eventArg.Exception.Message);

The custom operation can be terminated in couple of ways

1. Stop() – Graceful termination

2. Abort() – Abnormal termination

Happy coding!!!

Cinchoo – Read password from console

Introduction

Cinchoo is the application framework for .NET. It largely includes large class libraries and provides many features like Configuration Management, Generic Application Host, CommandLine argument parser, useful utility classes etc.

In this article, I’m going to talk about reading password from console. Rarely we do develop console applications that would take inputs from console window. In some situations you may want to accept some secure inputs from console window. Cinchoo library provides a API to take such input from console.

Download the Latest Cinchoo Binary here. (Nuget Command: Install-Package Cinchoo)

Using the code

Cinchoo exposes couple of API methods to read password or secure input from console window, It is exposed in ChoConsole class under Cinchoo.Core.Shell namespace

public static SecureString ReadSecurePassword(char maskChar = '*', int maxLength = Int32.MaxValue, Func<char, bool> filter = null, int timeoutInMilliSeconds = -1)

public static string ReadPassword(char maskChar = '*', int maxLength = Int32.MaxValue, Func<char, bool> filter = null, int timeoutInMilliSeconds = -1)

where

  • maskChar – Masked character.
  • maxLength – Maximum number of characters the user can type in.
  • filter – Optional callback method to filter any characters from accepting in the password.
  • timeoutInMilliSeconds – The number of milliseconds to wait before the method times out.

First method, returns SecureString, It represents text that should be kept confidential, such as by deleting it from computer memory when no longer needed. Most of .NET api not accepting SecureString as passwords. This method is recommended.

Second method, simply returns the password as string object. It is claimed to be insecure to keep the password in standard string object.

Sample #1

Below sample, read the password from console as string object with ‘*’ as masked character, maxlength of 10 chars. Besides it limits the password from accepting ‘A’ or ‘R’ characters.

class Program
{
    static void Main(string[] args)
    {
        //Read password from console as string
        Console.WriteLine(ChoConsole.ReadPassword('*', 10, (c) => c == 'A' || c == 'R'));
    }
}

Sample #2

Below sample, read the password from console as SecureString object with ‘^’ as masked character, maxlength of 10 chars. Besides it limits the password from accepting ‘A’ or ‘R’ characters with the timeout of 5 secs.

class Program
{
    static void Main(string[] args)
    { 
        //Read password from console as SecureString
        SecureString x = ChoConsole.ReadSecurePassword('^', 10, (c) => c == 'A' || c == 'R', 5000);

        //For testing purpose, I'm using this utility class to reveal the content of the SecureString. 
        //In real-world, you should avoid it.
        ChoInsecureString z = new ChoInsecureString(x);
        foreach (var c in z)
            Console.Write(c);
    }
}

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 – Command Line Argument Parser, Part 14

Inside Command Line Argument Parser – Automatic Help

Another feature that Cinchoo framework provides you is that, it automatically creates Usage help text.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

For a sample Command Line object below,

[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+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;
    }
}

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

/help or /? or /h

When creating instance of MyCommandLineArgObject as below,

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());

And run the application, the commandLineArgObject will display the usage as below

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

Cinchoo.Core.CommandLineArgs.Test.exe -D:Today -N:<int> -I:{True|False} -O:[<string>]

Where
        -D      Business Date.
        -N      No of spaces for a TAB.
        -I      Include Sub directory.
        -O      Output Directory.

Cinchoo – Command Line Argument Parser, Part 13

Inside Command Line Argument Parser – Load from file

In some cases, if you have multiple large, complex sets of command-line arguments that you want to run multiple times, Cinchoo framework provides a way to load the command line arguments from a file.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

Let say you create a file c:\CmdLine.txt with the below command line arguments

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

Sample Command Line object below,

[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;
    }
}

If the application containing above type executed with the below command line arguments (Please note, the file is been passed with @ symbol.)

@"C:\CmdLine.txt"

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

Cinchoo – Property Replacer, Part 1

Customizing Property Replacer – Static Properties

If you need that you need to define and use list of your own properties for your requirements, you can do so by adding <key, value> pair to ChoStaticDictionaryPropertyReplacer class. There values are static, will not be evaluated for each time.  Cinchoo framework will take these values for property replacement in various places like Command Line parsing, Configuration Management, Object.ToString() etc.

Example, add CLUSTER_NAME property at the start of the application as below

ChoStaticDictionaryPropertyReplacer.Me.Add("CLUSTER_NAME", "CNYC100123023");

Then, you can use that property by using the below code

string msg = "Cluster Name is %CLUSTER_NAME%";
Console.WriteLine(ChoString.ExpandProperties(msg));

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

Cluster Name is CNYC100123023

Cinchoo – Command Line Argument Parser, Part 11

Inside Command Line Argument Parser – Available Properties

In here I’ll list all the available properties in Cinchoo framework.

Properties can be specified with % delimiters as below

%NOW%

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

Cinchoo framework allows you to pass property as command line argument. At run time, the framework replaces with property value.

Global Properties

Below are the list of global properties available for use as command line arguments

  • %APPLICATION_NAME% – Application Name.
  • %PROCESS_ID% – Process Identifier.
  • %THREAD_ID% – Thread Identifier.
  • %THREAD_NAME% – Managed .NET Thread Name, if any.
  • %RANDOM_NO% – Random integer value.
  • %TODAY% – Current Date.
  • %NOW% – The current date and time on this computer, expressed as the local time.

Environment Properties

Below are the list of Environment properties available for use as command line arguments

  • %CURRENT_DIRECTORY% – The fully qualified path of the current directory; that is, the directory from which this process starts.
  • %MACHINE_NAME% – The NetBIOS name of this local computer
  • %OS_VERSION% – An OperatingSystem object that contains the current platform identifier and version number.
  • %PROCESSOR_COUNT% – The number of processors on the current machine.
  • %SYSTEM_DIRECTORY% – The fully qualified path of the system directory.
  • %SYSTEM_PAGE_SIZE% – The amount of memory for an operating system’s page file.
  • %TICK_COUNT% – The number of milliseconds elapsed since the system started.
  • %USER_DOMAIN_NAME% – The network domain name associated with the current user.
  • %USER_NAME% – The user name of the person who is currently logged on to the Windows operating system.
  • %VERSION% – A Version object that describes the major, minor, build, and revision numbers of the common language runtime.
  • %WORKING_SET% – The amount of physical memory mapped to the process context.

Please visit PropertyReplacer section for more information about Property re-placers.