public void Import(MigrationToolSettings settings)
        {
            var sourceImportFilePath = Path.Combine(settings.SourceDirectory, "localization-resource-translations.sql");
            if (!File.Exists(sourceImportFilePath))
            {
                throw new IOException($"Source file '{sourceImportFilePath}' for import not found!");
            }

            // create DB structures in target database
            using (var db = new LanguageEntities(settings.ConnectionString))
            {
                var resource = db.LocalizationResources.Where(r => r.Id == 0);
            }

            var fileInfo = new FileInfo(sourceImportFilePath);
            var script = fileInfo.OpenText().ReadToEnd();
            using (var connection = new SqlConnection(settings.ConnectionString))
            {
                connection.Open();

                using (var command = new SqlCommand(script, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }
Example #2
0
        public void GetServerProperties_MigrationToolSettings()
        {
            var api        = new IceWarpRpcApi();
            var authResult = Authenticate(api);

            var propertyNames = ClassHelper.PublicGetProperites(typeof(MigrationToolSettings));

            Assert.AreEqual(21, propertyNames.Count);

            var request = new GetServerProperties
            {
                SessionId          = authResult.SessionId,
                ServerPropertyList = new TServerPropertyList
                {
                    Items = propertyNames.Select(x => new TAPIProperty {
                        PropName = x.Name
                    }).ToList()
                }
            };
            var getPropertiesResult = api.Execute(_url, request);

            Assert.NotNull(getPropertiesResult);
            Assert.NotNull(getPropertiesResult.HttpRequestResult);
            Assert.True(getPropertiesResult.HttpRequestResult.Success);
            Assert.NotNull(getPropertiesResult.Items);

            var settings = new MigrationToolSettings(getPropertiesResult.Items);

            Assert.AreEqual(21, propertyNames.Count);
        }
Example #3
0
        public void ComBaseClassTests_GetPublicSetterProperties()
        {
            var testClass   = new MigrationToolSettings();
            var setterProps = testClass.SetablePropertiesList();

            Assert.AreEqual(14, setterProps.Count);
            Assert.IsNull(setterProps.FirstOrDefault(x => x.Name == "C_System_Tools_Migration_Stat_Errors"));
        }
        internal ICollection<LocalizationResource> Extract(MigrationToolSettings settings)
        {
            if (settings.ExportFromDatabase)
            {
                using (var db = new LanguageEntities(settings.ConnectionString))
                {
                    return db.LocalizationResources.Include(r => r.Translations).ToList();
                }
            }

            // test few default conventions (lazy enough to read from EPiServer Framework configuration file)
            string resourceFilesSourceDir;
            if (!string.IsNullOrEmpty(settings.ResourceDirectory))
            {
                resourceFilesSourceDir = Path.Combine(settings.SourceDirectory, settings.ResourceDirectory);
            }
            else
            {
                resourceFilesSourceDir = Path.Combine(settings.SourceDirectory, "Resources\\LanguageFiles");
                if (!Directory.Exists(resourceFilesSourceDir))
                {
                    resourceFilesSourceDir = Path.Combine(settings.SourceDirectory, "lang");
                }
            }

            if (!Directory.Exists(resourceFilesSourceDir))
            {
                throw new IOException($"Default resource directory '{resourceFilesSourceDir}' does not exist or can't be found. Use `-resourceDir` argument");
            }

            var resourceFiles = Directory.GetFiles(resourceFilesSourceDir, "*.xml");
            if (!resourceFiles.Any())
            {
                Console.WriteLine($"No resource files found in '{resourceFilesSourceDir}'");
            }

            var fileProcessor = new ResourceFileProcessor();
            var resources = fileProcessor.ParseFiles(resourceFiles);

            // initialize DB - to generate data structures
            try
            {
                using (var db = new LanguageEntities(settings.ConnectionString))
                {
                    var resource = db.LocalizationResources.Where(r => r.Id == 0);
                }
            }
            catch
            {
                // it's OK to have exception here
            }

            return resources;
        }
        public void BuildTPropertyValues_AllProperties()
        {
            var testClass = new MigrationToolSettings
            {
                C_System_Tools_DBMigration_FixUTF8      = true,
                C_System_Tools_Migration_Server         = "",
                C_System_Tools_Migration_MigrateService = ServerMigrationService.Both,
                C_System_Tools_Migration_SSLMode        = TlsSslMode.Detect,
                C_System_Tools_Migration_InfoAccount    = "Info Account"
            };

            var tPropertyValueItems = testClass.BuildTPropertyValues();

            Assert.AreEqual(5, tPropertyValueItems.Count);
            var fixUTF8 = tPropertyValueItems.FirstOrDefault(x => x.APIProperty.PropName == "C_System_Tools_DBMigration_FixUTF8");

            Assert.NotNull(fixUTF8);
            Assert.AreEqual(typeof(TPropertyString), fixUTF8.PropertyVal.GetType());
            Assert.AreEqual("1", ((TPropertyString)fixUTF8.PropertyVal).Val);
            Assert.AreEqual(TPermission.ReadWrite, fixUTF8.PropertyRight);

            var server = tPropertyValueItems.FirstOrDefault(x => x.APIProperty.PropName == "C_System_Tools_Migration_Server");

            Assert.NotNull(server);
            Assert.AreEqual(typeof(TPropertyString), server.PropertyVal.GetType());
            Assert.AreEqual("", ((TPropertyString)server.PropertyVal).Val);
            Assert.AreEqual(TPermission.ReadWrite, server.PropertyRight);

            var migrateService = tPropertyValueItems.FirstOrDefault(x => x.APIProperty.PropName == "C_System_Tools_Migration_MigrateService");

            Assert.NotNull(migrateService);
            Assert.AreEqual(typeof(TPropertyString), migrateService.PropertyVal.GetType());
            Assert.AreEqual(((int)ServerMigrationService.Both).ToString(), ((TPropertyString)migrateService.PropertyVal).Val);
            Assert.AreEqual(TPermission.ReadWrite, migrateService.PropertyRight);

            var sslMode = tPropertyValueItems.FirstOrDefault(x => x.APIProperty.PropName == "C_System_Tools_Migration_SSLMode");

            Assert.NotNull(sslMode);
            Assert.AreEqual(typeof(TPropertyString), sslMode.PropertyVal.GetType());
            Assert.AreEqual(((int)TlsSslMode.Detect).ToString(), ((TPropertyString)sslMode.PropertyVal).Val);
            Assert.AreEqual(TPermission.ReadWrite, sslMode.PropertyRight);

            var infoAccount = tPropertyValueItems.FirstOrDefault(x => x.APIProperty.PropName == "C_System_Tools_Migration_InfoAccount");

            Assert.NotNull(infoAccount);
            Assert.AreEqual(typeof(TPropertyString), infoAccount.PropertyVal.GetType());
            Assert.AreEqual("Info Account", ((TPropertyString)infoAccount.PropertyVal).Val);
            Assert.AreEqual(TPermission.ReadWrite, infoAccount.PropertyRight);
        }
        public void BuildTPropertyValues_InvalidProperty()
        {
            var testClass = new MigrationToolSettings
            {
                C_System_Tools_DBMigration_FixUTF8      = true,
                C_System_Tools_Migration_Server         = "",
                C_System_Tools_Migration_MigrateService = ServerMigrationService.Both,
                C_System_Tools_Migration_SSLMode        = TlsSslMode.Detect,
                C_System_Tools_Migration_InfoAccount    = "Info Account"
            };

            var invalidPropertyName = "INVALID_PROPERTY";
            var exception           = Assert.Throws <SettablePropertyException>(() => testClass.BuildTPropertyValues(new List <string> {
                invalidPropertyName
            }));

            Assert.AreEqual(invalidPropertyName, exception.PropertyName);
        }
        public void BuildTPropertyValues_SelectProperties()
        {
            var testClass = new MigrationToolSettings
            {
                C_System_Tools_DBMigration_FixUTF8      = true,
                C_System_Tools_Migration_Server         = "",
                C_System_Tools_Migration_MigrateService = ServerMigrationService.Both,
                C_System_Tools_Migration_SSLMode        = TlsSslMode.Detect,
                C_System_Tools_Migration_InfoAccount    = "Info Account"
            };

            var tPropertyValueItems = testClass.BuildTPropertyValues(new List <string> {
                "C_System_Tools_DBMigration_FixUTF8"
            });

            Assert.AreEqual(1, tPropertyValueItems.Count);
            var fixUTF8 = tPropertyValueItems.FirstOrDefault(x => x.APIProperty.PropName == "C_System_Tools_DBMigration_FixUTF8");

            Assert.NotNull(fixUTF8);
            Assert.AreEqual(typeof(TPropertyString), fixUTF8.PropertyVal.GetType());
            Assert.AreEqual("1", ((TPropertyString)fixUTF8.PropertyVal).Val);
            Assert.AreEqual(TPermission.ReadWrite, fixUTF8.PropertyRight);
        }
        public static void Main(string[] args)
        {
            _settings = ParseArguments(args);

            if (_settings.ShowHelp)
            {
                ShowHelp(_settings.OptionSet);
                return;
            }

            if (string.IsNullOrEmpty(_settings.SourceDirectory))
            {
                Console.WriteLine("ERROR: Source directory parameter is missing!");
                Console.WriteLine();
                ShowHelp(_settings.OptionSet);
                return;
            }

            if (!Directory.Exists(_settings.SourceDirectory))
            {
                throw new IOException($"Source directory {_settings.SourceDirectory} does not exist!");
            }

            Directory.SetCurrentDirectory(_settings.SourceDirectory);
            ReadConnectionString(_settings);
            AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(_settings.SourceDirectory, "App_Data"));

            if (_settings.ExportResources)
            {
                try
                {
                    Console.WriteLine("Export started.");
                    var extractor = new ResourceExtractor();
                    var resources = extractor.Extract(_settings);
                    string generatedScript;

                    if (_settings.Json)
                    {
                        var serializer = new JsonDataSerializer();
                        generatedScript = serializer.Serialize(resources);
                    }
                    else
                    {
                        var scriptGenerator = new SqlScriptGenerator();
                        generatedScript = scriptGenerator.Generate(resources, _settings.ScriptUpdate);
                    }

                    var scriptFileWriter = new ResultFileWriter();
                    var outputFile = scriptFileWriter.Write(generatedScript, _settings.TargetDirectory, _settings.Json);

                    Console.WriteLine($"Output file: {outputFile}");
                    Console.WriteLine("Export completed!");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error running tool: {e.Message}");
                    return;
                }
            }

            if (_settings.ImportResources)
            {
                Console.WriteLine("Import started!");

                var importer = new ResourceImporter();
                importer.Import(_settings);

                Console.WriteLine("Import completed!");
            }

            if (!_settings.ExportResources && !_settings.ImportResources)
            {
                Console.WriteLine("No command specified.");
                Console.WriteLine("Try 'DbLocalizationProvider.MigrationTool.exe --help' for more information.");
            }

            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }
        }
        private static void ReadConnectionString(MigrationToolSettings settings)
        {
            var vdm = new VirtualDirectoryMapping(_settings.SourceDirectory, true);
            var wcfm = new WebConfigurationFileMap();
            wcfm.VirtualDirectories.Add("/", vdm);
            var config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");

            var connectionString = config.ConnectionStrings.ConnectionStrings["EPiServerDB"].ConnectionString;
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ConfigurationErrorsException("Cannot find EPiServer database connection");
            }

            settings.ConnectionString = connectionString;
        }
        private static MigrationToolSettings ParseArguments(string[] args)
        {
            var showHelp = false;
            var sourceDirectory = string.Empty;
            var resourceDirectory = string.Empty;
            var targetDirectory = string.Empty;
            var scriptUpdate = false;
            var exportResources = false;
            var importResources = false;
            var exportFromDatabase = false;
            var jsonFormat = false;

            var p = new OptionSet
            {
                {
                    "s|sourceDir=", "web application source directory",
                    v => sourceDirectory = v
                },
                {
                    "t|targetDir=", "Target directory where to write import script (by default 'sourceDir')",
                    v => targetDirectory = v
                },
                {
                    "resourceDir=", "Xml language resource directory (relative to `sourceDir`)",
                    v => resourceDirectory = v
                },
                {
                    "o|overwriteResources", "Generate update script statements for existing resources",
                    k => scriptUpdate = true
                },
                {
                    "e|exportResources", "Export localization resources",
                    k => exportResources = true
                },
                {
                    "from-db|fromDatabase", "Export localization resources from SQL database",
                    k => exportFromDatabase = true
                },
                {
                    "json|jsonFormat", "Use JSON format",
                    k => jsonFormat = true
                },
                {
                    "i|importResources", "Import localization resources from SQL file into database",
                    k => importResources = true
                },
                {
                    "h|help", "show this message and exit",
                    v => showHelp = v != null
                }
            };

            var result = new MigrationToolSettings(p);

            try
            {
                var extra = p.Parse(args);
                result.SourceDirectory = sourceDirectory;
                result.ResourceDirectory = resourceDirectory;
                result.TargetDirectory = targetDirectory;
                result.ScriptUpdate = scriptUpdate;
                result.ExportResources = exportResources;
                result.ExportFromDatabase = exportFromDatabase;
                result.ImportResources = importResources;
                result.ShowHelp = showHelp;
                result.Json = jsonFormat;
            }
            catch (OptionException e)
            {
                Console.Write("DbLocalizationProvider.MigrationTool: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try 'DbLocalizationProvider.MigrationTool.exe --help' for more information.");
            }

            if (string.IsNullOrEmpty(result.TargetDirectory))
            {
                result.TargetDirectory = result.SourceDirectory;
            }

            return result;
        }