Beispiel #1
0
        /// <summary>
        /// Управлять службой
        /// </summary>
        public bool ControlService(ServiceApp serviceApp, ServiceCommand command)
        {
            try
            {
                string batchFileName = Path.Combine(Settings.Directory,
                                                    DirectoryBuilder.GetDirectory(serviceApp), GetServiceBatchFile(command));

                if (File.Exists(batchFileName))
                {
                    Process.Start(new ProcessStartInfo()
                    {
                        FileName        = batchFileName,
                        UseShellExecute = false
                    });
                    return(true);
                }
                else
                {
                    log.WriteError(string.Format(Localization.UseRussian ?
                                                 "Не найден файл для управления службой {0}" :
                                                 "File {0} for service control not found", batchFileName));
                    return(false);
                }
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Localization.UseRussian ?
                                   "Ошибка при управлении службой" :
                                   "Error controlling service");
                return(false);
            }
        }
Beispiel #2
0
    /// <summary>
    /// Creates a temporary directory from a retrieval method. Sets missing properties in the process.
    /// </summary>
    /// <param name="retrievalMethod">The retrieval method.</param>
    /// <param name="handler">A callback object used when the the user is to be informed about progress.</param>
    /// <param name="localPath">An optional local file path where the <paramref name="retrievalMethod"/> has already been downloaded. Leave <c>null</c> to download automatically.</param>
    /// <returns>A temporary directory built using the retrieval method.</returns>
    /// <exception cref="OperationCanceledException">The user canceled the task.</exception>
    /// <exception cref="WebException">A file could not be downloaded from the internet.</exception>
    /// <exception cref="IOException">There is a problem writing a temporary file.</exception>
    /// <exception cref="UnauthorizedAccessException">Write access to a temporary file is not permitted.</exception>
    public static TemporaryDirectory ToTempDir(this DownloadRetrievalMethod retrievalMethod, ITaskHandler handler, string?localPath = null)
    {
        #region Sanity checks
        if (retrievalMethod == null)
        {
            throw new ArgumentNullException(nameof(retrievalMethod));
        }
        if (handler == null)
        {
            throw new ArgumentNullException(nameof(handler));
        }
        #endregion

        var tempDir = new TemporaryDirectory("0publish");
        try
        {
            var builder = new DirectoryBuilder(tempDir);
            builder.Add(retrievalMethod, new SimpleCommandExecutor(), handler, localPath);
            return(tempDir);
        }
        catch
        {
            tempDir.Dispose();
            throw;
        }
    }
        public void Can_Create_Correctly()
        {
            var temp     = Path.GetTempPath();
            var guid     = Guid.NewGuid().ToString();
            var tempPath = Path.Combine(temp, guid).TrimEnd('/');

            try
            {
                var builder = new DirectoryBuilder(tempPath, true)
                              .AddFile("file1.txt")
                              .AddSubdirectoryAndEnter("dir1")
                              .AddFile("file11.txt")
                              .GoBack();

                builder.Create();

                Assert.True(File.Exists(Path.Combine(tempPath, "file1.txt")));
                Assert.True(Directory.Exists(Path.Combine(tempPath, "dir1")));
                Assert.True(File.Exists(Path.Combine(tempPath, "dir1//file11.txt")));
            }
            finally
            {
                Directory.Delete(tempPath, true);
            }
        }
Beispiel #4
0
        public void build_new_path_with_hour_name()
        {
            _mediaFileInfo.ModifiedDate = new DateTime(1, 1, 1, 15, 0, 0);
            var newPath = DirectoryBuilder.BuildNewPathByDate(_mediaFileInfo, DateInterval.Hour);

            newPath.Should().Be(@"x:\3 PM\test.jpg");
        }
