Пример #1
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);
                }
            }
        }
        private void Import(string parameters)
        {
            if (parameters.Split(' ').Length < 2)
            {
                Console.WriteLine("Type type and path to export file.");
                return;
            }

            string[] values        = parameters.Split(' ', 2);
            string   pathDirectory = string.Empty;

            if (values[0].Equals("csv", StringComparison.InvariantCultureIgnoreCase))
            {
                if (File.Exists(values[1]))
                {
                    using (FileStream fs = new FileStream(values[1], FileMode.Open))
                    {
                        List <FileCabinetRecord>   list = new List <FileCabinetRecord>();
                        FileCabinetServiceSnapshot snap = new FileCabinetServiceSnapshot(list);
                        snap.LoadFromCsv(fs);
                        this.service.Restore(snap);
                        Console.WriteLine($"Notes has been imported from {values[1]}.");
                    }
                }
                else
                {
                    Console.WriteLine("File not exists");
                }
            }
            else if (values[0].Equals("xml", StringComparison.InvariantCultureIgnoreCase))
            {
                if (File.Exists(values[1]))
                {
                    using (FileStream fs = new FileStream(values[1], FileMode.Open))
                    {
                        List <FileCabinetRecord>   list = new List <FileCabinetRecord>();
                        FileCabinetServiceSnapshot snap = new FileCabinetServiceSnapshot(list);
                        snap.LoadFromXml(fs);
                        this.service.Restore(snap);
                        Console.WriteLine($"Notes has been imported from {values[1]}.");
                    }
                }
                else
                {
                    Console.WriteLine("File not exists");
                }
            }
        }
        /// <summary>
        /// Imports the records from csv or xml file.
        /// </summary>
        /// <param name="parameters">Format to write in and path to write to.</param>
        private void Import(string parameters)
        {
            string[] args = parameters.Split();
            if (args == null || args.Length < 2)
            {
                Console.WriteLine("Incorrect parameters.");
                return;
            }

            string format = args[0].ToLower();
            string path   = args[1];

            if (!File.Exists(path))
            {
                Console.WriteLine("Import error: " + path + " does not exist");
                return;
            }

            using (StreamReader reader = new StreamReader(path))
            {
                int importedRecords = 0;
                IList <FileCabinetRecord>   records;
                IFileCabinetServiceSnapshot snapshot = new FileCabinetServiceSnapshot();
                switch (format)
                {
                case "csv":
                    records         = snapshot.LoadFromCsv(reader);
                    snapshot        = new FileCabinetServiceSnapshot(records);
                    importedRecords = this.Service.Restore(snapshot);
                    break;

                case "xml":
                    records         = snapshot.LoadFromXml(reader);
                    snapshot        = new FileCabinetServiceSnapshot(records);
                    importedRecords = this.Service.Restore(snapshot);
                    break;

                default:
                    Console.WriteLine("Incorrect format: can be xml or csv.");
                    return;
                }

                Console.WriteLine(importedRecords + " records were imported from " + path + ".");
            }
        }
Пример #4
0
 private static void ImportFromXml(string path)
 {
     try
     {
         using (StreamReader reader = new StreamReader(path))
         {
             FileCabinetServiceSnapshot snapshot = new FileCabinetServiceSnapshot();
             snapshot.LoadFromXml(reader);
             fileCabinetService.Restore(snapshot);
         }
     }
     catch (Exception ex) when(
         ex is ArgumentException || ex is NotSupportedException || ex is FileNotFoundException || ex is IOException ||
         ex is System.Security.SecurityException || ex is DirectoryNotFoundException || ex is UnauthorizedAccessException ||
         ex is PathTooLongException)
     {
         Console.WriteLine($"Import failed: can't open file {path}.");
     }
 }
