Пример #1
0
        }           // private static Dictionary<char , string> CreateSwitchListWithDefaults method

        private static void DisplayParsedArgs(
            string pstrTestLabel,
            CmdLneArgsBasic pCmdLineArgs,
            ref int pintTestNumber)
        {
            const string EXERCISE_TPL_BEGIN = @"Test {0}: Exercising A CmdLneArgsBasic object with the following capabilities: {1}{2}";
            const string EXERCISE_TPL_END   = @"{1}Finished exercising CmdLneArgsBasic object {0}{1}";

            Console.WriteLine(
                EXERCISE_TPL_BEGIN,                         // Format string (template)
                ++pintTestNumber,                           // Substituted for token 0
                pstrTestLabel,                              // Substituted for token 1
                Environment.NewLine);                       // Substituted for token 2

            DisplayReadOnlyProperties(pCmdLineArgs);
            EmumerateDefinedSwitches(
                pCmdLineArgs,
                s_achrSwitchSetAllUC);
            EnumerateDefinedNamedArguments(
                pCmdLineArgs,
                s_astrValidArgumentNames);
            EnumeratePositionalArgs(pCmdLineArgs);

            Console.WriteLine(        // Format string (template)
                EXERCISE_TPL_END,     // Substituted for token 0
                pCmdLineArgs,         // Substituted for token 1
                Environment.NewLine); // Substituted for token 2
        }                             // private static void DisplayParsedArgs method
Пример #2
0
        }   // private static void ExitWithError


        private static OutputFormat SetOutputFormat (
            CmdLneArgsBasic pcmdArgs ,
            ref string pstrDeferredMessage )
        {
            //  ----------------------------------------------------------------
            //  An invalid input value elicits a message similar to the following.
            //
            //      Requested value 'Foolish' was not found.
            //
            //  The simplest way to report an invalid value is by extracting it
            //  from the Message property of the ArgumentException thrown by the
            //  Enum.Parse method.
            //
            //  I happen to have a library routine, ExtractBoundedSubstrings,
            //  which became part of a sealed class, WizardWrx.StringTricks,
            //  exported by class library WizardWrx.SharedUtl2.dll version 2.62,
            //  which came into being exactly two years ago, 2011/11/23.
            //
            //	2016/06/10 - DAG - Though I have retired WizardWrx.SharedUtl2,
            //	                   StringTricks went into WizardWrx.DLLServices,
            //                     as did everything that was worth saving.
            //  ----------------------------------------------------------------

            const bool IGNORE_CASE = true;
            const int NONE = 0;

            OutputFormat renmOutputFormat = OutputFormat.Verbose;

            //  ----------------------------------------------------------------
            //  Enum.Parse needs a try/catch block, because an invalid SW_OUTPUT
            //  value raises an exception that can be gracefully handled without
            //  killing the program.
            //  ----------------------------------------------------------------

            try
            {
                if ( pcmdArgs.ValidSwitchesInCmdLine > NONE )
                {
                    renmOutputFormat = ( OutputFormat ) Enum.Parse (
                        typeof ( OutputFormat ) ,
                        pcmdArgs.GetSwitchByName (
                            SW_OUTPUT ,
                            OutputFormat.Verbose.ToString ( ) ) ,
                        IGNORE_CASE );
                }   // if ( pcmdArgs.ValidSwitchesInCmdLine > NONE )
            }
            catch ( ArgumentException exArg )
            {   // Display of the message is deferred until the BOJ message is printed.
                s_theApp.BaseStateManager.AppExceptionLogger.ReportException ( exArg );
                pstrDeferredMessage = string.Format (
                    Properties.Resources.ERRMSG_INVALID_OUTPUT_FORMAT ,
                    exArg.Message.ExtractBoundedSubstrings ( WizardWrx.SpecialCharacters.SINGLE_QUOTE ) ,
                    renmOutputFormat ,
                    Environment.NewLine );
            }

            return renmOutputFormat;
        }   // private static OutputFormat SetOutputFormat
Пример #3
0
        }   // private static int ScanForNextGuardCharacter


        /// <summary>
        /// Map the CMD_ARG_NEWLINE_REPL_TOKEN string values to a corresponding
        /// character.
        /// </summary>
        /// <param name="pcmdLneArgs">
        /// Passing the CmdLneArgsBasic object into the method hides the name of
        /// the corresponding command line argument, which is read into a local
        /// argument string from an embedded string resource.
        /// </param>
        /// <returns>
        /// The return value is one of two supported characters, a regular space
        /// and a nonbreaking space, both of which are defined as consnstants in
        /// core library WizardWrx.Common.dll, taken or converted to strings.
        /// </returns>
        private static string SetEmbeddedNewlineReplacementValue ( CmdLneArgsBasic pcmdLneArgs )
        {
            string strCmdArgValue = pcmdLneArgs.GetArgByName ( Properties.Resources.CMD_ARG_NEWLINE_REPL_TOKEN );

            if ( strCmdArgValue.Equals ( Properties.Resources.NEWLINE_REPL_TOKEN_SPACE ) )

                return SpecialStrings.TAB_CHAR;
            else if ( strCmdArgValue.Equals ( Properties.Resources.NEWLINE_REPL_TOKEN_NBSP ) )
                return SpecialCharacters.NONBREAKING_SPACE_CHAR.ToString ( );
            else
                return SpecialCharacters.NONBREAKING_SPACE_CHAR.ToString ( );
        }   // private static char SetEmbeddedNewlineReplacementValue
        }   // GetParameterNames Method


        /// <summary>
        /// Set the parameter values from an initialized CmdLneArgsBasic object,
        /// overriding any that were initialized from the Application Settings.
        /// </summary>
        /// <param name="pcmdArgs">
        /// Pass in a reference to a CmdLneArgsBasic object that was initialized
        /// from the string array returned by the GetParameterNames method.
        /// </param>
        /// <param name="penmParameterSource">
        /// Specify the member of the ParameterSource, generic type U,
        /// enumeration with which to mark the object if the CmdLneArgsBasic
        /// object includes a value.
        /// 
        /// Please <see cref="OperatingParametersCollection{T, U}"/> for more
        /// details.
        /// </param>
        public void SetFromCommandLineArguments (
            CmdLneArgsBasic pcmdArgs ,
            U penmParameterSource )
        {
            lock ( s_srCriticalSection )
            {
                IEnumerator<KeyValuePair<string , OperatingParameter<T , U>>> listOfValidArguments = _dctOperatingParameters
                .GetEnumerator ( );

                while ( listOfValidArguments.MoveNext ( ) )
                {
                    string strName = listOfValidArguments.Current.Key;
                    string strValue = pcmdArgs.GetArgByName ( strName );

                    if ( !string.IsNullOrEmpty ( strValue ) )
                    {
                        OperatingParameter<T , U> opThis = listOfValidArguments.Current.Value;
                        opThis.SetValue (
                            strValue ,                                              // string pstrValue
                            penmParameterSource );                                  // ParameterSource penmSource
                    }   // if ( !string.IsNullOrEmpty ( strValue ) )
                }   // while ( listOfValidArguments.MoveNext ( ) )
            }   // lock ( s_srCriticalSection )
        }   // SetFromCommandLineArguments Method
