Exemplo n.º 1
0
        /// <inheritdoc/>
        public override void Handle(AppCommandRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.Command.ToLower(new CultureInfo("en-US")) == "purge")
            {
                if (request.Parameters == "-h" || request.Parameters == "--help")
                {
                    Console.WriteLine("\t'purge' - remove records marked as deleted from file.\n\tDoes not require any additional parameters.");
                }
                else if (string.IsNullOrEmpty(request.Parameters))
                {
                    Purge();
                }
                else
                {
                    Console.WriteLine("This command does not accept parameters.");
                }
            }
            else
            {
                base.Handle(request);
            }
        }
Exemplo n.º 2
0
        /// <inheritdoc/>
        public override void Handle(AppCommandRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.Command.ToLower(new CultureInfo("en-US")) == "delete")
            {
                if (request.Parameters == "-h" || request.Parameters == "--help")
                {
                    Console.WriteLine("\t'delete' - deletes record(s) that match the search criteria.\n\tCommand format: delete where [fieldName]=[value] and [fieldName]=[value]\n\tSearch criteria support the 'and' operator for more accurate record search.");
                }
                else
                {
                    try
                    {
                        Delete(request.Parameters);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        Console.WriteLine("No records with this ID");
                    }
                }
            }
            else
            {
                base.Handle(request);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Handles the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>
        /// Class AppCommandRequest Instance.
        /// </returns>
        public override AppCommandRequest Handle(AppCommandRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            write($"'{request.Command}' is not a command. See 'help'.");
            List <string> similarCommands = new List <string>();

            foreach (var command in this.commandList)
            {
                int result = GetDamerauLevenshteinDistance(request.Command, command);
                if (result < 3)
                {
                    similarCommands.Add(command);
                }
            }

            if (similarCommands.Count == 1)
            {
                write("The most similar commands is");
                write($"\t\t{similarCommands[0]}");
            }
            else if (similarCommands.Count > 1)
            {
                write("The most similar commands are");
                foreach (var command in similarCommands)
                {
                    write($"\t\t{command}");
                }
            }

            return(null);
        }
Exemplo n.º 4
0
        /// <inheritdoc/>
        public override void Handle(AppCommandRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.Command.ToLower(new CultureInfo("en-US")) == "select")
            {
                if (request.Parameters == "-h" || request.Parameters == "--help")
                {
                    Console.WriteLine("\t'select' - outputs a table of selected record fields found with the specified search criteria.\n\tCommand format: select [field1],[field2]...[fieldN] where [fieldName]=[value] and [fieldName]=[value] or [fieldName]=[value]\n\tIf no specific fields are specified for output, it outputs the entire record.\n\tIf no output fields and search criteria, it outputs all records.\n\tSearch criteria support the use of the 'and' and 'or' operators.");
                }
                else
                {
                    try
                    {
                        this.Select(request.Parameters);
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Incorrect parameter(s) format.");
                    }
                }
            }
            else
            {
                base.Handle(request);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Handles command line request.
        /// </summary>
        /// <param name="commandRequest">Command line request.</param>
        public virtual void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                return;
            }

            if (this.commandHandler != null)
            {
                this.commandHandler.Handle(commandRequest);
            }
            else
            {
                IEnumerable <string> similarCommands = this.GetSimilarCommands(commandRequest.Command);
                if (!similarCommands.Any())
                {
                    Console.WriteLine($"Command {commandRequest.Command} doesn't exist.");
                }
                else if (similarCommands.Count() == 1)
                {
                    Console.WriteLine($"Command {commandRequest.Command} doesn't exist.");
                    Console.WriteLine($"The most similar command is '{similarCommands.First()}'");
                }
                else
                {
                    Console.WriteLine($"Command {commandRequest.Command} doesn't exist.");
                    Console.WriteLine(Configurator.GetConstantString("SimilarCommands"));
                    foreach (string command in similarCommands)
                    {
                        Console.WriteLine(command);
                    }
                }
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Стандартный обработчик.
 /// </summary>
 /// <param name="request">Запрос.</param>
 public override void Handle(AppCommandRequest request)
 {
     if (request != null)
     {
         PrintMissedCommandInfo(request.Command);
     }
 }
        /// <summary>Handles the specified request.</summary>
        /// <param name="request">The request.</param>
        public override void Handle(AppCommandRequest request)
        {
            if (request != null && !request.Command.Equals("help", StringComparison.InvariantCultureIgnoreCase))
            {
                this.NextHandler.Handle(request);
                return;
            }

            if (request != null && !string.IsNullOrEmpty(request.Parameters))
            {
                var index = Array.FindIndex(HelpMessages, 0, HelpMessages.Length, i => string.Equals(i[CommandHelpIndex], request.Parameters, StringComparison.InvariantCultureIgnoreCase));
                Console.WriteLine(index >= 0
                    ? HelpMessages[index][ExplanationHelpIndex]
                    : $"There is no explanation for '{request.Parameters}' command.");
            }
            else
            {
                Console.WriteLine("Available commands:");

                foreach (var helpMessage in HelpMessages)
                {
                    Console.WriteLine("\t{0}\t- {1}", helpMessage[CommandHelpIndex], helpMessage[DescriptionHelpIndex]);
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 8
0
        /// <inheritdoc/>
        public override void Handle(AppCommandRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.Command.ToLower(new CultureInfo("en-US")) == "exit")
            {
                if (request.Parameters == "-h" || request.Parameters == "--help")
                {
                    Console.WriteLine("\t'exit' - stops the application.\n\tDoes not require any additional parameters.");
                }
                else if (string.IsNullOrEmpty(request.Parameters))
                {
                    Exit();
                }
                else
                {
                    Console.WriteLine("This command does not accept parameters.");
                }
            }
            else
            {
                base.Handle(request);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Handles command line request.
        /// </summary>
        /// <param name="commandRequest">Command line request.</param>
        public override void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidCommand"));
                return;
            }

            if (commandRequest.Command is null)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidCommand"));
                return;
            }

            if (commandRequest.Command.Equals(Configurator.GetConstantString("CommandUpdate"), StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    Console.WriteLine($"{this.Update(commandRequest.Parameters)} records were updated.");
                    this.Service.ClearCache();
                }
                catch (ArgumentException)
                {
                    Console.WriteLine(Configurator.GetConstantString("InvalidInput"));
                    Console.WriteLine(Configurator.GetConstantString("CommandPatthern"));
                    Console.WriteLine(Configurator.GetConstantString("UpdatePatthern"));
                }
            }
            else
            {
                base.Handle(commandRequest);
            }
        }
Exemplo n.º 10
0
        private static void PrintMissedCommandInfo(AppCommandRequest request)
        {
            Console.WriteLine($"There is no '{request.Command}' command.");
            var simalarCommands = GetMostSimilarCommands(request);

            PrintMostSimilarCommands(simalarCommands);
            Console.WriteLine();
        }
Exemplo n.º 11
0
        /// <inheritdoc/>
        public override void Handle(AppCommandRequest appCommandRequest)
        {
            if (appCommandRequest == null)
            {
                throw new ArgumentNullException(nameof(appCommandRequest));
            }

            PrintMissedCommandInfo(appCommandRequest.Command);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Executes the command.
        /// </summary>
        /// <param name="command">Command info.</param>
        public override void Handle(AppCommandRequest command)
        {
            if (this.GoToNextCommand(command))
            {
                return;
            }

            if (command is null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            if (!command.Parameters.Contains("values", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            string[] splitParameters = command.Parameters.Split("values", 2);
            if (splitParameters.Length != 2)
            {
                throw new ArgumentException("Invalid parameters.");
            }

            int indexForNameProperties  = 0;
            int indexForValueProperties = 1;
            Dictionary <PropertyInfo, object> properties;

            try
            {
                string[] nameProperties  = SplitBrackets(splitParameters[indexForNameProperties]);
                string[] valueProperties = SplitBrackets(splitParameters[indexForValueProperties]);
                properties = ParseParameters(nameProperties, valueProperties);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            DataRecord dataRecord = new DataRecord();

            foreach (var property in properties.Keys)
            {
                object value = properties[property];
                typeof(DataRecord).GetProperty(property.Name).SetValue(dataRecord, value);
            }

            try
            {
                this.service.CreateRecord(dataRecord);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// handles the specified request.
        /// </summary>
        /// <param name="request">Input handle.</param>
        /// <returns>AppCommandRequest instance.</returns>
        public override AppCommandRequest Handle(AppCommandRequest request)
        {
            if (request == null)
            {
                throw new ArgumentException($"The {nameof(request)} is null");
            }

            PrintMissedCommandInfo(request);
            return(null);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Exit from programm.
        /// </summary>
        /// <param name="command">Parameters command.</param>
        public override void Handle(AppCommandRequest command)
        {
            if (this.GoToNextCommand(command))
            {
                return;
            }

            Console.WriteLine("Exiting an application...");
            this.changeStatus(false);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Handle the given request.
        /// </summary>
        /// <param name="commandRequest">The command request.</param>
        public virtual void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                throw new ArgumentNullException($"{nameof(commandRequest)} cannot be null.");
            }

            if (!(this.commandHandler is null))
            {
                this.commandHandler.Handle(commandRequest);
            }
Exemplo n.º 16
0
 /// <summary>
 /// Handles the request.
 /// </summary>
 /// <param name="request">Request to handle.</param>
 /// <returns>The object back, or null otherwise.</returns>
 public virtual object Handle(AppCommandRequest request)
 {
     if (this.nextHandler != null)
     {
         return(this.nextHandler.Handle(request));
     }
     else
     {
         return(null);
     }
 }
Exemplo n.º 17
0
 /// <inheritdoc/>
 public virtual void Handle(AppCommandRequest request)
 {
     if (this.nextHandler != null)
     {
         this.nextHandler.Handle(request);
     }
     else
     {
         return;
     }
 }
        /// <summary>
        /// Prints statistics.
        /// </summary>
        /// <param name="command">Parameters command.</param>
        public override void Handle(AppCommandRequest command)
        {
            if (this.GoToNextCommand(command))
            {
                return;
            }

            var recordsCount   = this.service.GetCount();
            var recordsRemoved = this.service.GetCountRemovedRecords();

            Console.WriteLine($"{recordsCount} record(s). {recordsRemoved} removed record(s).");
        }
Exemplo n.º 19
0
        /// <summary>
        /// Defragments a file.
        /// </summary>
        /// <param name="command">Parameters of command.</param>
        public override void Handle(AppCommandRequest command)
        {
            if (this.GoToNextCommand(command))
            {
                return;
            }

            int count   = this.service.GetCount();
            int removed = this.service.Purge();

            Console.WriteLine($"Data file processing is completed: {removed} of {count}");
        }
        /// <summary>
        /// Handles command line request.
        /// </summary>
        /// <param name="commandRequest">Command line request.</param>
        public override void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidCommand"));
                return;
            }

            if (commandRequest.Command is null)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidCommand"));
                return;
            }

            if (commandRequest.Command.Equals(Configurator.GetConstantString("CommandSelect"), StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    string[] memoization = this.GetMemoizationKey(commandRequest.Parameters);
                    string   oldResult   = this.Service.GetCache(memoization);
                    if (oldResult != null)
                    {
                        Console.WriteLine(oldResult);
                    }
                    else
                    {
                        string result = null;
                        if (string.IsNullOrEmpty(commandRequest.Parameters.Trim()))
                        {
                            result = this.SelectAll();
                        }
                        else
                        {
                            result = this.Select(commandRequest.Parameters);
                        }

                        memoization[8] = result;
                        this.Service.SaveInCache(memoization);
                        Console.WriteLine(result);
                    }
                }
                catch (ArgumentException)
                {
                    Console.WriteLine(Configurator.GetConstantString("InvalidInput"));
                    Console.WriteLine(Configurator.GetConstantString("CommandPatthern"));
                    Console.WriteLine(Configurator.GetConstantString("SelectPatthern"));
                }
            }
            else
            {
                base.Handle(commandRequest);
            }
        }
        /// <summary>Handles the specified request.</summary>
        /// <param name="request">The request.</param>
        public override void Handle(AppCommandRequest request)
        {
            if (request != null && !request.Command.Equals("exit", StringComparison.InvariantCultureIgnoreCase))
            {
                this.NextHandler.Handle(request);
                return;
            }

            #pragma warning disable CA1303 // Do not pass literals as localized parameters
            Console.WriteLine("Exiting an application...");
            #pragma warning restore CA1303 // Do not pass literals as localized parameters
            this.close?.Invoke(false);
        }
Exemplo n.º 22
0
        private static IEnumerable <string> GetMostSimilarCommands(AppCommandRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var requestCommandSymbols = request.Command.ToUpperInvariant();
            var commandsIntersactions = commands.Select(command => (command, command.ToUpperInvariant()))
                                        .Select(commandTuple => (commandTuple.command, commandTuple.Item2.Intersect(requestCommandSymbols).Count()));
            var max = commandsIntersactions.Max(tuple => tuple.Item2);

            return(max > 2 ? commandsIntersactions.Where(tuple => tuple.Item2.Equals(max)).Select(tuple => tuple.command) : Enumerable.Empty <string>());
        }
Exemplo n.º 23
0
 /// <summary>
 /// Обработчкик команды поиска.
 /// </summary>
 /// <param name="request">Запрос.</param>
 public override void Handle(AppCommandRequest request)
 {
     if (request != null)
     {
         if (request.Command.Equals("Find", comparisonType: StringComparison.InvariantCultureIgnoreCase))
         {
             this.Find(request.Parameters);
         }
         else
         {
             this.nextHandler.Handle(request);
         }
     }
 }
Exemplo n.º 24
0
        /// <summary>Handles the specified request.</summary>
        /// <param name="request">The request.</param>
        public override void Handle(AppCommandRequest request)
        {
            if (request != null && !request.Command.Equals("import", StringComparison.InvariantCultureIgnoreCase))
            {
                this.NextHandler.Handle(request);
                return;
            }

            if (request != null)
            {
                string[] parametersArray = request.Parameters.Split(' ');
                string   formatName      = parametersArray[0];
                string   path            = parametersArray[1];
                try
                {
                    if (formatName.Equals("csv", StringComparison.InvariantCultureIgnoreCase))
                    {
                        using (StreamReader sr = new StreamReader(new FileStream(path, FileMode.Open)))
                        {
                            FileCabinetServiceSnapshot snapshot = this.service.MakeSnapshot();
                            snapshot.LoadFromCsv(sr);
                            this.service.Restore(snapshot);
                            sr.Close();
                        }

                        Console.WriteLine("All records were imported.");
                    }

                    if (formatName.Equals("xml", StringComparison.InvariantCultureIgnoreCase))
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Open))
                        {
                            FileCabinetServiceSnapshot snapshot = this.service.MakeSnapshot();
                            snapshot.LoadFromXml(fs);
                            this.service.Restore(snapshot);
                            fs.Close();
                        }

                        Console.WriteLine("All records were imported.");
                    }
                }
                #pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
                #pragma warning restore CA1031 // Do not catch general exception types
                {
                    Console.WriteLine("Import failed: " + ex.Message);
                }
            }
        }
        /// <summary>
        /// Executes the command.
        /// </summary>
        /// <param name="command">Command info.</param>
        public override void Handle(AppCommandRequest command)
        {
            if (command is null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            if (this.GoToNextCommand(command))
            {
                return;
            }

            string parameters = command.Parameters;

            if (!parameters.StartsWith("where", StringComparison.InvariantCultureIgnoreCase))
            {
                Console.WriteLine("Invalid format. Doesn't start with where.");
                return;
            }

            parameters = parameters.Remove(0, 5);
            string[] nameProperties, valueProperties;

            Dictionary <PropertyInfo, object> properties;
            IEnumerable <FileCabinetRecord>   records;
            string separator = "and";

            try
            {
                (nameProperties, valueProperties) = SplitParameters(parameters, separator);
                properties = ParseParameters(nameProperties, valueProperties);
                records    = this.FindRecords(properties);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            List <int> ids = new List <int>();

            foreach (var record in records)
            {
                ids.Add(record.Id);
                this.service.Remove(record.Id);
            }

            Console.WriteLine(GetMessage(ids));
        }
        /// <summary>
        /// Create request handler.
        /// </summary>
        /// <param name="commandRequest">Request.</param>
        public override void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                throw new ArgumentNullException(nameof(commandRequest), "CommandRequest can't be null.");
            }

            if (commandRequest.Command == "INSERT")
            {
                this.Insert(commandRequest.Parameters);
            }
            else
            {
                base.Handle(commandRequest);
            }
        }
Exemplo n.º 27
0
        /// <inheritdoc/>
        public override void Handle(AppCommandRequest appCommandRequest)
        {
            if (appCommandRequest == null)
            {
                throw new ArgumentNullException(nameof(appCommandRequest));
            }

            if (appCommandRequest.Command.Equals(Command, StringComparison.InvariantCultureIgnoreCase))
            {
                this.Exit(appCommandRequest.Parameters);
            }
            else
            {
                this.nextHandler.Handle(appCommandRequest);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Handles the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>
        /// Class AppCommandRequest Instance.
        /// </returns>
        public virtual AppCommandRequest Handle(AppCommandRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (this.nextHandler != null)
            {
                return(this.nextHandler.Handle(request));
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Handles the specified command request.
        /// </summary>
        /// <param name="commandRequest">The command request.</param>
        /// <exception cref="ArgumentNullException">Throws when commandRequest is null.</exception>
        public override void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                throw new ArgumentNullException(nameof(commandRequest));
            }

            if (commandRequest.Command.ToUpperInvariant() != "EXIT")
            {
                this.NextHandler.Handle(commandRequest);
                return;
            }

            Console.WriteLine("Exiting an application...");
            this.isRunning(false);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Handle request.
        /// </summary>
        /// <param name="commandRequest">The command request.</param>
        public override void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                throw new ArgumentNullException($"{nameof(commandRequest)} cannot be null.");
            }

            if (string.Equals(commandRequest.Commands, HelpConstant, StringComparison.OrdinalIgnoreCase))
            {
                Help(commandRequest.Parameters);
            }
            else
            {
                base.Handle(commandRequest);
            }
        }