Beispiel #5
0
        /// <summary>
        /// Получить доступные части конфигурации
        /// </summary>
        public bool GetAvailableConfig(out ConfigParts configParts)
        {
            try
            {
                configParts = ConfigParts.None;

                foreach (ConfigParts configPart in AllConfigParts)
                {
                    if (Directory.Exists(Path.Combine(Settings.Directory, DirectoryBuilder.GetDirectory(configPart))))
                    {
                        configParts |= configPart;
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Localization.UseRussian ?
                                   "Ошибка при получении доступных частей конфигурации" :
                                   "Error getting available parts of the configuration");
                configParts = ConfigParts.None;
                return(false);
            }
        }
Beispiel #6
0
 /// <summary>
 /// Упаковать директорию
 /// </summary>
 private void PackDir(ZipArchive zipArchive, RelPath relPath, PathDict ignoredPathDict)
 {
     PackDir(zipArchive,
             GetAbsPath(relPath),
             DirectoryBuilder.GetDirectory(relPath.ConfigPart, relPath.AppFolder, '/'),
             ignoredPathDict.GetOrAdd(relPath.ConfigPart, relPath.AppFolder));
 }
Beispiel #7
0
        public static async Task Provision_recursive_dir_in()
        {
            var directory = new DirectoryBuilder("root");

            directory.Directory("out");
            var cfg = directory.Directory("cfg");
            var src = directory.Directory("src");
            var lib = src.Directory("lib").Directory("config");

            directory.TextFile("package.json").Code.Append("{ \"private\": true }");
            cfg.TextFile("config.ini").Code.Append("SOME_CONFIG = 'SOME VALUE'");
            src.TextFile("index.js").Code.Append("require('config').getFromFile('./config.txt').log('SOME_CONFIG')");
            lib.TextFile("config.js").Code.Append("// Test.");

            await directory.ProvisionInAsync(Tmp);

            AssertDirectory("root", 4);
            AssertDirectory(Path.Join("root", "cfg"), 1);
            AssertDirectory(Path.Join("root", "src"), 2);
            AssertDirectory(Path.Join("root", "src", "lib"), 1);
            AssertDirectory(Path.Join("root", "src", "lib", "config"), 1);
            AssertDirectory(Path.Join("root", "out"), 0);

            AssertFile(Path.Join("root", "package.json"), "{ \"private\": true }");
            AssertFile(Path.Join("root", "cfg", "config.ini"), "SOME_CONFIG = 'SOME VALUE'");
            AssertFile(Path.Join("root", "src", "index.js"), "require('config').getFromFile('./config.txt').log('SOME_CONFIG')");
            AssertFile(Path.Join("root", "src", "lib", "config", "config.js"), "// Test.");
        }
Beispiel #8
0
        public void build_new_path_with_day_name()
        {
            _mediaFileInfo.ModifiedDate = new DateTime(1, 1, 1);
            var newPath = DirectoryBuilder.BuildNewPathByDate(_mediaFileInfo, DateInterval.Day);

            newPath.Should().Be(@"x:\1-Monday\test.jpg");
        }
Beispiel #9
0
        /// <summary>
        /// Check user
        /// </summary>
        /// <remarks>Checks username, password and role</remarks>
        public bool ValidateUser(string username, string password, out string errMsg)
        {
            try {
                // check the number of attempts
                if (validateUserAttemptNum > MaxValidateUserAttempts)
                {
                    errMsg = Localization.UseRussian
                        ? "Превышено количество попыток входа"
                        : "Number of login attempts exceeded";
                    return(false);
                }
                else
                {
                    validateUserAttemptNum++;
                }

                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    // opening user table
                    BaseAdapter baseAdapter = new BaseAdapter();
                    var         userTable   = new DataTable();
                    baseAdapter.FileName = Path.Combine(Settings.Directory,
                                                        DirectoryBuilder.GetDirectory(ConfigParts.Base), "user.dat");
                    baseAdapter.Fill(userTable, false);

                    // search and verification of user information
                    userTable.CaseSensitive = false;
                    DataRow[] rows = userTable.Select(string.Format("Name = '{0}'", username));

                    if (rows.Length > 0)
                    {
                        var row = rows[0];
                        if ((string)row["Password"] == password)
                        {
                            if ((int)row["RoleID"] == BaseValues.Roles.App)
                            {
                                validateUserAttemptNum = 0;
                                errMsg = "";
                                return(true);
                            }
                            else
                            {
                                errMsg = Localization.UseRussian ? "Недостаточно прав" : "Insufficient rights";
                                return(false);
                            }
                        }
                    }
                }

                errMsg = Localization.UseRussian
                    ? "Неверное имя пользователя или пароль"
                    : "Invalid username or password";
                return(false);
            } catch (Exception ex) {
                errMsg = Localization.UseRussian ? "Ошибка при проверке пользователя" : "Error validating user";
                log.WriteException(ex, errMsg);
                return(false);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Получить статус службы
        /// </summary>
        public bool GetServiceStatus(ServiceApp serviceApp, out ServiceStatus status)
        {
            try
            {
                status = ServiceStatus.Undefined;
                string statusFileName = Path.Combine(Settings.Directory,
                                                     DirectoryBuilder.GetDirectory(serviceApp),
                                                     DirectoryBuilder.GetDirectory(AppFolder.Log),
                                                     GetServiceStatusFile(serviceApp));

                if (File.Exists(statusFileName))
                {
                    string[] lines = File.ReadAllLines(statusFileName, Encoding.UTF8);

                    foreach (string line in lines)
                    {
                        if (line.StartsWith("State", StringComparison.Ordinal) ||
                            line.StartsWith("Состояние", StringComparison.Ordinal))
                        {
                            int colonInd = line.IndexOf(':');

                            if (colonInd > 0)
                            {
                                string statusStr = line.Substring(colonInd + 1).Trim();

                                if (statusStr.Equals("normal", StringComparison.OrdinalIgnoreCase) ||
                                    statusStr.Equals("норма", StringComparison.OrdinalIgnoreCase))
                                {
                                    status = ServiceStatus.Normal;
                                }
                                else if (statusStr.Equals("stopped", StringComparison.OrdinalIgnoreCase) ||
                                         statusStr.Equals("остановлен", StringComparison.OrdinalIgnoreCase))
                                {
                                    status = ServiceStatus.Stopped;
                                }
                                else if (statusStr.Equals("error", StringComparison.OrdinalIgnoreCase) ||
                                         statusStr.Equals("ошибка", StringComparison.OrdinalIgnoreCase))
                                {
                                    status = ServiceStatus.Error;
                                }
                            }
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Localization.UseRussian ?
                                   "Ошибка при получении статуса службы" :
                                   "Error getting service status");
                status = ServiceStatus.Undefined;
                return(false);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Распаковать архив конфигурации
        /// </summary>
        public bool UnpackConfig(string srcFileName, ConfigOptions configOptions)
        {
            try
            {
                // удаление существующей конфигурации
                List <RelPath> configPaths = GetConfigPaths(configOptions.ConfigParts);
                PathDict       pathDict    = PrepareIgnoredPaths(configOptions.IgnoredPaths);

                foreach (RelPath relPath in configPaths)
                {
                    ClearDir(relPath, pathDict);
                }

                // определение допустимых директорий для распаковки
                ConfigParts   configParts    = configOptions.ConfigParts;
                List <string> allowedEntries = new List <string>(AllConfigParts.Length);

                foreach (ConfigParts configPart in AllConfigParts)
                {
                    if (configParts.HasFlag(configPart))
                    {
                        allowedEntries.Add(DirectoryBuilder.GetDirectory(configPart, '/'));
                    }
                }

                // распаковка новой конфигурации
                using (FileStream fileStream =
                           new FileStream(srcFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (ZipArchive zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read))
                    {
                        string instanceDir = Settings.Directory;

                        foreach (ZipArchiveEntry entry in zipArchive.Entries)
                        {
                            if (StartsWith(entry.FullName, allowedEntries, StringComparison.Ordinal))
                            {
                                string relPath      = entry.FullName.Replace('/', Path.DirectorySeparatorChar);
                                string destFileName = instanceDir + relPath;
                                Directory.CreateDirectory(Path.GetDirectoryName(destFileName));
                                entry.ExtractToFile(destFileName, true);
                            }
                        }

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Localization.UseRussian ?
                                   "Ошибка при распаковке конфигурации из архива" :
                                   "Error unpacking configuration from archive");
                return(false);
            }
        }
Beispiel #12
0
        /// <inheritdoc/>
        protected override void ExtractArchive()
        {
            try
            {
                // Read ZIP file sequentially and reference central directory in parallel
                foreach (var centralEntry in _centralDirectory)
                {
                    var localEntry = _zipStream.GetNextEntry();
                    if (localEntry == null)
                    {
                        break;
                    }

                    string?relativePath = GetRelativePath(centralEntry.Name);
                    if (string.IsNullOrEmpty(relativePath))
                    {
                        continue;
                    }

                    if (centralEntry.IsDirectory)
                    {
                        DirectoryBuilder.CreateDirectory(relativePath, localEntry.DateTime);
                    }
                    else if (centralEntry.IsFile)
                    {
                        if (IsSymlink(centralEntry))
                        {
                            DirectoryBuilder.CreateSymlink(relativePath, _zipStream.ReadToString());
                        }
                        else
                        {
                            WriteFile(relativePath, centralEntry.Size, localEntry.DateTime, _zipStream, IsExecutable(centralEntry));
                        }
                    }

                    UnitsProcessed += centralEntry.CompressedSize;
                }
            }
            #region Error handling
            catch (SharpZipBaseException ex)
            {
                // Wrap exception since only certain exception types are allowed
                throw new IOException(Resources.ArchiveInvalid, ex);
            }
            catch (InvalidDataException ex)
            {
                // Wrap exception since only certain exception types are allowed
                throw new IOException(Resources.ArchiveInvalid, ex);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                // Wrap exception since only certain exception types are allowed
                throw new IOException(Resources.ArchiveInvalid, ex);
            }
            #endregion
        }
Beispiel #13
0
 static void InitializePaths()
 {
     DirectoryBuilder.InitializeMainAsGrandparentDirectory();
     dataDirectory     = DirectoryBuilder.BuildPathAndDirectoryFromMainDirectory("data");
     userDataDirectory = DirectoryBuilder.BuildPathAndDirectoryFromMainDirectory(
         new string[] { "data", "users" });
     gameDataDirectory = DirectoryBuilder.BuildPathAndDirectoryFromMainDirectory(
         new string[] { "data", "games" });
     gameSystemDataDirectory = DirectoryBuilder.BuildPathAndDirectoryFromMainDirectory(
         new string[] { "data", "systems" });
 }
    public void Hardlink()
    {
        using var tempDir = new TemporaryDirectory("0install-test-archive");
        var builder = new DirectoryBuilder(tempDir);
        using var stream = typeof(ArchiveExtractorTestBase).GetEmbeddedStream(FileName);
        ArchiveExtractor.For(MimeType, new SilentTaskHandler())
                        .Extract(builder, stream);

        FileUtils.AreHardlinked(Path.Combine(tempDir, "hardlink"), Path.Combine(tempDir, "subdir1", "regular"))
                 .Should().BeTrue(because: "'regular' and 'hardlink' should be hardlinked together");
    }
Beispiel #15
0
        /// <summary>
        /// Проверить пользователя
        /// </summary>
        /// <remarks>Проверяется имя пользователя, пароль и роль</remarks>
        public bool ValidateUser(string username, string password, out string errMsg)
        {
            try
            {
                // проверка количества попыток
                if (validateUserAttemptNum > MaxValidateUserAttempts)
                {
                    errMsg = Localization.UseRussian ?
                             "Превышено количество попыток входа" :
                             "Number of login attempts exceeded";
                    return(false);
                }

                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    // открытие таблицы пользователей
                    BaseAdapter baseAdapter = new BaseAdapter();
                    DataTable   userTable   = new DataTable();
                    baseAdapter.FileName = Path.Combine(Settings.Directory,
                                                        DirectoryBuilder.GetDirectory(ConfigParts.Base), "user.dat");
                    baseAdapter.Fill(userTable, false);

                    // поиск и проверка информации о пользователе
                    userTable.CaseSensitive = false;
                    DataRow[] rows = userTable.Select(string.Format("Name = '{0}'", username));

                    if (rows.Length > 0)
                    {
                        DataRow row = rows[0];
                        if ((string)row["Password"] == password && (int)row["RoleID"] == BaseValues.Roles.Admin)
                        {
                            validateUserAttemptNum = 0;
                            errMsg = "";
                            return(true);
                        }
                    }
                }

                validateUserAttemptNum++;
                errMsg = Localization.UseRussian ?
                         "Неверное имя пользователя или пароль" :
                         "Invalid username or password";
                return(false);
            }
            catch (Exception ex)
            {
                errMsg = Localization.UseRussian ?
                         "Ошибка при проверке пользователя" :
                         "Error validating user";
                log.WriteException(ex, errMsg);
                return(false);
            }
        }
Beispiel #16
0
        private void ApplyMultipleIntervals(DateInterval interval, MediaFileInfo mediaFile)
        {
            var initialPath = mediaFile.CurrentPath;

            for (var i = (int)DateInterval.Year; i >= (int)interval; i--)
            {
                mediaFile.NewPath     = DirectoryBuilder.BuildNewPathByDate(mediaFile, (DateInterval)i);
                mediaFile.CurrentPath = mediaFile.NewPath;
            }

            mediaFile.CurrentPath = initialPath;
        }
Beispiel #17
0
        /// <summary>
        /// Unpack configuration archive
        /// </summary>
        public bool UnpackConfig(string srcFileName, ConfigOptions configOptions)
        {
            try {
                // delete existing configuration
                List <RelPath> configPaths = GetConfigPaths(configOptions.ConfigParts);
                var            pathDict    = PrepareIgnoredPaths(configOptions.IgnoredPaths);

                foreach (var relPath in configPaths)
                {
                    ClearDir(relPath, pathDict);
                }

                // definition of valid unpacking directories
                var configParts    = configOptions.ConfigParts;
                var allowedEntries = new List <string>(AllConfigParts.Length);

                foreach (var configPart in AllConfigParts)
                {
                    if (configParts.HasFlag(configPart))
                    {
                        allowedEntries.Add(DirectoryBuilder.GetDirectory(configPart, '/'));
                    }
                }

                // unpacking new configuration
                using (var fileStream =
                           new FileStream(srcFileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                    using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read)) {
                        string instanceDir = Settings.Directory;

                        foreach (var entry in zipArchive.Entries)
                        {
                            if (StartsWith(entry.FullName, allowedEntries, StringComparison.Ordinal))
                            {
                                string relPath      = entry.FullName.Replace('/', Path.DirectorySeparatorChar);
                                string destFileName = instanceDir + relPath;
                                Directory.CreateDirectory(Path.GetDirectoryName(destFileName));
                                entry.ExtractToFile(destFileName, true);
                            }
                        }

                        return(true);
                    }
                }
            } catch (Exception ex) {
                log.WriteException(ex,
                                   Localization.UseRussian
                        ? "Ошибка при распаковке конфигурации из архива"
                        : "Error unpacking configuration from archive");
                return(false);
            }
        }
Beispiel #18
0
        public static async Task Provision_simple_dir_as()
        {
            var directory = new DirectoryBuilder("src");

            directory.TextFile("config.ini").Code.Append("SOME_CONFIG = 'SOME VALUE'");
            directory.TextFile("index.js").Code.Append("require('config').getFromFile('./config.txt').log('SOME_CONFIG')");

            await directory.ProvisionAsAsync(Tmp);

            AssertDirectory("", 2);

            AssertFile("config.ini", "SOME_CONFIG = 'SOME VALUE'");
            AssertFile("index.js", "require('config').getFromFile('./config.txt').log('SOME_CONFIG')");
        }
        public void Can_Create_Base_Dir_If_Dont_Exists()
        {
            var temp     = Path.GetTempPath();
            var guid     = Guid.NewGuid().ToString();
            var tempPath = Path.Combine(temp, guid).TrimEnd('/');

            try
            {
                var dirBuilder = new DirectoryBuilder(tempPath, true);
                dirBuilder.Create();
                Directory.Exists(tempPath);
            }
            finally
            {
                Directory.Delete(tempPath, true);
            }
        }
        public void Throws_If_Adding_Invalid_Dir_Name(string dirName)
        {
            var dirBuilder = new DirectoryBuilder(Path.GetTempPath());

            var exception = Assert.Throws <ArgumentException>(() =>
            {
                dirBuilder.AddSubdirectoryAndStay(dirName);
            });

            Assert.Equal("directoryName", exception.ParamName);
            Assert.Contains("Directory name can't contains invalid chars", exception.Message);

            exception = Assert.Throws <ArgumentException>(() =>
            {
                dirBuilder.AddSubdirectoryAndEnter(dirName);
            });

            Assert.Equal("directoryName", exception.ParamName);
            Assert.Contains("Directory name can't contains invalid chars", exception.Message);
        }
        public void Throws_If_Adding_Empty_File_Name(string fileName)
        {
            var dirBuilder = new DirectoryBuilder(Path.GetTempPath());

            var exception = Assert.Throws <ArgumentException>(() =>
            {
                dirBuilder.AddFile(fileName);
            });

            Assert.Equal("fileName", exception.ParamName);
            Assert.Contains("File name can't be null or empty", exception.Message);

            exception = Assert.Throws <ArgumentException>(() =>
            {
                dirBuilder.AddFile(fileName);
            });

            Assert.Equal("fileName", exception.ParamName);
            Assert.Contains("File name can't be null or empty", exception.Message);
        }
        public static HashSet <string> LoadBridgeDefinedTypes(bool forceReload)
        {
            if (!forceReload && bridgeTypes != null)
            {
                return(bridgeTypes);
            }

            bridgeTypes = new HashSet <string>();
            // string text = File.ReadAllText((PathProc.BridgePath + "stub-builder" + "inner" + "BridgeTypes.txt").ToProjectRoot);/
            string text = DirectoryBuilder.GetDirectory("configs")["Text"]["BridgeTypes.txt"];

            string[] lines = text.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            string   ns    = "";

            for (int i = 0; i < lines.Length; i++)
            {
                string line = lines[i];
                if (line.StartsWith("//"))
                {
                    continue;
                }
                if (line[0] == '[')
                {
                    ns = line.Substring(1, line.Length - 2);
                }
                else
                {
                    string name   = line;
                    int    index1 = name.IndexOf('<');
                    if (index1 >= 0)
                    {
                        int index2 = name.IndexOf('>');
                        int tCount = name.Substring(index1 + 1, index2 - index1 - 1).Count((c) => c == ',');
                        name = line.Substring(0, index1) + "`" + (tCount + 1);
                    }
                    bridgeTypes.Add(ns + "." + name);
                }
            }

            return(bridgeTypes);
        }
Beispiel #23
0
        public async Task <Directory> CreateDirectory(string name, string directoryPath, bool isPrivate = false, string parentDirectoryId = null)
        {
            string fullPath = $"{directoryPath}{name}";

            if (!fileWriter.CreateDirectory(fullPath))
            {
                ErrorWriter.Append("Directory name already exists");
                return(null);
            }

            var directory = new DirectoryBuilder()
                            .SetName(name)
                            .SetPath(fullPath)
                            .AssignedTo(!isPrivate ? null : currentUserId)
                            .WithParentDirectory(parentDirectoryId)
                            .Build();

            database.DirectoryRepository.Add(directory);

            return(await database.Complete() ? directory : null);
        }
Beispiel #24
0
        /// <inheritdoc/>
        protected override void ExtractArchive()
        {
            State = TaskState.Data;

            try
            {
                UnitsTotal = _archive.TotalUncompressSize;

                foreach (var entry in _archive.Entries)
                {
                    string?relativePath = GetRelativePath(entry.Key.Replace('\\', '/'));
                    if (relativePath == null)
                    {
                        continue;
                    }

                    if (entry.IsDirectory)
                    {
                        DirectoryBuilder.CreateDirectory(relativePath, entry.LastModifiedTime?.ToUniversalTime());
                    }
                    else
                    {
                        CancellationToken.ThrowIfCancellationRequested();

                        string absolutePath = DirectoryBuilder.NewFilePath(relativePath, entry.LastModifiedTime?.ToUniversalTime());
                        using (var fileStream = File.Create(absolutePath))
                            entry.WriteTo(fileStream);

                        UnitsProcessed += entry.Size;
                    }
                }
            }
            #region Error handling
            catch (ExtractionException ex)
            {
                // Wrap exception since only certain exception types are allowed
                throw new IOException(Resources.ArchiveInvalid, ex);
            }
            #endregion
        }
        Stream IUnpackStreamContext.OpenFileWriteStream(string path, long fileSize, DateTime lastWriteTime)
        {
            #region Sanity checks
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            #endregion

            CancellationToken.ThrowIfCancellationRequested();

            string relativePath = GetRelativePath(path);
            if (relativePath == null)
            {
                return(null);
            }

            _bytesStaged = fileSize;

            string absolutePath = DirectoryBuilder.NewFilePath(relativePath, lastWriteTime);
            return(File.Create(absolutePath));
        }
        public void Can_Describe_Correctly()
        {
            var tempPath = Path.GetTempPath().TrimEnd('/');

            var dirBuilder = new DirectoryBuilder(tempPath, true)
                             .AddFile("file1.txt")
                             .AddFile("file2.txt")
                             .AddSubdirectoryAndEnter("dir1")
                             .AddFile("file11.txt")
                             .AddFile("file12.txt")
                             .GoBack()
                             .AddSubdirectoryAndStay("dir2")
                             .AddSubdirectoryAndEnter("dir3")
                             .AddSubdirectoryAndEnter("dir31")
                             .AddFile("file311.txt")
                             .AddFile("file312.txt")
                             .GoBack()
                             .AddFile("file31.txt")
                             .GoBack();

            var strBuilder = new StringBuilder();

            strBuilder.AppendLine(tempPath);
            strBuilder.AppendLine(Path.Combine(tempPath, @"file1.txt"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"file2.txt"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir1"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir1/file11.txt"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir1/file12.txt"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir2"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir3"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir3/file31.txt"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir3/dir31"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir3/dir31/file311.txt"));
            strBuilder.AppendLine(Path.Combine(tempPath, @"dir3/dir31/file312.txt"));

            Assert.Equal(strBuilder.ToString(), dirBuilder.ToString());
        }
Beispiel #27
0
        public void Classify(List <MediaFileInfo> images, ClassifierArgs args)
        {
            var dateArgs = args as DateClassifierArgs;

            if (images == null)
            {
                throw new ArgumentNullException(nameof(images));
            }
            if (dateArgs == null)
            {
                throw new ArgumentNullException(nameof(dateArgs));
            }
            foreach (var image in images)
            {
                if (!dateArgs.UseMultipleClassifiers)
                {
                    image.NewPath = DirectoryBuilder.BuildNewPathByDate(image, dateArgs.Interval);
                }
                else
                {
                    ApplyMultipleIntervals(dateArgs.Interval, image);
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Exports the configuration to the specified archive.
        /// </summary>
        public void ExportToArchive(string destFileName, ScadaProject project, Instance instance,
                                    TransferSettings transferSettings)
        {
            if (destFileName == null)
            {
                throw new ArgumentNullException("destFileName");
            }
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            FileStream fileStream = null;
            ZipArchive zipArchive = null;

            try {
                fileStream = new FileStream(destFileName, FileMode.Create, FileAccess.Write, FileShare.Read);
                zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create);
                bool ignoreRegKeys = transferSettings.IgnoreRegKeys;

                // add the configuration database to the archive
                if (transferSettings.IncludeBase)
                {
                    foreach (IBaseTable srcTable in project.ConfigBase.AllTables)
                    {
                        string entryName  = "BaseDAT/" + srcTable.Name.ToLowerInvariant() + ".dat";
                        var    tableEntry = zipArchive.CreateEntry(entryName, CompressionLevel.Fastest);

                        using (var entryStream = tableEntry.Open()) {
                            // convert the table to DAT format
                            BaseAdapter baseAdapter = new BaseAdapter()
                            {
                                Stream = entryStream
                            };
                            baseAdapter.Update(srcTable);
                        }
                    }
                }

                // add the interface files to the archive
                if (transferSettings.IncludeInterface)
                {
                    PackDirectory(zipArchive, project.Interface.InterfaceDir,
                                  DirectoryBuilder.GetDirectory(ConfigParts.Interface, '/'), ignoreRegKeys);
                }

                // add the Server settings to the archive
                if (transferSettings.IncludeServer && instance.ServerApp.Enabled)
                {
                    PackDirectory(zipArchive, instance.ServerApp.AppDir,
                                  DirectoryBuilder.GetDirectory(ConfigParts.Server, '/'), ignoreRegKeys);
                }

                // add the Communicator settings to the archive
                if (transferSettings.IncludeServer && instance.ServerApp.Enabled)
                {
                    PackDirectory(zipArchive, instance.CommApp.AppDir,
                                  DirectoryBuilder.GetDirectory(ConfigParts.Comm, '/'), ignoreRegKeys);
                }

                // add the Webstation settings to the archive
                if (transferSettings.IncludeServer && instance.ServerApp.Enabled)
                {
                    PackDirectory(zipArchive, Path.Combine(instance.WebApp.AppDir, "config"),
                                  DirectoryBuilder.GetDirectory(ConfigParts.Web, AppFolder.Config, '/'), ignoreRegKeys);

                    if (!transferSettings.IgnoreWebStorage)
                    {
                        PackDirectory(zipArchive, Path.Combine(instance.WebApp.AppDir, "storage"),
                                      DirectoryBuilder.GetDirectory(ConfigParts.Web, AppFolder.Storage, '/'), ignoreRegKeys);
                    }
                }
            } catch (Exception ex) {
                throw new ScadaException(AdminPhrases.ExportToArchiveError, ex);
            } finally {
                zipArchive?.Dispose();
                fileStream?.Dispose();
            }
        }
Beispiel #29
0
        /// <summary>
        /// Imports the configuration from the specified archive.
        /// </summary>
        public void ImportArchive(string srcFileName, ScadaProject project, Instance instance,
                                  out ConfigParts foundConfigParts)
        {
            if (srcFileName == null)
            {
                throw new ArgumentNullException("srcFileName");
            }
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            foundConfigParts = ConfigParts.None;
            string extractDir = Path.Combine(Path.GetDirectoryName(srcFileName),
                                             Path.GetFileNameWithoutExtension(srcFileName));

            try {
                // extract the configuration
                ExtractArchive(srcFileName, extractDir);

                // import the configuration database
                string srcBaseDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Base));

                if (Directory.Exists(srcBaseDir))
                {
                    foundConfigParts |= ConfigParts.Base;

                    foreach (IBaseTable destTable in project.ConfigBase.AllTables)
                    {
                        string datFileName = Path.Combine(srcBaseDir, destTable.Name.ToLowerInvariant() + ".dat");

                        if (File.Exists(datFileName))
                        {
                            try {
                                BaseAdapter baseAdapter = new BaseAdapter()
                                {
                                    FileName = datFileName
                                };
                                var srcTable = new DataTable();
                                baseAdapter.Fill(srcTable, true);
                                ImportBaseTable(srcTable, destTable);
                            } catch (Exception ex) {
                                throw new ScadaException(string.Format(
                                                             AdminPhrases.ImportBaseTableError, destTable.Name), ex);
                            }
                        }
                    }
                }

                // import the interface files
                string srcInterfaceDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Interface));

                if (Directory.Exists(srcInterfaceDir))
                {
                    foundConfigParts |= ConfigParts.Interface;
                    MergeDirectory(srcInterfaceDir, project.Interface.InterfaceDir);
                }

                // import the Server settings
                if (instance.ServerApp.Enabled)
                {
                    string srcServerDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Server));

                    if (Directory.Exists(srcServerDir))
                    {
                        foundConfigParts |= ConfigParts.Server;
                        MergeDirectory(srcServerDir, instance.ServerApp.AppDir);

                        if (!instance.ServerApp.LoadSettings(out string errMsg))
                        {
                            throw new ScadaException(errMsg);
                        }
                    }
                }

                // import the Communicator settings
                if (instance.CommApp.Enabled)
                {
                    string srcCommDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Comm));

                    if (Directory.Exists(srcCommDir))
                    {
                        foundConfigParts |= ConfigParts.Comm;
                        MergeDirectory(srcCommDir, instance.CommApp.AppDir);

                        if (!instance.CommApp.LoadSettings(out string errMsg))
                        {
                            throw new ScadaException(errMsg);
                        }
                    }
                }

                // import the Webstation settings
                if (instance.WebApp.Enabled)
                {
                    string srcWebDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Web));

                    if (Directory.Exists(srcWebDir))
                    {
                        foundConfigParts |= ConfigParts.Web;
                        MergeDirectory(srcWebDir, instance.WebApp.AppDir);
                    }
                }
            } catch (Exception ex) {
                throw new ScadaException(AdminPhrases.ImportArchiveError, ex);
            } finally {
                // delete the extracted files
                if (Directory.Exists(extractDir))
                {
                    Directory.Delete(extractDir, true);
                }
            }
        }
Beispiel #30
0
 /// <summary>
 /// Получить абсолютный путь из относительного
 /// </summary>
 public string GetAbsPath(ConfigParts configPart, AppFolder appFolder, string path)
 {
     return(Path.Combine(Settings.Directory, DirectoryBuilder.GetDirectory(configPart, appFolder), path));
 }