Пример #5
0
		static void Main ( string [ ] args )
		{
			const int EXTRA_LEADING_CHARACTERS = 19;

			const string INTERNAL_ERROR_OO2_PREFIX = @"INTERNAL PROCESSING ERROR 002:";
			const string INTERNAL_ERROR_OO3_PREFIX = @"INTERNAL PROCESSING ERROR 003:";
			const string INTERNAL_ERROR_OO4_PREFIX = @"INTERNAL PROCESSING ERROR 004:";
			const string INTERNAL_ERROR_OO5_PREFIX = @"INTERNAL PROCESSING ERROR 005:";

			s_theApp = ConsoleAppStateManager.GetTheSingleInstance ( );
			s_theApp.DisplayBOJMessage ( );
			s_theApp.BaseStateManager.AppExceptionLogger.OptionFlags = s_theApp.BaseStateManager.AppExceptionLogger.OptionFlags
																	   | ExceptionLogger.OutputOptions.Stack
																	   | ExceptionLogger.OutputOptions.EventLog
																	   | ExceptionLogger.OutputOptions.StandardError;
			s_theApp.BaseStateManager.LoadErrorMessageTable ( s_astrErrorMessages );

			try
			{
				Console.WriteLine ( 
					"Namespace of Entry Point Routine {0} = {1} " ,
					System.Reflection.MethodBase.GetCurrentMethod ( ).Name ,
					System.Reflection.Assembly.GetEntryAssembly ( ).EntryPoint.DeclaringType.Namespace );

				Type typeCmdArgsBasic = typeof ( CmdLneArgsBasic );
				System.Reflection.Assembly asmClassLibrary = System.Reflection.Assembly.GetAssembly ( typeCmdArgsBasic );

				Console.WriteLine (
					"Namespace of Entry Point Routine of the assembly that exports class {0} = {1} " ,
					typeCmdArgsBasic.FullName ,
					asmClassLibrary.EntryPoint == null
						? Properties.Resources.RENDERED_STRING_IS_NULL
						: asmClassLibrary.EntryPoint.DeclaringType.Namespace );

				Utl.ListInternalResourceNames ( System.Reflection.Assembly.GetExecutingAssembly ( ) );
				AppSettingsForEntryAssembly appSettingsForEntryAssembly = AppSettingsForEntryAssembly.GetTheSingleInstance ( Properties.Settings.Default.Properties);

				string strAppSettingMane = @"OperatingParameter1";

				{   // Constrain the scope of objAppSettingValue.
					object objAppSettingValue = appSettingsForEntryAssembly.GetAppSettingByName ( strAppSettingMane );
					Console.WriteLine (
						"Application Setting {0} = {1}" ,
						strAppSettingMane ,
						objAppSettingValue == null
							? Properties.Resources.RENDERED_STRING_IS_NULL
							: objAppSettingValue );
				}   // Let objAppSettingValue go out of scope.

				strAppSettingMane = @"OperatingParameter2";

				{   // Constrain the scope of objAppSettingValue.
					object objAppSettingValue = appSettingsForEntryAssembly.GetAppSettingByName ( strAppSettingMane );
					Console.WriteLine (
						"Application Setting {0} = {1}" ,
						strAppSettingMane ,
						objAppSettingValue == null
							? Properties.Resources.RENDERED_STRING_IS_NULL
							: objAppSettingValue );
				}   // Let objAppSettingValue go out of scope.

				appSettingsForEntryAssembly.ListAllAppSettings ( );
				OperatingParametersCollection<ParameterType , ParameterSource> operatingParametersColl = OperatingParametersCollection<ParameterType , ParameterSource>.GetTheSingleInstance (
					Properties.Settings.Default.Properties ,
					Properties.Resources.PARAMETER_DISPLAY_NAME_TEMPLATE ,
					ParameterSource.ApplicationSettings );
				CmdLneArgsBasic cmdArgs = new CmdLneArgsBasic (
					operatingParametersColl.GetParameterNames ( ) ,
					CmdLneArgsBasic.ArgMatching.CaseInsensitive );
				operatingParametersColl.SetFromCommandLineArguments (
					cmdArgs ,
					ParameterSource.CommandLine );

				int intTotalParameters = operatingParametersColl.GetCount ( );
				Console.WriteLine (
					Properties.Resources.MSG_PARAMETER_LIST_HEADER ,            // Format Control String: The {0} application has {1} parameters.
					s_theApp.BaseStateManager.AppRootAssemblyFileBaseName ,     // Format Item 0: The {0} application
					intTotalParameters ,                                        // Format Item 1: has {1} parameters.
					Environment.NewLine );                                      // Format Item 2: platform-dependent newline
				int intParameterNumber = ListInfo.LIST_IS_EMPTY;

				foreach ( string strParamName in operatingParametersColl.GetParameterNames ( ) )
				{
					Console.WriteLine (
						Properties.Resources.MESSAGE_PARAMETER_NAME ,           // Format Control String: "    Parameter # {0}: {1}" (excluding the quotation marks, of course!)
						++intParameterNumber ,                                  // Format Item 0: Parameter # {0}:
						Utl.ListPropertiesPerDefaultToString (                  // Format Item 1: Property Details listed by its ToString method
							operatingParametersColl.GetParameterByName ( strParamName ) ,
							EXTRA_LEADING_CHARACTERS ) );
				}   // foreach ( string strParamName in operatingParametersColl.GetParameterNames ( ) )

				Console.WriteLine (
					Properties.Resources.MSG_PARAMETER_LIST_FOOTER ,            // Format Control String: End of {0} parameter list.
					s_theApp.BaseStateManager.AppRootAssemblyFileBaseName ,     // Format Item 0: End of {0} parameter
					Environment.NewLine );                                      // Format Item 1: platform-dependent newline

				Console.WriteLine (
					Properties.Resources.MSG_VALIDATION_BEGIN ,                 // Format Control String
					Environment.NewLine );                                      // Format Item 0: platform-dependent newline

				foreach ( string strParamName in operatingParametersColl.GetParameterNames ( ) )
				{
					OperatingParameter<ParameterType , ParameterSource> operatingParameter = operatingParametersColl.GetParameterByName ( strParamName );
					bool fParamIsValid = operatingParameter.IsValueValid<ParameterType> ( );
					Console.WriteLine (
						Properties.Resources.MSG_VALIDATION_DETAIL ,            // Format Control String: Parameter {0} value of {1} is {2}.
						operatingParameter.DisplayName ,                        // Format Item 0: Parameter {0}
						Utl.RenderStringValue (
							operatingParameter.ParamValue ) ,                   // Format Item 1: value of {1}
						fParamIsValid );                                        // Format Item 2: is {2}
				}   // foreach ( string strParamName in operatingParametersColl.GetParameterNames ( ) )

				Console.WriteLine (
					Properties.Resources.MSG_VALIDATION_END ,                   // Format Control String
					Environment.NewLine );                                      // Format Item 0: platform-dependent newline
			}	// try block
			catch ( Exception exAllKinds )
			{   // Theere must be a lower-maintenance way to do this.
				if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO2_PREFIX ) )
				{
					s_theApp.BaseStateManager.AppReturnCode = ERROR_INTERNAL_PROCESSING_ERROR_002;
				}   // TRUE block, if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO2_PREFIX ) )
				else if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO3_PREFIX ) )
				{
					s_theApp.BaseStateManager.AppReturnCode = ERROR_INTERNAL_PROCESSING_ERROR_003;
				}   // TRUE block, else if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO3_PREFIX ) )
				else if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO4_PREFIX ) )
				{
					s_theApp.BaseStateManager.AppReturnCode = ERROR_INTERNAL_PROCESSING_ERROR_004;
				}   // TRUE block, else if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO4_PREFIX ) )
				else if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO5_PREFIX ) )
				{
					s_theApp.BaseStateManager.AppReturnCode = ERROR_INTERNAL_PROCESSING_ERROR_005;
				}   // TRUE block, else if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO4_PREFIX ) )
				else
				{   // If all else fails, call it a run-of-the-mill runtime error.
					s_theApp.BaseStateManager.AppReturnCode = WizardWrx.MagicNumbers.ERROR_RUNTIME;
				}   // FALSE block, if ( exAllKinds.Message.StartsWith ( INTERNAL_ERROR_OO2_PREFIX ) ) ...

				s_theApp.BaseStateManager.AppExceptionLogger.ReportException ( exAllKinds );
			}   // catch ( Exception exAllKinds ) block

			if ( s_theApp.BaseStateManager.AppReturnCode == WizardWrx.MagicNumbers.ERROR_SUCCESS )
			{
				s_theApp.NormalExit ( ConsoleAppStateManager.NormalExitAction.Timed );
			}   // TRUE (anticipated outcome) block, if ( s_theApp.BaseStateManager.AppReturnCode == WizardWrx.MagicNumbers.ERROR_SUCCESS )
			else
			{
				s_theApp.ErrorExit ( ( uint ) s_theApp.BaseStateManager.AppReturnCode );
			}   // FALSE (unanticipated outcome) block, if ( s_theApp.BaseStateManager.AppReturnCode == WizardWrx.MagicNumbers.ERROR_SUCCESS )
		}   // static void Main