Пример #5
0
        /// <inheritdoc/>
        protected override void Make(AppCommandRequest commandRequest)
        {
            (string format, string fileName) = CommandHandleBase.SplitParam(commandRequest.Parameters);
            if (!File.Exists(fileName))
            {
                Console.WriteLine($"File \"{fileName}\"is not exist.");
                return;
            }

            FileStream fileStream;

            try
            {
                fileStream = File.OpenRead(fileName);
            }
            catch (Exception)
            {
                Console.WriteLine("Can't open file");
                return;
            }

            int count    = 0;
            var snapshot = new FileCabinetServiceSnapshot();

            switch (format)
            {
            case "csv":
                snapshot.LoadFromCSV(fileStream);
                count = this.Service.Restore(snapshot);
                break;

            case "xml":
                snapshot.LoadFromXml(fileStream);
                count = this.Service.Restore(snapshot);
                break;

            default:
                Console.WriteLine("Format is not supported.");
                break;
            }

            Console.WriteLine($"{count} records were imported from {fileName}.");
        }
        private void Import(string parameters)
        {
            string[] parametersArr = parameters.Split(' ', 2);
            if (parametersArr.Length < 2)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidInput"));
                Console.WriteLine(Configurator.GetConstantString("CommandPatthern"));
                Console.WriteLine(Configurator.GetConstantString("ImportPatthern"));
                return;
            }

            const int importTypeIndex = 0;
            const int filePathIndex   = 1;

            if (!File.Exists(parametersArr[filePathIndex]))
            {
                Console.WriteLine($"File {parametersArr[filePathIndex]} isn't exist.");
                return;
            }

            FileCabinetServiceSnapshot snapshot = new FileCabinetServiceSnapshot();

            if (parametersArr[importTypeIndex].Equals(Configurator.GetConstantString("CsvType"), StringComparison.OrdinalIgnoreCase))
            {
                using StreamReader fileStream = new StreamReader(parametersArr[filePathIndex]);
                snapshot.LoadFromCsv(fileStream);
                int numberOfImported = this.Service.Restore(snapshot);
                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} records were imported from {1}", numberOfImported, parametersArr[filePathIndex]));
            }
            else if (parametersArr[importTypeIndex].Equals(Configurator.GetConstantString("XmlType"), StringComparison.OrdinalIgnoreCase))
            {
                using StreamReader fileStream = new StreamReader(parametersArr[filePathIndex]);
                using XmlReader xmlReader     = XmlReader.Create(fileStream);
                snapshot.LoadFromXml(xmlReader);
                int numberOfImported = this.Service.Restore(snapshot);
                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} records were imported from {1}", numberOfImported, parametersArr[filePathIndex]));
            }
            else
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidFormatType"));
            }
        }
        private void ImportXml(string path)
        {
            var snapshot = new FileCabinetServiceSnapshot(Array.Empty <FileCabinetRecord>());

            try
            {
                using (var stream = File.Open(@path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (var st = new StreamReader(stream))
                    {
                        snapshot.LoadFromXml(st);
                    }
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine($"Import error: file {path} not exist");
            }

            int completed = this.fileCabinetService.Restore(snapshot);

            Console.WriteLine($"{completed} recordses were imported from {path}");
        }
Пример #8
0
        private void Import(string parameters)
        {
            const string xml = "xml";
            const string csv = "csv";

            try
            {
                var parameterArray = parameters.Split(' ', StringSplitOptions.RemoveEmptyEntries);
                if (parameterArray.Length != 2)
                {
                    throw new ArgumentException("You did not specify the type of file to export or the path to export");
                }

                var fullPath      = parameterArray.Last();
                var nameFile      = Path.GetFileName(fullPath);
                var extensionFile = Path.GetExtension(nameFile).TrimStart('.');
                var typeFile      = parameterArray.First();
                if (!string.Equals(typeFile, xml, StringComparison.OrdinalIgnoreCase) && !string.Equals(typeFile, csv, StringComparison.OrdinalIgnoreCase))
                {
                    bool rezult = false;
                    do
                    {
                        Console.Write("Please, input correct type of file: ");
                        typeFile = Console.ReadLine();
                        rezult   = string.Equals(typeFile, xml, StringComparison.OrdinalIgnoreCase) || string.Equals(typeFile, csv, StringComparison.OrdinalIgnoreCase);
                    }while (rezult == false);
                }

                if (typeFile != extensionFile)
                {
                    throw new ArgumentException($"You want to import data from a {nameFile}, but you specified the type {typeFile}");
                }

                if (File.Exists(fullPath))
                {
                    snapshot = this.service.MakeSnapshot();
                    if (string.Equals(csv, typeFile, StringComparison.OrdinalIgnoreCase))
                    {
                        using (var fileStream = File.Open(nameFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            snapshot.LoadFromCsv(fileStream);
                            Console.WriteLine($"{snapshot.ListFromFile.Count} records were imported from {fullPath}");
                            this.service.Restore(snapshot);
                        }
                    }
                    else if (string.Equals(xml, typeFile, StringComparison.OrdinalIgnoreCase))
                    {
                        using (var fileStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            snapshot.LoadFromXml(fileStream);
                            Console.WriteLine($"{snapshot.ListFromFile.Count} records were imported from {fullPath}");
                            this.service.Restore(snapshot);
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"Import error: {fullPath} is not exist.");
                }
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("Enter the file extension and his name or path");
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #9
0
        private void Import(string parameters)
        {
            if (string.IsNullOrWhiteSpace(parameters))
            {
                Console.WriteLine("Enter export parameters.");
                return;
            }

            var    splittedParameters = parameters.Split(SpaceSymbol, NumberOfParameters, StringSplitOptions.RemoveEmptyEntries);
            string typeOfFile;
            string filePath;

            try
            {
                typeOfFile = splittedParameters[FirstElementIndex];
                filePath   = splittedParameters[SecondElementIndex].Trim(QuoteSymbol);
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("Invalid number of parameters.");
                return;
            }

            if (!File.Exists(filePath))
            {
                Console.WriteLine($"Import error: file {filePath} is not exist.");
                return;
            }

            if (typeOfFile.Equals(CsvFileExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                using var reader = new StreamReader(filePath, Encoding.Unicode);
                var snapshot = new FileCabinetServiceSnapshot();
                try
                {
                    snapshot.LoadFromCsv(reader, this.fileCabinetService.Validator);
                }
                catch (FormatException)
                {
                    Console.WriteLine("One of the record's properties has invalid format.");
                    return;
                }
                catch (IndexOutOfRangeException)
                {
                    Console.WriteLine("One of the record's has invalid number of properties.");
                    return;
                }

                foreach (var record in snapshot.InvalidRecords)
                {
                    Console.WriteLine($"Record #{record.Item1.Id} was skipped: {record.Item2}");
                }

                this.fileCabinetService.Restore(snapshot);
                Console.WriteLine($"{snapshot.Records.Count} records were imported.");
            }
            else if (typeOfFile.Equals(XmlFileExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                using var reader = XmlReader.Create(filePath);
                var snapshot = new FileCabinetServiceSnapshot();
                try
                {
                    snapshot.LoadFromXml(reader, this.fileCabinetService.Validator);
                }
                catch (InvalidOperationException)
                {
                    Console.WriteLine("One of the record's properties has invalid format.");
                    return;
                }

                foreach (var record in snapshot.InvalidRecords)
                {
                    Console.WriteLine($"Record #{record.Item1.Id} was skipped: {record.Item2}");
                }

                this.fileCabinetService.Restore(snapshot);
                Console.WriteLine($"{snapshot.Records.Count} records were imported.");
            }
            else
            {
                Console.WriteLine("Invalid type of file.");
                return;
            }
        }
        /// <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() != "IMPORT")
            {
                this.NextHandler.Handle(commandRequest);
                return;
            }

            string[] param = commandRequest.Parameters.Split(' ');

            if (param.Length != 2)
            {
                Console.WriteLine("Invalid number of parameters");
                return;
            }

            if (string.IsNullOrWhiteSpace(param[0]) || string.IsNullOrWhiteSpace(param[1]))
            {
                Console.WriteLine("Invalid parameters");
                return;
            }

            FileStream fileStream = null;

            try
            {
                fileStream = new FileStream(param[1], FileMode.Open);
            }
            catch (IOException)
            {
                fileStream?.Close();
                Console.WriteLine("Import failed: can't open file {0}", param[1]);
                return;
            }
            catch (UnauthorizedAccessException)
            {
                return;
            }

            FileCabinetServiceSnapshot serviceSnapshot = new FileCabinetServiceSnapshot();

            try
            {
                if (param[0].ToUpperInvariant() == "CSV")
                {
                    serviceSnapshot.LoadFromCsv(new StreamReader(fileStream, leaveOpen: true));
                    this.Service.Restore(serviceSnapshot);
                    Console.WriteLine("records were imported from {0}", param[1]);
                }

                if (param[0].ToUpperInvariant() == "XML")
                {
                    serviceSnapshot.LoadFromXml(new StreamReader(fileStream, leaveOpen: true));
                    this.Service.Restore(serviceSnapshot);
                    Console.WriteLine("records were imported from {0}", param[1]);
                }

                this.Service.MemEntity.Clear();
            }
            catch (FormatException)
            {
                Console.WriteLine("Not correct format.");
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine("Not correct format.");
            }

            fileStream.Close();
        }
Пример #11
0
        private void Import(string parameters)
        {
            if (parameters == null)
            {
                Console.WriteLine(Source.Resource.GetString("exportArgumentsException", CultureInfo.InvariantCulture));
                Console.WriteLine(Source.Resource.GetString("exportFormat", CultureInfo.InvariantCulture));
                return;
            }

            var arguments = parameters.Split(' ');

            if (arguments.Length == 1)
            {
                Console.WriteLine(Source.Resource.GetString("importArgumentsException", CultureInfo.InvariantCulture));
                Console.WriteLine(Source.Resource.GetString("importFormat", CultureInfo.InvariantCulture));
                return;
            }
            else if (arguments.Length == 2)
            {
                const int typeIndex = 0;
                const int pathIndex = 1;

                var snapshot = new FileCabinetServiceSnapshot();

                if (arguments[typeIndex].Equals("csv", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (!File.Exists(arguments[pathIndex]))
                    {
                        Console.WriteLine(Source.Resource.GetString("fileNotFound", CultureInfo.InvariantCulture));
                        return;
                    }

                    using (var fileStream = new StreamReader(arguments[pathIndex]))
                    {
                        try
                        {
                            snapshot.LoadFromCsv(fileStream);
                            int numberOfStored = this.Service.Restore(snapshot);
                            Console.WriteLine(Source.Resource.GetString("importFileComplete", CultureInfo.InvariantCulture), numberOfStored, arguments[pathIndex]);
                        }
                        catch (ArgumentNullException)
                        {
                            Console.WriteLine(Source.Resource.GetString("importFailed", CultureInfo.InvariantCulture));
                        }
                    }
                }
                else if (arguments[typeIndex].Equals("xml", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (!File.Exists(arguments[pathIndex]))
                    {
                        Console.WriteLine(Source.Resource.GetString("fileNotFound", CultureInfo.InvariantCulture));
                        return;
                    }

                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent      = true;
                    settings.IndentChars = "\t";

                    using (var fileStream = new StreamReader(arguments[pathIndex]))
                        using (var xmlReader = XmlReader.Create(fileStream))
                        {
                            snapshot.LoadFromXml(xmlReader);
                            int numberOfImported = this.Service.Restore(snapshot);
                            Console.WriteLine(Source.Resource.GetString("importFileComplete", CultureInfo.InvariantCulture), numberOfImported, arguments[pathIndex]);
                        }
                }
                else
                {
                    Console.WriteLine(Source.Resource.GetString("importUnknownFormat", CultureInfo.InvariantCulture), arguments[typeIndex]);
                }
            }
            else
            {
                Console.WriteLine(Source.Resource.GetString("importUnknownArgument", CultureInfo.InvariantCulture), arguments[2]);
            }
        }