Tag Archives: console

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