Пример #6
0
        };  // static char [ ] s_achrValidSwitches

        static void Main ( string [ ] args )
        {

            s_theApp = ConsoleAppStateManager.GetTheSingleInstance ( );

            CmdLneArgsBasic cmdArgs = new CmdLneArgsBasic (
                s_achrValidSwitches ,
                CmdLneArgsBasic.ArgMatching.CaseInsensitive )
            {
                AllowEmptyStringAsDefault = CmdLneArgsBasic.BLANK_AS_DEFAULT_ALLOWED
            };

            //  ----------------------------------------------------------------
            //  The default value of the AppSubsystem property is GUI, which
            //  disables output to the console. Since ReportException returns
            //  the message that would have been written, you still have the
            //  option of displaying or discarding it. If EventLoggingState is
            //  set to Enabled, the message is written into the Application
            //  Event log, where it is preserved until the event log record is
            //  purged by the aging rules or some other method.
            //  ----------------------------------------------------------------

            s_theApp.BaseStateManager.AppExceptionLogger.OptionFlags =
                s_theApp.BaseStateManager.AppExceptionLogger.OptionFlags
                | ExceptionLogger.OutputOptions.EventLog
                | ExceptionLogger.OutputOptions.Stack
                | ExceptionLogger.OutputOptions.StandardError;
            s_theApp.BaseStateManager.LoadErrorMessageTable ( s_astrErrorMessages );

            string strDeferredMessage = null;

            OutputFormat enmOutputFormat = SetOutputFormat (
                cmdArgs ,
                ref strDeferredMessage );

            if ( enmOutputFormat != OutputFormat.None )
            {   // Unless output is suppressed, display the standard BOJ message.
                s_theApp.DisplayBOJMessage ( );
            }   // if ( enmOutputFormat != OutputFormat.None )

            if ( !string.IsNullOrEmpty ( strDeferredMessage ) )
            {   // SetOutputFormat saves its error message, if any, in SetOutputFormat. 
                Console.WriteLine ( strDeferredMessage );
            }   // if ( !string.IsNullOrEmpty ( s_strDeferredMessage ) )

            if ( cmdArgs.PositionalArgsInCmdLine < CmdLneArgsBasic.FIRST_POSITIONAL_ARG )
            {   // Required input is missing. Report and bug out.
                s_theApp.ErrorExit ( ERR_NEED_INPUT_FILENAME );
            }   // if ( cmdArgs.PositionalArgsInCmdLine < CmdLneArgsBasic.FIRST_POSITIONAL_ARG )

            string strTestFileName = cmdArgs.GetArgByPosition ( CmdLneArgsBasic.FIRST_POSITIONAL_ARG );
            Console.WriteLine (
                Properties.Resources.MSG_INPUT_FILENAME ,
                s_theApp.BaseStateManager.InitialWorkingDirectoryName ,
                strTestFileName ,
                Environment.NewLine );

            try
            {
#if ANYCSV
                int intNCases = System.IO.File.ReadAllLines (
                    strTestFileName , 
                    Encoding.ASCII ).Length;
                int intCurrCase = MagicNumbers.ZERO;

                WizardWrx.AnyCSV.Parser ReusableParser = new WizardWrx.AnyCSV.Parser (
                    WizardWrx.AnyCSV.CSVParseEngine.DelimiterChar.Comma ,
                    WizardWrx.AnyCSV.CSVParseEngine.GuardChar.DoubleQuote ,
                    WizardWrx.AnyCSV.CSVParseEngine.GuardDisposition.Strip );
                Console.WriteLine (
                    Properties.Resources.MSG_TOSTRING_CONSTRUCTED_FROM_ENUMS ,          // Format control string
                    Properties.Resources.MSG_TOSTRING_JUST_CONSTRUCTED ,                // Format Item 0: {0}, the ToString method
                    nameof ( ReusableParser ) ,                                         // Format Item 1: the ToString method on {1} reports
                    ReusableParser.ToString ( ) );                                      // Format Item 2: reports as follows: {2}.

                using ( System.IO.StreamReader srTestData = new System.IO.StreamReader (
                        strTestFileName ,
                        Encoding.ASCII ,
                        IGNORE_BOM ,
                        MagicNumbers.CAPACITY_08KB ) )
                {
                    do
                    {
                        string strTestCase = srTestData.ReadLine ( );

                        string [ ] astrInstanceTestOutput = ReusableParser.Parse ( strTestCase );

                        if ( intCurrCase == MagicNumbers.ZERO )
                        {   // On the first iteration, intCurrCase is zero.
                            Console.WriteLine (
                                Properties.Resources.MSG_TOSTRING_CONSTRUCTED_FROM_ENUMS ,          // Format control string
                                Properties.Resources.MSG_TOSTRING_POST_FIRST_USE ,                  // Format Item 0: {0}, the ToString method
                                nameof ( ReusableParser ) ,                                         // Format Item 1: the ToString method on {1} reports
                                ReusableParser.ToString ( ) );                                      // Format Item 2: reports as follows: {2}.
                        }   // if ( intCurrCase == MagicNumbers.ZERO )

                        string [ ] astrStaticTestOutput1 = WizardWrx.AnyCSV.Parser.Parse (
                            strTestCase ,                                                           // Input string
                            WizardWrx.AnyCSV.Parser.COMMA ,                                         // Field delimiter character
                            WizardWrx.AnyCSV.Parser.DOUBLE_QUOTE );                                 // Delimiter guard character

                        //  ----------------------------------------------------
                        //  Identify the case number, and show the input string.
                        //  ----------------------------------------------------

                        intCurrCase++;
                        int intNFields = astrStaticTestOutput1.Length;
                        Console.WriteLine (
                            Properties.Resources.MSG_CASE_LABEL ,
                            new string [ ]
                            {
                                intCurrCase.ToString ( ) ,
                                intNCases.ToString ( ) ,
                                intNFields.ToString ( ) ,
                                strTestCase ,
                                Environment.NewLine } );

                        ReportScenarioOutcome (
                            Properties.Resources.INSTANCE_SCENARIO_1 ,
                            astrInstanceTestOutput ,
                            astrInstanceTestOutput.Length );
                        ReportScenarioOutcome (
                            Properties.Resources.STATIC_SCENARIO_1 ,
                            astrStaticTestOutput1 ,
                            intNFields );

                        string [ ] astrStaticTestOutput2 = WizardWrx.AnyCSV.Parser.Parse (
                            strTestCase ,                                                           // Input string
                            WizardWrx.AnyCSV.Parser.COMMA ,                                         // Field delimiter character
                            WizardWrx.AnyCSV.Parser.DOUBLE_QUOTE ,                                  // Delimiter guard character
                            WizardWrx.AnyCSV.Parser.GuardDisposition.Keep );                        // Override to keep.

                        intNFields = astrStaticTestOutput2.Length;
                        ReportScenarioOutcome (
                            Properties.Resources.STATIC_SCENARIO_2 ,
                            astrStaticTestOutput2 ,
                            intNFields );

                        string [ ] astrStaticTestOutput3 = WizardWrx.AnyCSV.Parser.Parse (
                            strTestCase ,                                                           // Input string
                            WizardWrx.AnyCSV.Parser.COMMA ,                                         // Field delimiter character
                            WizardWrx.AnyCSV.Parser.DOUBLE_QUOTE ,                                  // Delimiter guard character
                            WizardWrx.AnyCSV.Parser.GuardDisposition.Strip ,                        // Override to keep.
                            WizardWrx.AnyCSV.Parser.TrimWhiteSpace.TrimLeading );
                        intNFields = astrStaticTestOutput3.Length;
                        ReportScenarioOutcome (
                            Properties.Resources.STATIC_SCENARIO_3 ,
                            astrStaticTestOutput3 ,
                            intNFields );
                    } while ( !srTestData.EndOfStream );
                }   // using ( System.IO.StreamReader srTestData = new System.IO.StreamReader (
#else
                CsvParser engine = new CsvParser ( );
                string [ ] [ ] astrParsedStrings = engine.Parse ( 
                    new System.IO.StreamReader (
                        strTestFileName ,
                        Encoding.ASCII ,
                        IGNORE_BOM ,
                        StandardConstants.FILE_BUFSIZE_STANDARD_08KB ) );
                int intNCases = astrParsedStrings.Length;

                for ( int intCurrCase = StandardConstants.ARRAY_FIRST_ELEMENT ; intCurrCase < intNCases ; intCurrCase++ )
                {
                    int intNFields = astrParsedStrings [ intCurrCase ].Length;
                    Console.WriteLine (
                        Properties.Resources.MSG_CASE_LABEL ,
                        new string [ ]
                        {
                            OrdinalFromSubscript ( intCurrCase ).ToString(),
                            intNCases.ToString() ,
                            intNFields.ToString() ,
                            Environment.NewLine
                        } );
                    
                    for ( int intCurrField = StandardConstants.ARRAY_FIRST_ELEMENT ;
                              intCurrField < astrParsedStrings [ intCurrCase ].Length ;
                              intCurrField++ )
                    {
                        Console.WriteLine (
                            Properties.Resources.MSG_CASE_DETAIL ,
                            OrdinalFromSubscript ( intCurrField ) ,
                            intNFields ,
                            astrParsedStrings [ intCurrCase ] [ intCurrField ] );
                    }   // for ( int intCurrField = StandardConstants.ARRAY_FIRST_ELEMENT ; intCurrField < astrParsedStrings [ intCurrCase ].Length ; intCurrField++ )
                }   // for ( int intCurrCase = StandardConstants.ARRAY_FIRST_ELEMENT ; intCurrCase < intNCases ; intNCases++ )
#endif
            }
            catch ( Exception exAll )
            {   // The Message string is displayed, but the complete exception goes to the event log.
                s_theApp.BaseStateManager.AppExceptionLogger.ReportException ( exAll );
                Console.WriteLine ( exAll.Message );

                ExitWithError (
                    enmOutputFormat ,
                    ERR_RUNTIME );
            }   // Providing a catch block is enough to cause the program to fall through.

#if DEBUG
            if ( enmOutputFormat == OutputFormat.None )
            {   // Suppress all output.
                s_theApp.NormalExit (  ConsoleAppStateManager.NormalExitAction.Silent );
            }   // TRUE block, if ( enmOutputFormat == OutputFormat.None )
            else
            {   // Display the standard exit banner.
                s_theApp.NormalExit ( ConsoleAppStateManager.NormalExitAction.WaitForOperator );
            }   // FALSE block, if ( enmOutputFormat == OutputFormat.None )
#else
            if ( enmOutputFormat == OutputFormat.None )
            {   // Suppress all output.
                s_theApp.NormalExit ( ConsoleAppStateManager.NormalExitAction.Silent );
            }   // TRUE block, if ( enmOutputFormat == OutputFormat.None )
            else
            {   // Display the standard exit banner.
                s_theApp.NormalExit(ConsoleAppStateManager.NormalExitAction.WaitForOperator);
            }   // FALSE block, if ( enmOutputFormat == OutputFormat.None )
#endif
        }   // static void Main
Пример #7
0
        static void Main ( string [ ] args )
        {
            s_exLogger.OptionFlags = s_exLogger.OptionFlags
                                     | ExceptionLogger.OutputOptions.Stack
                                     | ExceptionLogger.OutputOptions.EventLog;
            s_theApp.BaseStateManager.LoadErrorMessageTable (
                new string [ ]
                {
                    null ,														// ERROR_SUCCESS
                    Properties.Resources.MSG_ERROR_RUNTIME_EXCEPTION ,			// ERR_RUNTIME
                    Properties.Resources.MSG_ERROR_FILE_TO_PROCESS_OMITTED ,	// ERR_FILENAME_MISSING
                    Properties.Resources.MSG_ERROR_FILE_TO_PROCESS_NOT_FOUND ,	// ERR_FNF
                    Properties.Resources.MSG_ERROR_BACKUP_OF_BACKUP				// WRM_NAME_COLLISION
                } );
            s_theApp.DisplayBOJMessage ( );
            CmdLneArgsBasic cmdLneArgs = new CmdLneArgsBasic (
                new string [ ]
                {
                    Properties.Resources.CMD_ARG_INPUT_FILENAME,
                    Properties.Resources.CMD_ARG_NEWLINE_REPL_TOKEN
                } );
            s_operatingParameters.InputFileNamePerCmd = cmdLneArgs.GetArgByName (
                Properties.Resources.CMD_ARG_INPUT_FILENAME );

            //  ----------------------------------------------------------------
            //  Evaluate the sole required command line argument. Unless it has
            //  a value, there is no point proceeding with anything more.
            //  ----------------------------------------------------------------

            if ( !string.IsNullOrEmpty ( s_operatingParameters.InputFileNamePerCmd ) )
            {
                s_operatingParameters.NewlineReplacementToken = SetEmbeddedNewlineReplacementValue ( cmdLneArgs );
                s_operatingParameters.BackupFileName = string.Concat (
                    s_operatingParameters.InputFileNamePerCmd ,
                    Properties.Resources.MSG_BACKUP_FILE_EXTENSION );
                Console.WriteLine (
                    Properties.Resources.MSG_INFO_INPUT_FILENAME ,              // Format control string
                    s_operatingParameters.InputFileNamePerCmd ,                 // Name of event log export file to process
                    s_operatingParameters.BackupFileName ,                      // Name of backup file to create
                    Environment.NewLine );                                      // Embedded newline

                //  ------------------------------------------------------------
                //  From here to almost the end involves interacting with the
                //  file system, so the majority of the main routine runs inside
                //  a try/catch block.
                //  ------------------------------------------------------------

                try
                {
                    if ( File.Exists ( s_operatingParameters.InputFileNamePerCmd ) )
                    {
                        if ( MakeBackup ( s_operatingParameters.InputFileNamePerCmd , s_operatingParameters.BackupFileName ) )
                        {
                            ProcessInputFile ( );
                        }   // if ( MakeBackup ( s_operatingParameters.InputFileNamePerCmd , s_operatingParameters.BackupFileName ) )
                    }   // TRUE (anticipated outcome) block, if ( File.Exists ( s_operatingParameters.InputFileNamePerCmd ) )
                    else
                    {
                        s_theApp.BaseStateManager.AppReturnCode = ERR_FNF;
                    }   // FALSE (unanticipated outcome) block, if ( File.Exists ( s_operatingParameters.InputFileNamePerCmd ) )
                }
                catch ( Exception exAll )
                {
                    s_theApp.BaseStateManager.AppExceptionLogger.ReportException ( exAll );
                    s_theApp.BaseStateManager.AppReturnCode = ERR_RUNTIME;
                }
            }   // TRUE (anticipated outcome) block, if ( !string.IsNullOrEmpty ( s_operatingParameters.InputFileNamePerCmd ) )
            else
            {
                s_theApp.BaseStateManager.AppReturnCode = ERR_FILENAME_MISSING;
                Console.WriteLine (
                    Properties.Resources.MSG_SYNTAX_HELP ,                      // Format Control String, presently "{1}Minimum command line:{1}{1}{0} InputFileName=CSVFileName{1}where CSVFileName = Name of CSV to process{1}"
                    s_theApp.BaseStateManager.AppRootAssemblyFileName ,         // Format Token 0: {0} InputFileName=CSVFileName
                    Environment.NewLine );                                      // Format Token 1: Newlines everywhere else
            }   // FALSE (unanticipated outcome) block, if ( !string.IsNullOrEmpty ( s_operatingParameters.InputFileNamePerCmd ) )

            //  ----------------------------------------------------------------
            //  Summarize and wrap up takes one of two turns, depending on the
            //  value of the return code stored in the application manager.
            //  ----------------------------------------------------------------

            if ( s_theApp.BaseStateManager.AppReturnCode == MagicNumbers.ERROR_SUCCESS )
            {
                s_theApp.NormalExit ( ConsoleAppStateManager.NormalExitAction.Timed );
            }   // TRUE (desired outcome) block, if ( s_theApp.BaseStateManager.AppReturnCode == MagicNumbers.ERROR_SUCCESS )
            else
            {   // Strictly speaking, one of the outcomes is just a warning.
                Console.WriteLine ( );
                s_theApp.ErrorExit ( ( uint ) s_theApp.BaseStateManager.AppReturnCode );
            }	// false (undesired outcome) block, if ( s_theApp.BaseStateManager.AppReturnCode == MagicNumbers.ERROR_SUCCESS )
        }   // static void Main
Пример #8
0
        }           // private static string FormatSpecialCharacters

        private static void EmumerateDefinedSwitches(
            CmdLneArgsBasic pcmdLineArgs,
            char [] pachrSwitchSetAllDefined)
        {
            const string MSG_DISP_BLANK_AS_DEFAULT = @"   BlankAsDefault Property = {0}{1}";
            const string ARG_DISP_TPL_SWITCH       = @"     Switch {0} = {1}";
            const string MSG_NO_SWITCHES_DEFINED   = @"     No switches are defined. Input {0} is {1}.";
            const string MSG_SWITCH_OMITTED        = @"** OMITTED **";

            if (pachrSwitchSetAllDefined == null)
            {
                Console.WriteLine(
                    MSG_NO_SWITCHES_DEFINED,
                    pcmdLineArgs,
                    LIST_IS_NULL);
            }               // TRUE block, if ( pachrSwitchSetAllDefined == null )
            else
            {
                if (pachrSwitchSetAllDefined.Length == ArrayInfo.ARRAY_FIRST_ELEMENT)
                {
                    Console.WriteLine(
                        MSG_NO_SWITCHES_DEFINED,
                        pcmdLineArgs,
                        LIST_IS_EMPTY);
                }                   // TRUE block, if ( pachrSwitchSetAllDefined.Length == ArrayInfo.ARRAY_FIRST_ELEMENT )
                else
                {
                    foreach (bool fBlankAsDefault in s_afBlankAsDefault)
                    {
                        pcmdLineArgs.AllowEmptyStringAsDefault = fBlankAsDefault;
                        Console.WriteLine(
                            MSG_DISP_BLANK_AS_DEFAULT,
                            pcmdLineArgs.AllowEmptyStringAsDefault,
                            Environment.NewLine);

                        foreach (char chrSwitch in pachrSwitchSetAllDefined)
                        {
                            Console.WriteLine(
                                ARG_DISP_TPL_SWITCH,
                                chrSwitch,
                                pcmdLineArgs.GetSwitchByName(chrSwitch));
                            Console.WriteLine(
                                ARG_DISP_TPL_SWITCH,
                                chrSwitch,
                                pcmdLineArgs.GetSwitchByName(
                                    chrSwitch,
                                    MSG_SWITCH_OMITTED));
                            Console.WriteLine(
                                ARG_DISP_TPL_SWITCH,
                                chrSwitch,
                                pcmdLineArgs.GetSwitchByName(
                                    chrSwitch,
                                    SpecialStrings.EMPTY_STRING,
                                    CmdLneArgsBasic.BLANK_AS_DEFAULT_FORBIDDEN));
                            Console.WriteLine(
                                ARG_DISP_TPL_SWITCH,
                                chrSwitch,
                                pcmdLineArgs.GetSwitchByName(
                                    chrSwitch,
                                    SpecialStrings.EMPTY_STRING,
                                    CmdLneArgsBasic.BLANK_AS_DEFAULT_ALLOWED));
                            Console.WriteLine(
                                ARG_DISP_TPL_SWITCH,
                                chrSwitch,
                                pcmdLineArgs.GetBooleanSwitchByName(chrSwitch));
                        } // foreach ( char chrSwitch in pachrSwitchSetAllDefined )
                    }     // foreach ( bool fBlankAsDefault in _afBlankAsDefault )
                }         // FALSE block, if ( pachrSwitchSetAllDefined.Length == ArrayInfo.ARRAY_FIRST_ELEMENT )
            }             // FALSE block, if ( pachrSwitchSetAllDefined == null )
        }                 // private static void EmumerateDefinedSwitches method
Пример #9
0
        }           // private static void method EnumeratePositionalArgs

        private static void EnumerateDefinedNamedArguments(
            CmdLneArgsBasic pcmdLineArgs,
            string [] pastrValidArgumentNames)
        {
            const string ARG_DISP_TPL_NAMED_ARG    = @"     Argument {0} = {1} - First character = {2}";
            const string MSG_NO_NAMED_ARGS_DEFINED = @"     No named arguments are defined. Input {0} is {1}.";

            if (pcmdLineArgs == null)
            {
                Console.WriteLine(
                    MSG_NO_NAMED_ARGS_DEFINED,
                    pcmdLineArgs,
                    LIST_IS_NULL);
            }               // TRUE block, if ( pcmdLineArgs == null )
            else if (pcmdLineArgs.DefinedNamedArgs == ArrayInfo.ARRAY_FIRST_ELEMENT)
            {
                Console.WriteLine(
                    MSG_NO_NAMED_ARGS_DEFINED,
                    pcmdLineArgs,
                    LIST_IS_EMPTY);
            }               // TRUE block, else if ( pcmdLineArgs.DefinedNamedArgs == ArrayInfo.ARRAY_FIRST_ELEMENT )
            else
            {
                foreach (string strArgName in pastrValidArgumentNames)
                {
                    try
                    {
                        Console.WriteLine(
                            ARG_DISP_TPL_NAMED_ARG,
                            strArgName,
                            pcmdLineArgs.GetArgByName(strArgName),
                            FormatSpecialCharacters(pcmdLineArgs.GetArgByNameAsChar(strArgName)));
                    }
                    catch (Exception exAny)
                    {
                        if (exAny.Message.StartsWith(WizardWrx.Common.Properties.Resources.ERRMSG_ARG_IS_NULL_OR_EMPTY) && exAny.TargetSite.Name == "FirstCharFromString")
                        {
                            Console.WriteLine(
                                ARG_DISP_TPL_NAMED_ARG,
                                strArgName,
                                pcmdLineArgs.GetArgByName(strArgName),
                                FormatSpecialCharacters(
                                    pcmdLineArgs.GetArgByNameAsChar(
                                        strArgName,
                                        SpecialCharacters.NULL_CHAR)));
                        }                           // TRUE block, if ( exAny.Message.StartsWith(MagicNumbers.ERRMSG_ARG_IS_NULL_OR_EMPTY) && exAny.TargetSite.Name == "FirstCharFromString" )
                        else
                        {
                            StringBuilder sbMsg = new StringBuilder(MagicNumbers.CAPACITY_08KB);

                            sbMsg.AppendFormat(
                                Program.ERRMSG_INTERNAL_ERROR_TPL,
                                exAny.Message,
                                Environment.NewLine);

                            sbMsg.AppendFormat(
                                Program.ERRMSG_INTERNAL_SOURCE_TPL,
                                exAny.Source,
                                Environment.NewLine);
                            sbMsg.AppendFormat(
                                Program.ERRMSG_INTERNAL_TARGETSITE_TPL,
                                exAny.TargetSite.Name,
                                Environment.NewLine);

                            // ---------------------------------------------------------
                            // 2012/07/07 - DAG    - Added environment.NewLine to the
                            //                       argument list. This same change
                            //                       should be applied to the routine in
                            //                       TextLog.cs from which this code is
                            //                       derived.
                            // ---------------------------------------------------------

                            sbMsg.AppendFormat(
                                Program.ERRMSG_INTERNAL_STACKTRACE_TPL,
                                exAny.StackTrace,
                                Environment.NewLine);

                            if (exAny.InnerException != null)
                            {
                                sbMsg.AppendFormat(
                                    Program.ERRMSG_INTERNAL_INNER_MSG_TPL,
                                    exAny.InnerException.Message);
                            }

                            string strMsg = sbMsg.ToString( );

                            Console.WriteLine(strMsg);
                            System.Diagnostics.EventLog.WriteEntry(
                                ExceptionLogger.GetTheSingleInstance( ).AppEventSourceID,
                                strMsg,
                                System.Diagnostics.EventLogEntryType.Warning);
                        } // FALSE block, if ( exAny.Message.StartsWith(MagicNumbers.ERRMSG_ARG_IS_NULL_OR_EMPTY) && exAny.TargetSite.Name == "FirstCharFromString" )
                    }     // catch block
                }         // foreach ( string strArgName in pastrValidArgumentNames )
            }             // FALSE block, else if ( pcmdLineArgs.DefinedNamedArgs == ArrayInfo.ARRAY_FIRST_ELEMENT )
        }                 // private static void EnumerateDefinedNamedArguments
Пример #10
0
        }           // private static void DisplayReadOnlyProperties

        private static void EnumeratePositionalArgs(CmdLneArgsBasic pcmdLineArgs)
        {
            const string ARG_DISP_TPL_COUNT      = @"{1}     Count of positional arguments = {0}{1}";
            const string ARG_DISP_TPL_END        = @"{0}     End of positional argument list{0}";
            const string ARG_DISP_TPL_POSITIONAL = @"          Positional argument # {0} = {1}";
            const string MSG_NO_POSITIONAL_ARGS  = @"     The command line contains no positional arguments.";

            //bool fMoreArgs = true;
            int intArgOrdinal = ArrayInfo.ARRAY_FIRST_ELEMENT;

            //  ----------------------------------------------------------------
            //  This is the old way, before I had these properties to query.
            //  ----------------------------------------------------------------

            //while ( fMoreArgs )
            //{
            //    string strThisArg = pcmdLineArgs.GetArgByPosition ( ++intArgOrdinal );

            //    if ( strThisArg == CmdLneArgsBasic.VALUE_NOT_SET )
            //        fMoreArgs = false;
            //    else
            //        Console.WriteLine (
            //            ARG_DISP_TPL_POSITIONAL ,
            //            intArgOrdinal ,
            //            strThisArg );
            //}   // while ( fMoreArgs )

            //if ( intArgOrdinal == ArrayInfo.NEXT_INDEX )
            //{   // No positional arguments found.
            //    Console.WriteLine ( MSG_NO_POSITIONAL_ARGS );
            //}   // if ( intArgOrdinal == ArrayInfo.NEXT_INDEX )

            //  ----------------------------------------------------------------
            //  This is the new way, which leverages the new properties.
            //  ----------------------------------------------------------------

            int intNPositionalArgsFound = pcmdLineArgs.PositionalArgsInCmdLine;

            if (intNPositionalArgsFound == ArrayInfo.ARRAY_FIRST_ELEMENT)
            {               // Report the absence of command line arguments.
                Console.WriteLine(MSG_NO_POSITIONAL_ARGS);
            }               // TRUE block (the degenerate case), if ( intNPositionalArgsFound == ArrayInfo.ARRAY_FIRST_ELEMENT )
            else
            {               // List arguments in order by position.
                Console.WriteLine(
                    ARG_DISP_TPL_COUNT,
                    intNPositionalArgsFound,
                    Environment.NewLine);

                for (intArgOrdinal = ArrayInfo.NEXT_INDEX;
                     intArgOrdinal <= intNPositionalArgsFound;
                     intArgOrdinal++)
                {
                    Console.WriteLine(
                        ARG_DISP_TPL_POSITIONAL,
                        intArgOrdinal,
                        pcmdLineArgs.GetArgByPosition(intArgOrdinal));
                }                   // for ( intArgOrdinal = ArrayInfo.NEXT_INDEX ; ...

                Console.WriteLine(
                    ARG_DISP_TPL_END,
                    Environment.NewLine);
            }       // FALSE block (the normal case), if ( intNPositionalArgsFound == ArrayInfo.ARRAY_FIRST_ELEMENT )
        }           // private static void method EnumeratePositionalArgs
Пример #11
0
        }           // private static void DisplayPublicConstants

        private static void DisplayReadOnlyProperties(CmdLneArgsBasic pcmdLineArgs)
        {
            const string ARG_IS_NULL_MSG = @"     Method DisplayReadOnlyProperties was called with a null reference.";
            const string PROP_MSG_BEGIN  = @"     Begin Read-Only Properties of object {0}{1}";
            const string PROP_MSG_END    = @"{0}     End of Read-Only Properties{0}";

            const string PROP_NAME_COUNT = @"Count";

            const string PROP_NAME_ARG_LIST_IS_EMPTY   = @"ArgListIsEmpty";
            const string PROP_NAME_ARG_MATCHING_METHOD = @"ArgumentMatching";
            const string PROP_NAME_ARGUMENT_TYPE_ARRAY = @"ArgumentTypeArray";

            const string PROP_NAME_DEFINED_NAMED_ARGS    = @"DefinedNamedArgs";
            const string PROP_NAME_DEFINED_SWITCHES_ARGS = @"DefinedSwitches";

            const string PROP_NAME_INVALID_NAMED_ARGS    = @"InvalidNamedArgsInCmd";
            const string PROP_NAME_INVALID_SWITCHES_ARGS = @"InvalidSwitchesInCmd";

            const string PROP_NAME_POSITIONAL_ARGS_IN_CMD = @"PositionalArgsInCmdLine";

            const string PROP_NAME_VALID_NAMED_ARGS    = @"ValidNamedArgsInCmd";
            const string PROP_NAME_VALID_SWITCHES_ARGS = @"ValidSwitchesInCmd";

            const string PROP_VALUE_TPL         = @"          {0} = {1}";
            const string PROP_ARRAY_SIZE_TPL    = @"{2}          {0} is an array of {1} elements, as follows.{2}";
            const string PROP_ARRAY_ELEMENT_TPL = @"               Element {0} = {1}";

            if (pcmdLineArgs == null)
            {               // Save the NullReferenceException for when you really need it.
                Console.Write(ARG_IS_NULL_MSG);
            }               // TRUE (abnormal) block, if ( pcmdLineArgs == null )
            else
            {               // Display the properties in a formatted listing.
                Console.WriteLine(
                    PROP_MSG_BEGIN,
                    pcmdLineArgs,
                    Environment.NewLine);

                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_COUNT,
                    pcmdLineArgs.Count);

                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_ARG_LIST_IS_EMPTY,
                    pcmdLineArgs.ArgListIsEmpty);
                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_ARG_MATCHING_METHOD,
                    pcmdLineArgs.ArgumentMatching);

                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_DEFINED_NAMED_ARGS,
                    pcmdLineArgs.DefinedNamedArgs);
                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_DEFINED_SWITCHES_ARGS,
                    pcmdLineArgs.DefinedSwitches);

                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_INVALID_NAMED_ARGS,
                    pcmdLineArgs.InvalidNamedArgsInCmd);
                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_INVALID_SWITCHES_ARGS,
                    pcmdLineArgs.InvalidSwitchesInCmd);

                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_POSITIONAL_ARGS_IN_CMD,
                    pcmdLineArgs.PositionalArgsInCmdLine);

                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_VALID_NAMED_ARGS,
                    pcmdLineArgs.ValidNamedArgsInCmdLine);
                Console.WriteLine(
                    PROP_VALUE_TPL,
                    PROP_NAME_VALID_SWITCHES_ARGS,
                    pcmdLineArgs.ValidSwitchesInCmdLine);

                int intArgPosition = ArrayInfo.ARRAY_INVALID_INDEX;

                try
                {
                    Console.WriteLine(
                        PROP_ARRAY_SIZE_TPL,                                                // Template string
                        PROP_NAME_ARGUMENT_TYPE_ARRAY,                                      // Token 0
                        pcmdLineArgs.ArgumentTypeArray.Length,                              // Token 1
                        Environment.NewLine);                                               // Token 2
                    intArgPosition = ArrayInfo.ARRAY_FIRST_ELEMENT;
                }
                catch (Exception errAllKinds)
                {
                    Console.WriteLine(@"          {0}", errAllKinds.Message);
                }

                if (pcmdLineArgs.ArgListIsEmpty == CmdLneArgsBasic.ARG_LIST_HAS_ARGS)
                {                   // Display a summary, followed by an enumeration.
                    if (intArgPosition == ArrayInfo.ARRAY_INVALID_INDEX)
                    {
                        Console.WriteLine(
                            PROP_ARRAY_SIZE_TPL,                   // Template string
                            PROP_NAME_ARGUMENT_TYPE_ARRAY,         // Token 0
                            pcmdLineArgs.ArgumentTypeArray.Length, // Token 1
                            Environment.NewLine);                  // Token 2
                        intArgPosition = ArrayInfo.ARRAY_FIRST_ELEMENT;
                    }                                              // if ( intArgPosition == ArrayInfo.ARRAY_INVALID_INDEX )

                    foreach (CmdLneArgsBasic.ArgType enmArgType in pcmdLineArgs.ArgumentTypeArray)
                    {                               // Use the implicit array enumerator.
                        Console.WriteLine(
                            PROP_ARRAY_ELEMENT_TPL, // Template string
                            ++intArgPosition,       // Token 0
                            enmArgType);            // Token 1
                    }                               // foreach ( CmdLneArgsBasic.ArgType enmArgType in pcmdLineArgs.ArgumentTypeArray )
                }                                   // TRUE (normal) case, if ( pcmdLineArgs.ArgListIsEmpty == CmdLneArgsBasic.ARG_LIST_HAS_ARGS )
                else
                {
                    Console.WriteLine(@"          The command line is devoid of arguments.");
                }                   // FALSE (degenerate) case, if ( pcmdLineArgs.ArgListIsEmpty == CmdLneArgsBasic.ARG_LIST_HAS_ARGS )

                Console.WriteLine(
                    PROP_MSG_END,
                    Environment.NewLine);
            }       // FALSE (normal) block, if ( pcmdLineArgs == null )
        }           // private static void DisplayReadOnlyProperties
Пример #12
0
        };  // static readonly bool [ ] _afBlankAsDefault

        internal static void Go( )
        {
            int intTestNumber = 0;

            //  ------------------------------------------------------------
            //  Test a CmdLneArgsBasic object that supports ONLY positional
            //  arguments. This is the simplest kind, and the least useful.
            //  ------------------------------------------------------------

            {               // Set scope boundaries around CmdLneArgsBasic SimpleParser.
                CmdLneArgsBasic SimpleParser = new CmdLneArgsBasic( );
                DisplayParsedArgs(
                    "Supports positional arguments only, and does case sensitive parsing",
                    SimpleParser,
                    ref intTestNumber);
            }               // CmdLneArgsBasic object SimpleParser goes out of scope.

            //  ------------------------------------------------------------
            //  Test a CmdLneArgsBasic object that supports positional
            //  arguments and switches. This is probably the most useful
            //  implementation.
            //  ------------------------------------------------------------

            {               // Set scope boundaries around CmdLneArgsBasic SwitchParser.
                CmdLneArgsBasic SwitchParser = new CmdLneArgsBasic(s_achrSwitchSetAllUC);
                DisplayParsedArgs(
                    "Supports positional arguments and switches, and does case sensitive parsing",
                    SwitchParser,
                    ref intTestNumber);
            }               // CmdLneArgsBasic SwitchParser goes out of scope.

            //  ------------------------------------------------------------
            //  Test a CmdLneArgsBasic object that supports positional
            //  arguments and switches, including an invalid switch.
            //  ------------------------------------------------------------

            {               // Set scope boundaries around InvalidSwitchParser SwitchParser.
                try
                {
                    CmdLneArgsBasic InvalidSwitchParser = new CmdLneArgsBasic(s_achrSwitchesWithDupicates);

                    DisplayParsedArgs(
                        "Supports positional arguments and switches, and does case sensitive parsing",
                        InvalidSwitchParser,
                        ref intTestNumber);
                }
                catch (Exception exAll)
                {
                    System.Diagnostics.Trace.WriteLine(
                        string.Format(
                            "{0}: {1}",
                            SysDateFormatters.FormatDateTimeForShow(DateTime.Now),
                            ExceptionLogger.GetTheSingleInstance().ReportException(exAll))); // Log the error with the event viewer and the trace listener(s), if any.
                }
            }                                                                                // CmdLneArgsBasic InvalidSwitchParser goes out of scope.

            //  ------------------------------------------------------------
            //  Test a CmdLneArgsBasic object that supports positional
            //  arguments and switches, including an invalid switch.
            //  ------------------------------------------------------------

            {               // Set scope boundaries around IntegerSwitchParser SwitchParser.
                try
                {
                    CmdLneArgsBasic IntegerSwitchParser = new CmdLneArgsBasic(s_achrSwitchSetAllUC);

                    DisplayParsedArgs(
                        "Supports positional arguments and switches, and does case sensitive parsing",
                        IntegerSwitchParser,
                        ref intTestNumber);
                    Console.WriteLine(
                        "    Querying switch Q with a default value of -1 returns {0}",
                        IntegerSwitchParser.GetSwitchByNameAsInt(
                            'Q',
                            -1));
                    Console.WriteLine(
                        "    Querying switch R with a default value of -1 returns {0}",
                        IntegerSwitchParser.GetSwitchByNameAsInt(
                            'S',
                            -1));
                }
                catch (Exception exAll)
                {
                    Console.WriteLine(
                        "Exception caught while constructing InvalidSwitchParser{2}    Message = {0}{2}    Method = {1}{2}",
                        exAll.Message,
                        exAll.TargetSite.Name,
                        Environment.NewLine);
                }
            }               // CmdLneArgsBasic IntegerSwitchParser goes out of scope.

            //  ------------------------------------------------------------
            //  Test a CmdLneArgsBasic object that supports positional
            //  arguments and switches. This is probably the most useful
            //  implementation for die-hard Windows programmers, because its
            //  parsing rules are case inssensitive.
            //  ------------------------------------------------------------

            {               // Set scope boundaries around CmdLneArgsBasic CaseInsensitiveSwitchParser.
                CmdLneArgsBasic CaseInsensitiveSwitchParser = new CmdLneArgsBasic(
                    s_achrSwitchSetAllUC,
                    CmdLneArgsBasic.ArgMatching.CaseInsensitive);
                DisplayParsedArgs(
                    "Supports positional arguments and switches, and does case INsensitive parsing",
                    CaseInsensitiveSwitchParser,
                    ref intTestNumber);
            }               // CmdLneArgsBasic SwitchParser goes out of scope.

            //  ------------------------------------------------------------
            //  Test a CmdLneArgsBasic object that supports all three kinds
            //  of arguments. This is the most versatile parser, period.
            //  ------------------------------------------------------------

            {               // Set scope boundaries around CmdLneArgsBasic FullyLoadedParser.
                CmdLneArgsBasic FullyLoadedParser1 = new CmdLneArgsBasic(
                    s_achrSwitchSetAllUC,
                    s_astrValidArgumentNames);
                DisplayParsedArgs(
                    "Supports named and positional arguments and switches, and does case sensitive parsing",
                    FullyLoadedParser1,
                    ref intTestNumber);

                Console.WriteLine(
                    "     GetArgByMultipleAliases, NAMED_ARG_UC_2 first = {0}",
                    FullyLoadedParser1.GetArgByMultipleAliases(
                        new string []
                {
                    NAMED_ARG_UC_2,
                    NAMED_ARG_UC_3
                }));

                //  ---------------------------------------------------------
                //  Swap preferences, and repeat.
                //  ---------------------------------------------------------

                Console.WriteLine(
                    "     GetArgByMultipleAliases, NAMED_ARG_UC_3 first = {0}",
                    FullyLoadedParser1.GetArgByMultipleAliases(
                        new string []
                {
                    NAMED_ARG_UC_3,
                    NAMED_ARG_UC_2
                }));
            }               // CmdLneArgsBasic FullyLoadedParser goes out of scope.

            //  ------------------------------------------------------------
            //  Test a CmdLneArgsBasic object that supports all three kinds
            //  of arguments, and implements case insensitive parsing. This
            //  is the most versatile parser for die-hard Window
            //  programmers.
            //  ------------------------------------------------------------

            {               // Set scope boundaries around CmdLneArgsBasic FullyLoadedWinCmdParser.
                CmdLneArgsBasic FullyLoadedWinCmdParser = new CmdLneArgsBasic(
                    s_achrSwitchSetAllUC,
                    s_astrValidArgumentNames,
                    CmdLneArgsBasic.ArgMatching.CaseInsensitive);
                DisplayParsedArgs(
                    "Supports named and positional arguments and switches, and does case INsensitive parsing",
                    FullyLoadedWinCmdParser,
                    ref intTestNumber);
            }               // CmdLneArgsBasic FullyLoadedWinCmdParser goes out of scope.

            //  ------------------------------------------------------------
            //  Finally, test a CmdLineArgs object that supports all three
            //  kinds of arguments, and takes its lists of supported named
            //  arguments and switches from dictionaries of names and
            //  defaults. By making this object do  case sensitive parsing
            //  we get the default for the third named argument, as was the
            //  case in the next to last test above.
            //  ------------------------------------------------------------

            {               // Set scope boundaries around CmdLneArgsBasic FullyLoadedParser2.
                Dictionary <string, string> dctNamedArgsWithDefaults = CreateNamedArgListWithDefaults( );
                Dictionary <char, string>   dctSwitchesWithDefaults  = CreateSwitchListWithDefaults( );

                CmdLneArgsBasic FullyLoadedParser2 = new CmdLneArgsBasic(
                    dctSwitchesWithDefaults,
                    dctNamedArgsWithDefaults);
                DisplayParsedArgs(
                    "Supports named and positional arguments and switches WITH DEFAULTS, and does case sensitive parsing",
                    FullyLoadedParser2,
                    ref intTestNumber);
            }           // CmdLneArgsBasic FullyLoadedParser2 goes out of scope.
        }               // internal static void Go