예제 #1
0
        public void MigratingCoreAndDesktopTFMsAddsRuntimeIdentifierWithWin7x86ConditionOnAllFullFrameworksWhenNoRuntimesExistAlready()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssets)
                                .FromTestAssetBase("PJAppWithMultipleFrameworks")
                                .SaveToDisk(testDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory);
            var mockProj        = ProjectRootElement.Create();

            var migrationSettings = MigrationSettings.CreateMigrationSettingsTestHook(testDirectory, testDirectory, mockProj);
            var migrationInputs   = new MigrationRuleInputs(
                projectContexts,
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);

            mockProj.Properties.Count(p => p.Name == "RuntimeIdentifier").Should().Be(1);
            var runtimeIdentifier = mockProj.Properties.First(p => p.Name == "RuntimeIdentifier");

            runtimeIdentifier.Value.Should().Be("win7-x86");
            runtimeIdentifier.Condition.Should().Be(" '$(TargetFramework)' == 'net20' OR '$(TargetFramework)' == 'net35' OR '$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net461' ");
        }
예제 #2
0
        public async Task CanEmbedOnParent(MigrationProvider provider)
        {
            const string tableName      = "groups1";
            const string collectionName = "Groups1";

            using (WithSqlDatabase(provider, out var connectionString, out string schemaName, "basic"))
            {
                var driver = DatabaseDriverDispatcher.CreateDriver(provider, connectionString);
                using (var store = GetDocumentStore())
                {
                    var db = await GetDocumentDatabaseInstanceFor(store);

                    var settings = new MigrationSettings
                    {
                        Collections = new List <RootCollection>
                        {
                            new RootCollection(schemaName, tableName, collectionName)
                            {
                                NestedCollections = new List <EmbeddedCollection>
                                {
                                    new EmbeddedCollection(schemaName, tableName, RelationType.ManyToOne, new List <string> {
                                        "parent_group_id"
                                    }, "Parent")
                                    {
                                        NestedCollections = new List <EmbeddedCollection>
                                        {
                                            new EmbeddedCollection(schemaName, tableName, RelationType.ManyToOne, new List <string> {
                                                "parent_group_id"
                                            }, "Grandparent")
                                        }
                                    }
                                }
                            }
                        }
                    };

                    using (db.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                    {
                        var schema = driver.FindSchema();
                        ApplyDefaultColumnNamesMapping(schema, settings);
                        await driver.Migrate(settings, schema, db, context);
                    }

                    using (var session = store.OpenSession())
                    {
                        var group = session.Load <JObject>($"{collectionName}/53");
                        Assert.Equal("G1.1.1.1", group["Name"]);
                        var parent = group["Parent"];
                        Assert.NotNull(parent);
                        Assert.Equal("G1.1.1", parent["Name"]);
                        var grandparent = parent["Grandparent"];
                        Assert.NotNull(grandparent);
                        Assert.Equal("G1.1", grandparent["Name"]);
                    }

                    var collectionStatistics = store.Maintenance.Send(new GetCollectionStatisticsOperation());
                    Assert.Equal(7, collectionStatistics.CountOfDocuments);
                }
            }
        }
예제 #3
0
        public async Task CanMigrateEmbedOnParent(MigrationProvider provider)
        {
            using (WithSqlDatabase(provider, out var connectionString, out string schemaName, "basic"))
            {
                var driver = DatabaseDriverDispatcher.CreateDriver(provider, connectionString);
                using (var store = GetDocumentStore())
                {
                    var collection = new RootCollection(schemaName, "order", "Orders")
                    {
                        NestedCollections = new List <EmbeddedCollection>
                        {
                            new EmbeddedCollection(schemaName, "order_item", RelationType.OneToMany, new List <string> {
                                "order_id"
                            }, "Items")
                        }
                    };

                    var db = await GetDocumentDatabaseInstanceFor(store);

                    var settings = new MigrationSettings
                    {
                        Collections = new List <RootCollection>
                        {
                            collection
                        }
                    };

                    using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
                        using (db.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                        {
                            var schema = driver.FindSchema();
                            ApplyDefaultColumnNamesMapping(schema, settings);
                            await driver.Migrate(settings, schema, db, context, token : cts.Token);
                        }

                    using (var session = store.OpenSession())
                    {
                        var order = session.Load <JObject>("Orders/1");

                        Assert.NotNull(order);
                        // total and metadata, Id (Orders/1), Items
                        Assert.Equal(4, order.Properties().Count());

                        Assert.Equal("Orders", order["@metadata"]["@collection"]);
                        Assert.Equal(440, order["Total"]);
                        Assert.Equal("Orders/1", order["Id"]);
                        var firstItem = order["Items"][0];
                        Assert.Equal(110, firstItem["Price"]);
                        Assert.Equal(1, firstItem.Count());

                        var secondItem = order["Items"][1];
                        Assert.Equal(330, secondItem["Price"]);
                        Assert.Equal(1, secondItem.Count());
                    }

                    var collectionStatistics = store.Maintenance.Send(new GetCollectionStatisticsOperation());
                    Assert.Equal(1, collectionStatistics.CountOfDocuments);
                }
            }
        }
        public void TFMSpecificProjectDependenciesAreMigratedToProjectReferenceUnderConditionItemGroup()
        {
            var solutionDirectory = TestAssets.Get("TestAppWithLibraryUnderTFM")
                                    .CreateInstance(callingMethod: "p")
                                    .WithSourceFiles()
                                    .Root.FullName;

            var appDirectory = Path.Combine(solutionDirectory, "TestApp");

            var projectContext = ProjectContext.Create(appDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp11);
            var mockProj       = ProjectRootElement.Create();
            var testSettings   = MigrationSettings.CreateMigrationSettingsTestHook(appDirectory, appDirectory, mockProj, null);
            var testInputs     = new MigrationRuleInputs(new[] { projectContext }, mockProj, mockProj.AddItemGroup(),
                                                         mockProj.AddPropertyGroup());

            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var projectReferences = mockProj.Items.Where(item => item.ItemType.Equals("ProjectReference", StringComparison.Ordinal));

            projectReferences.Count().Should().Be(1);

            var projectReference = projectReferences.First();

            projectReference.Include.Should().Be(Path.Combine("..", "TestLibrary", "TestLibrary.csproj"));
            projectReference.Parent.Condition.Should().Be(" '$(TargetFramework)' == 'netcoreapp1.1' ");
        }
        public void If_a_project_dependency_is_present_DesignTimeAutoUnify_and_AutoUnify_are_present()
        {
            var solutionDirectory =
                TestAssetsManager.CreateTestInstance("TestAppWithLibrary", callingMethod: "p").Path;

            var appDirectory = Path.Combine(solutionDirectory, "TestApp");
            var libDirectory = Path.Combine(solutionDirectory, "TestLibrary");

            var projectContext = ProjectContext.Create(appDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);
            var mockProj       = ProjectRootElement.Create();
            var testSettings   = new MigrationSettings(appDirectory, appDirectory, "1.0.0", mockProj);
            var testInputs     = new MigrationRuleInputs(new[] { projectContext }, mockProj, mockProj.AddItemGroup(),
                                                         mockProj.AddPropertyGroup());

            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var autoUnify = mockProj.Properties.Where(p => p.Name == "AutoUnify");

            autoUnify.Count().Should().Be(1);
            autoUnify.First().Value.Should().Be("true");

            var designTimeAutoUnify = mockProj.Properties.Where(p => p.Name == "DesignTimeAutoUnify");

            designTimeAutoUnify.Count().Should().Be(1);
            designTimeAutoUnify.First().Value.Should().Be("true");
        }
        public AssetPairMigrationManager(
            IHealthService healthService,
            ICandlesPersistenceQueue candlesPersistenceQueue,
            MigrationCandlesGenerator candlesGenerator,
            AssetPairMigrationTelemetryService telemetryService,
            IAssetPair assetPair,
            ILog log,
            BidAskHCacheService bidAskHCacheService,
            IHistoryProvider historyProvider,
            ICandlesHistoryMigrationService candlesHistoryMigrationService,
            Action <string> onStoppedAction,
            MigrationSettings settings)
        {
            _healthService           = healthService;
            _candlesPersistenceQueue = candlesPersistenceQueue;
            _candlesGenerator        = candlesGenerator;
            _telemetryService        = telemetryService;
            _assetPair                      = assetPair;
            _log                            = log;
            _bidAskHCacheService            = bidAskHCacheService;
            _historyProvider                = historyProvider;
            _candlesHistoryMigrationService = candlesHistoryMigrationService;
            _onStoppedAction                = onStoppedAction;
            _settings                       = settings;

            _cts = new CancellationTokenSource();
        }
        private ProjectRootElement MigrateProject(
            string solution,
            string project,
            NuGetFramework targetFramework)
        {
            var solutionDirectory = TestAssets.Get(solution)
                                    .CreateInstance(callingMethod: "p")
                                    .WithSourceFiles()
                                    .Root.FullName;

            var appDirectory = Path.Combine(solutionDirectory, project);

            var projectContext = ProjectContext.Create(appDirectory, targetFramework);
            var mockProj       = ProjectRootElement.Create();
            var testSettings   = MigrationSettings.CreateMigrationSettingsTestHook(appDirectory, appDirectory, mockProj, null);
            var testInputs     = new MigrationRuleInputs(new[] { projectContext }, mockProj, mockProj.AddItemGroup(),
                                                         mockProj.AddPropertyGroup());

            new MigrateProjectDependenciesRule().Apply(testSettings, testInputs);

            var s = mockProj.Items.Select(p => $"ItemType = {p.ItemType}, Include = {p.Include}");

            Console.WriteLine(string.Join(Environment.NewLine, s));

            return(mockProj);
        }
        private void AddProjectTypeSpecificDependencies(
            MigrationRuleInputs migrationRuleInputs,
            MigrationSettings migrationSettings,
            ProjectItemGroupElement noFrameworkPackageReferenceItemGroup)
        {
            var type = migrationRuleInputs.DefaultProjectContext.ProjectFile.GetProjectType();

            switch (type)
            {
            case ProjectType.Web:
                _transformApplicator.Execute(
                    SdkPackageDependencyTransform.Transform(
                        new PackageDependencyInfo
                {
                    Name          = PackageConstants.WebSdkPackageName,
                    Version       = migrationSettings.SdkPackageVersion,
                    PrivateAssets = "All"
                }),
                    noFrameworkPackageReferenceItemGroup,
                    mergeExisting: false);
                break;

            default:
                break;
            }
        }
예제 #9
0
        public void Migrating_netcoreapp_project_Does_not_populate_TargetFrameworkIdentifier_and_TargetFrameworkVersion()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssetsManager)
                                .FromTestAssetBase("TestAppWithRuntimeOptions")
                                .WithCustomProperty("buildOptions", new Dictionary <string, string>
            {
                { "emitEntryPoint", "false" }
            })
                                .SaveToDisk(testDirectory);

            var projectContext = ProjectContext.Create(testDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);
            var mockProj       = ProjectRootElement.Create();

            var migrationSettings = new MigrationSettings(testDirectory, testDirectory, "1.0.0", mockProj);
            var migrationInputs   = new MigrationRuleInputs(
                new[] { projectContext },
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);

            mockProj.Properties.Count(p => p.Name == "TargetFrameworkIdentifier").Should().Be(0);
            mockProj.Properties.Count(p => p.Name == "TargetFrameworkVersion").Should().Be(0);
        }
        public void RuntimeOptionsAreCopiedFromProjectJsonToRuntimeConfigTemplateJsonFile()
        {
            var testInstance = TestAssets.Get("TestAppWithRuntimeOptions")
                               .CreateInstance()
                               .WithSourceFiles()
                               .Root;

            var projectDir  = testInstance.FullName;
            var projectPath = Path.Combine(projectDir, "project.json");

            var project           = JObject.Parse(File.ReadAllText(projectPath));
            var rawRuntimeOptions = (JObject)project.GetValue("runtimeOptions");

            var projectContext = ProjectContext.Create(projectDir, FrameworkConstants.CommonFrameworks.NetCoreApp10);

            var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(projectDir, projectDir, default(ProjectRootElement));
            var testInputs   = new MigrationRuleInputs(new[] { projectContext }, null, null, null);

            new MigrateRuntimeOptionsRule().Apply(testSettings, testInputs);

            var migratedRuntimeOptionsPath = Path.Combine(projectDir, s_runtimeConfigFileName);

            File.Exists(migratedRuntimeOptionsPath).Should().BeTrue();

            var migratedRuntimeOptionsContent = JObject.Parse(File.ReadAllText(migratedRuntimeOptionsPath));

            JToken.DeepEquals(rawRuntimeOptions, migratedRuntimeOptionsContent).Should().BeTrue();
        }
예제 #11
0
        public int Execute()
        {
            var projectsToMigrate = GetProjectsToMigrate(_projectArg);

            var msBuildTemplate = _templateFile != null?
                                  ProjectRootElement.TryOpen(_templateFile) : _temporaryDotnetNewProject.MSBuildProject;

            var sdkVersion = _sdkVersion ?? _temporaryDotnetNewProject.MSBuildProject.GetSdkVersion();

            EnsureNotNull(sdkVersion, "Null Sdk Version");

            MigrationReport migrationReport = null;

            foreach (var project in projectsToMigrate)
            {
                var projectDirectory       = Path.GetDirectoryName(project);
                var outputDirectory        = projectDirectory;
                var migrationSettings      = new MigrationSettings(projectDirectory, outputDirectory, sdkVersion, msBuildTemplate, _xprojFilePath);
                var projectMigrationReport = new ProjectMigrator().Migrate(migrationSettings, _skipProjectReferences);

                if (migrationReport == null)
                {
                    migrationReport = projectMigrationReport;
                }
                else
                {
                    migrationReport = migrationReport.Merge(projectMigrationReport);
                }
            }

            WriteReport(migrationReport);

            return(migrationReport.FailedProjectsCount);
        }
예제 #12
0
        private const int CommandTimeout = 10 * 60; // We want to avoid timeout exception. We don't care about performance here. The query can take long time if all the outer database are working simultaneously on the same machine

        protected void ApplyDefaultColumnNamesMapping(DatabaseSchema dbSchema, MigrationSettings settings, bool binaryToAttachment = false)
        {
            foreach (var collection in settings.Collections)
            {
                ApplyDefaultColumnNamesMapping(dbSchema, collection, binaryToAttachment);
            }
        }
예제 #13
0
        public void Migrating_Single_TFM_project_Populates_TargetFramework()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssetsManager)
                                .FromTestAssetBase("TestAppWithRuntimeOptions")
                                .WithCustomProperty("buildOptions", new Dictionary <string, string>
            {
                { "emitEntryPoint", "false" }
            })
                                .SaveToDisk(testDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory);
            var mockProj        = ProjectRootElement.Create();

            // Run BuildOptionsRule
            var migrationSettings = new MigrationSettings(testDirectory, testDirectory, "1.0.0", mockProj);
            var migrationInputs   = new MigrationRuleInputs(
                projectContexts,
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);
            Console.WriteLine(mockProj.RawXml);

            mockProj.Properties.Count(p => p.Name == "TargetFramework").Should().Be(1);
        }
예제 #14
0
        /// <summary>
        /// Method for saving migration profiles
        /// </summary>
        /// <param name="sender">sender of event</param>
        /// <param name="e">event of sender</param>
        private void SaveMigrationProfileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MigrationSettings settings = this.UIToSettings();

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "XML files (*.xml)|*.xml";
            saveFileDialog1.Title  = "Save the current profile";
            saveFileDialog1.ShowDialog();

            if (saveFileDialog1.FileName != string.Empty)
            {
                try
                {
                    TextWriter    writer     = new StreamWriter(saveFileDialog1.FileName);
                    XmlSerializer serializer = new XmlSerializer(typeof(MigrationSettings));
                    serializer.Serialize(writer, settings);
                    writer.Close();
                    this.log.AddMessage("Settings saved to \"" + saveFileDialog1.FileName + "\"");
                }
                catch (XmlException xe)
                {
                    Debug.WriteLine(xe.ToString());
                    MessageBox.Show("XML writing error. The settings file could not be written correctly!");
                    this.log.AddMessage("Settings could not be saved to \"" + saveFileDialog1.FileName + "\". Error: " + xe.Message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    MessageBox.Show("Error: Could not write file to disk. Original error: " + ex.Message);
                    this.log.AddMessage("Settings could not be saved to \"" + saveFileDialog1.FileName + "\". Error: " + ex.Message);
                }
            }
        }
예제 #15
0
        public void MigratingLibWithMultipleTFMsDoesNotAddRuntimes()
        {
            var testDirectory = Temp.CreateDirectory().Path;
            var testPJ        = new ProjectJsonBuilder(TestAssets)
                                .FromTestAssetBase("PJLibWithMultipleFrameworks")
                                .SaveToDisk(testDirectory);

            var projectContexts = ProjectContext.CreateContextForEachFramework(testDirectory);
            var mockProj        = ProjectRootElement.Create();

            var migrationSettings =
                MigrationSettings.CreateMigrationSettingsTestHook(testDirectory, testDirectory, mockProj);
            var migrationInputs = new MigrationRuleInputs(
                projectContexts,
                mockProj,
                mockProj.AddItemGroup(),
                mockProj.AddPropertyGroup());

            new MigrateTFMRule().Apply(migrationSettings, migrationInputs);

            var reason = "Should not add runtime identifiers for libraries";

            mockProj.Properties.Count(p => p.Name == "RuntimeIdentifiers").Should().Be(0, reason);
            mockProj.Properties.Count(p => p.Name == "RuntimeIdentifier").Should().Be(0, reason);
        }
예제 #16
0
        public void Apply(MigrationSettings migrationSettings, MigrationRuleInputs migrationRuleInputs)
        {
            var csproj        = migrationRuleInputs.OutputMSBuildProject;
            var propertyGroup = migrationRuleInputs.CommonPropertyGroup;

            CleanExistingProperties(csproj);
            CleanExistingPackageReferences(csproj);

            if (migrationRuleInputs.ProjectContexts.Count() == 1)
            {
                _transformApplicator.Execute(
                    FrameworkTransform.Transform(
                        migrationRuleInputs.ProjectContexts.Single().TargetFramework),
                    propertyGroup,
                    mergeExisting: true);
            }
            else
            {
                _transformApplicator.Execute(
                    FrameworksTransform.Transform(
                        migrationRuleInputs.ProjectContexts.Select(p => p.TargetFramework)),
                    propertyGroup,
                    mergeExisting: true);
            }
        }
예제 #17
0
        public async Task CanLimitRows(MigrationProvider provider)
        {
            using (WithSqlDatabase(provider, out var connectionString, out string schemaName, "basic"))
            {
                var driver = DatabaseDriverDispatcher.CreateDriver(provider, connectionString);

                using (var store = GetDocumentStore())
                {
                    var db = await GetDocumentDatabaseInstanceFor(store);

                    var settings = new MigrationSettings
                    {
                        Collections = new List <RootCollection>
                        {
                            new RootCollection(schemaName, "movie", "Movies")
                        },
                        MaxRowsPerTable = 2
                    };

                    using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
                        using (db.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                        {
                            var schema = driver.FindSchema();
                            ApplyDefaultColumnNamesMapping(schema, settings);
                            await driver.Migrate(settings, schema, db, context, token : cts.Token);
                        }

                    using (var session = store.OpenSession())
                    {
                        Assert.Equal(2, session.Advanced.LoadStartingWith <JObject>("Movies/").Length);
                    }
                }
            }
        }
예제 #18
0
        public void Apply(MigrationSettings migrationSettings, MigrationRuleInputs migrationRuleInputs)
        {
            var csproj         = migrationRuleInputs.OutputMSBuildProject;
            var projectContext = migrationRuleInputs.DefaultProjectContext;

            var propertyGroup = _configurationPropertyGroup ?? migrationRuleInputs.CommonPropertyGroup;
            var itemGroup     = _configurationItemGroup ?? migrationRuleInputs.CommonItemGroup;

            var compilerOptions = projectContext.ProjectFile.GetCompilerOptions(null, null);

            // If we're in a configuration, we need to be careful not to overwrite values from BuildOptions
            // without a configuration
            if (_configurationBuildOptions == null)
            {
                CleanExistingProperties(csproj);

                PerformPropertyAndItemMappings(
                    compilerOptions,
                    propertyGroup,
                    itemGroup,
                    _transformApplicator,
                    migrationSettings.ProjectDirectory);
            }
            else
            {
                PerformConfigurationPropertyAndItemMappings(
                    compilerOptions,
                    _configurationBuildOptions,
                    propertyGroup,
                    itemGroup,
                    _transformApplicator,
                    migrationSettings.ProjectDirectory);
            }
        }
예제 #19
0
        static void Main(string[] args)
        {
            string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Console.WriteLine("BV Migrate | " + version);
            Console.WriteLine();

            if (args.Length < 2)
            {
                ShowHelp();
                return;
            }

            Console.WriteLine("Parsing Arguments");

            MigrationSettings data = new MigrationSettings();

            foreach (string arg in args)
            {
                ParseArg(data, arg);
            }

            data.PrepArgs();

            MigrationService migrator = new MigrationService(data);

            migrator.ProgressReport += new MigrationService.ProgressReportDelegate(builder_ProgressReport);
            migrator.StartMigration();
        }
        public void SpecifiedDefaultPropertiesAreRemovedWhenTheyExistInTheCsprojTemplate()
        {
            // Setup project with default properties
            var defaultPropertiesExpectedToBeRemoved = new string[]
            {
                "OutputType",
                "TargetExt"
            };

            var defaultValue = "defaultValue";

            var templateProj         = ProjectRootElement.Create();
            var defaultPropertyGroup = templateProj.AddPropertyGroup();

            foreach (var defaultPropertyName in defaultPropertiesExpectedToBeRemoved)
            {
                defaultPropertyGroup.AddProperty(defaultPropertyName, defaultValue);
            }

            // Setup projectcontext
            var testProjectDirectory = TestAssetsManager.CreateTestInstance("TestAppWithRuntimeOptions").Path;
            var projectContext       = ProjectContext.Create(testProjectDirectory, FrameworkConstants.CommonFrameworks.NetCoreApp10);

            var testSettings = new MigrationSettings(testProjectDirectory, testProjectDirectory, templateProj);
            var testInputs   = new MigrationRuleInputs(new[] { projectContext }, templateProj, templateProj.AddItemGroup(),
                                                       templateProj.AddPropertyGroup());

            new MigrateBuildOptionsRule().Apply(testSettings, testInputs);

            defaultPropertyGroup.Properties.Count.Should().Be(0);
        }
예제 #21
0
        public void Apply(MigrationSettings migrationSettings, MigrationRuleInputs migrationRuleInputs)
        {
            MigrationTrace.Instance.WriteLine(String.Format(LocalizableStrings.ExecutingRule, nameof(MigrateConfigurationsRule)));
            var projectContext = migrationRuleInputs.DefaultProjectContext;
            var configurations = projectContext.ProjectFile.GetConfigurations().ToList();

            var frameworks = new List <NuGetFramework>();

            frameworks.AddRange(projectContext.ProjectFile.GetTargetFrameworks().Select(t => t.FrameworkName));

            if (!configurations.Any() && !frameworks.Any())
            {
                MigrationTrace.Instance.WriteLine(String.Format(LocalizableStrings.NoConfigurationOrFrameworkFoundInProject, nameof(MigrateConfigurationsRule)));

                return;
            }

            foreach (var framework in frameworks)
            {
                MigrateConfiguration(projectContext.ProjectFile, framework, migrationSettings, migrationRuleInputs);
            }

            foreach (var configuration in configurations)
            {
                MigrateConfiguration(projectContext.ProjectFile, configuration, migrationSettings, migrationRuleInputs);
            }
        }
예제 #22
0
        public async Task Attachments(MigrationProvider provider)
        {
            using (WithSqlDatabase(provider, out var connectionString, out string schemaName, "basic"))
            {
                var driver = DatabaseDriverDispatcher.CreateDriver(provider, connectionString);
                using (var store = GetDocumentStore())
                {
                    var db = await GetDocumentDatabaseInstanceFor(store);

                    var settings = new MigrationSettings
                    {
                        Collections = new List <RootCollection>
                        {
                            new RootCollection(schemaName, "actor", "Actors")
                            {
                                NestedCollections = new List <EmbeddedCollection>
                                {
                                    new EmbeddedCollection(schemaName, "actor_movie", RelationType.OneToMany, new List <string> {
                                        "a_id"
                                    }, "Movies")
                                    {
                                        NestedCollections = new List <EmbeddedCollection>
                                        {
                                            new EmbeddedCollection(schemaName, "movie", RelationType.ManyToOne, new List <string> {
                                                "m_id"
                                            }, "Movie")
                                        }
                                    }
                                }
                            }
                        }
                    };

                    using (db.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                    {
                        var schema = driver.FindSchema();
                        ApplyDefaultColumnNamesMapping(schema, settings, true);
                        await driver.Migrate(settings, schema, db, context);
                    }

                    using (var session = store.OpenSession())
                    {
                        var actor32 = session.Load <JObject>("Actors/32");
                        Assert.False(actor32.ContainsKey("Photo"));
                        Assert.False(actor32.ContainsKey("photo"));
                        var attachments = session.Advanced.Attachments.GetNames(actor32)
                                          .Select(x => x.Name)
                                          .OrderBy(x => x)
                                          .ToArray();

                        Assert.Equal(new[] { "Movies_0_Movie_File", "Movies_1_Movie_File", "Photo" }, attachments);

                        var actor34 = session.Load <JObject>("Actors/34");
                        Assert.False(actor34.ContainsKey("Photo"));
                        Assert.False(actor34.ContainsKey("photo"));
                        Assert.Equal(0, session.Advanced.Attachments.GetNames(actor34).Length);
                    }
                }
            }
        }
예제 #23
0
        public void Apply(MigrationSettings migrationSettings, MigrationRuleInputs migrationRuleInputs)
        {
            MigrationTrace.Instance.WriteLine($"Executing rule: {nameof(MigrateConfigurationsRule)}");
            var projectContext = migrationRuleInputs.DefaultProjectContext;
            var configurations = projectContext.ProjectFile.GetConfigurations().ToList();

            var frameworks = new List <NuGetFramework>();

            frameworks.AddRange(projectContext.ProjectFile.GetTargetFrameworks().Select(t => t.FrameworkName));

            if (!configurations.Any() && !frameworks.Any())
            {
                MigrationTrace.Instance.WriteLine($"{nameof(MigrateConfigurationsRule)}: No configuration or framework build options found in project");
                return;
            }

            foreach (var framework in frameworks)
            {
                MigrateConfiguration(projectContext.ProjectFile, framework, migrationSettings, migrationRuleInputs);
            }

            foreach (var configuration in configurations)
            {
                MigrateConfiguration(projectContext.ProjectFile, configuration, migrationSettings, migrationRuleInputs);
            }
        }
예제 #24
0
        public void ItHasWarningWhenMigratingADeprecatedProjectJson()
        {
            var testProjectDirectory = TestAssets
                                       .GetProjectJson(TestAssetKinds.NonRestoredTestProjects, "PJDeprecatedCompile")
                                       .CreateInstance()
                                       .WithSourceFiles()
                                       .Root
                                       .GetDirectory("project")
                                       .FullName;

            var mockProj     = ProjectRootElement.Create();
            var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(
                testProjectDirectory,
                testProjectDirectory,
                mockProj);

            var projectMigrator = new ProjectMigrator(new FakeEmptyMigrationRule());
            var report          = projectMigrator.Migrate(testSettings);

            var projectReport  = report.ProjectMigrationReports.First();
            var warningMessage = projectReport.Warnings.First();

            warningMessage.Should().Contain("MIGRATE1011::Deprecated Project:");
            warningMessage.Should().Contain("The 'compile' option is deprecated. Use 'compile' in 'buildOptions' instead. (line: 3, file:");
        }
예제 #25
0
        public void ItHasErrorWhenMigratingAProjectJsonWithoutAFrameworks()
        {
            var testInstance = TestAssets.Get(
                "NonRestoredTestProjects",
                "TestLibraryWithProjectFileWithoutFrameworks")
                               .CreateInstance()
                               .WithSourceFiles();

            var testProjectDirectory = testInstance.Root.FullName;

            var mockProj     = ProjectRootElement.Create();
            var testSettings = MigrationSettings.CreateMigrationSettingsTestHook(
                testProjectDirectory,
                testProjectDirectory,
                mockProj);

            var projectMigrator = new ProjectMigrator(new FakeEmptyMigrationRule());
            var report          = projectMigrator.Migrate(testSettings);

            var projectReport = report.ProjectMigrationReports.First();

            projectReport.Errors.First().GetFormattedErrorMessage()
            .Should().Contain("MIGRATE1013::No Project:")
            .And.Contain($"The project.json specifies no target frameworks in {testProjectDirectory}");
        }
        public void RuntimeOptions_are_copied_from_projectJson_to_runtimeconfig_template_json_file()
        {
            var testInstance = TestAssetsManager.CreateTestInstance("TestAppWithRuntimeOptions").WithLockFiles();
            var projectDir   = testInstance.Path;
            var projectPath  = Path.Combine(testInstance.Path, "project.json");

            var project           = JObject.Parse(File.ReadAllText(projectPath));
            var rawRuntimeOptions = (JObject)project.GetValue("runtimeOptions");

            var projectContext = ProjectContext.Create(projectDir, FrameworkConstants.CommonFrameworks.NetCoreApp10);

            var testSettings = new MigrationSettings(projectDir, projectDir, "1.0.0", default(ProjectRootElement));
            var testInputs   = new MigrationRuleInputs(new[] { projectContext }, null, null, null);

            new MigrateRuntimeOptionsRule().Apply(testSettings, testInputs);

            var migratedRuntimeOptionsPath = Path.Combine(projectDir, s_runtimeConfigFileName);

            File.Exists(migratedRuntimeOptionsPath).Should().BeTrue();
            Console.WriteLine(migratedRuntimeOptionsPath);

            var migratedRuntimeOptionsContent = JObject.Parse(File.ReadAllText(migratedRuntimeOptionsPath));

            JToken.DeepEquals(rawRuntimeOptions, migratedRuntimeOptionsContent).Should().BeTrue();
        }
예제 #27
0
        /// <summary>
        /// Method for loading migration profiles
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">event of the sender</param>
        private void LoadMigrationProfileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter           = "XML files (*.xml)|*.xml";
            openFileDialog1.Title            = "Open migration profile";
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    TextReader        reader     = new StreamReader(openFileDialog1.FileName);
                    XmlSerializer     serializer = new XmlSerializer(typeof(MigrationSettings));
                    MigrationSettings settings   = (MigrationSettings)serializer.Deserialize(reader);
                    reader.Close();
                    this.SettingsToUI(settings);
                    this.log.AddMessage("Settings file \"" + openFileDialog1.FileName + "\" loaded");
                }
                catch (XmlException xe)
                {
                    Debug.WriteLine(xe.ToString());
                    this.log.AddMessage("Settings file \"" + openFileDialog1.FileName + "\" could not be loaded due to XML error. Original Message: " + xe.Message);
                    MessageBox.Show("XML reading error. The settings file is corrupted!");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    this.log.AddMessage("Settings file \"" + openFileDialog1.FileName + "\" could not be loaded. Error: " + ex.Message);
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
예제 #28
0
        public async Task CanMigrateEmbedOnChild(MigrationProvider provider)
        {
            using (WithSqlDatabase(provider, out var connectionString, out string schemaName, "basic"))
            {
                var driver = DatabaseDriverDispatcher.CreateDriver(provider, connectionString);
                using (var store = GetDocumentStore())
                {
                    var collection = new RootCollection(schemaName, "order_item", "OrderItems")
                    {
                        NestedCollections = new List <EmbeddedCollection>
                        {
                            new EmbeddedCollection(schemaName, "order", RelationType.ManyToOne, new List <string> {
                                "order_id"
                            }, "Order")
                        }
                    };

                    var db = await GetDocumentDatabaseInstanceFor(store);

                    var settings = new MigrationSettings
                    {
                        Collections = new List <RootCollection>
                        {
                            collection
                        }
                    };

                    using (db.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                    {
                        var schema = driver.FindSchema();
                        ApplyDefaultColumnNamesMapping(schema, settings);
                        await driver.Migrate(settings, schema, db, context);
                    }

                    using (var session = store.OpenSession())
                    {
                        var orderItem = session.Load <JObject>("OrderItems/10");

                        Assert.NotNull(orderItem);
                        // price and metadata, Id (OrderItems/10), Order
                        Assert.Equal(4, orderItem.Properties().Count());

                        Assert.Equal("OrderItems", orderItem["@metadata"]["@collection"]);
                        Assert.Equal(110, orderItem["Price"]);
                        Assert.Equal("OrderItems/10", orderItem["Id"]);
                        var nestedOrder = orderItem["Order"];
                        Assert.NotNull(nestedOrder);
                        Assert.Equal(1, nestedOrder.Count());
                        Assert.Equal(440, nestedOrder["Total"]);

                        var orderItem2 = session.Load <JObject>("OrderItems/11");
                        Assert.NotNull(orderItem2);
                    }

                    var collectionStatistics = store.Maintenance.Send(new GetCollectionStatisticsOperation());
                    Assert.Equal(2, collectionStatistics.CountOfDocuments);
                }
            }
        }
예제 #29
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            MigrationSettings settings = (MigrationSettings)e.Argument;
            MigrationService  svc      = new MigrationService(settings);

            svc.ProgressReport += new MigrationService.ProgressReportDelegate(svc_ProgressReport);
            svc.StartMigration();
        }
예제 #30
0
        public void Apply(MigrationSettings migrationSettings, MigrationRuleInputs migrationRuleInputs)
        {
            var outputName = migrationRuleInputs.DefaultProjectContext.GetProjectName();

            var outputProject = Path.Combine(migrationSettings.OutputDirectory, outputName + ".csproj");

            migrationRuleInputs.OutputMSBuildProject.Save(outputProject);
        }
예제 #31
0
        public void Migrate(MigrationSettings s)
        {
            settings = s;

            try
            {
                if (s.ClearProducts)
                {
                    ClearProductIndexes();
                }
                ReindexProducts();
            }
            catch (Exception e)
            {
                wl("ERROR: " + e.Message);
                wl(e.StackTrace);
            }
        }
        private static void Test(Language language, CodeDomProvider provider)
        {
            MigrationSettings settings = new MigrationSettings();
            settings.VSProjectName = "ClassLibrary1";
            settings.Namespace = "ClassLibrary1";
            settings.Language = language;

            MigrationContext context = new MigrationContext(
                settings,
                null,
                null,
                null,
                null,
                provider,
                null,
                null,
                new EmptyOperationStatus(),
                null);
            context.LocalizedStrings.Add("One", "Uno");
            context.References.Add("AxSLXControls, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL", @"AxSLXControls.dll");
            context.References.Add(typeof (Form).Assembly.GetName().Name, null);

            Plugin plugin = new Plugin();
            plugin.Family = "Test";
            plugin.Name = "Class1";
            plugin.Blob.Data = new byte[0];
            ScriptInfo script = new ScriptInfo(plugin);
            context.Scripts.Add("0", script);

            MigrationContextHolderService holder = new MigrationContextHolderService();
            holder.Context = context;

            VSProjectService p = new VSProjectService();
            p.ContextHolder = holder;
            p.Generate();
        }
예제 #33
0
        public void Migrate(MigrationSettings s)
        {
            wl("");
            wl("MerchantTribe Migrator Started");
            wl("");

            settings = s;

            try
            {

                // Clear Products
                if (s.ClearProducts && s.ImportProductImagesOnly == false)
                {
                    ClearProducts();
                }

                // Clear Categories
                if (s.ClearCategories)
                {
                    ClearCategories();
                }

                // Clear Users
                if (s.ClearUsers)
                {
                    ClearUsers();
                }

                // Users 
                if (s.ImportUsers)
                {
                    //ImportRoles();
                    ImportPriceGroups();
                    ImportUsers();
                }

                // Affiliates
                if (s.ImportAffiliates)
                {
                    ImportAffiliates();
                }

                // Taxes and Shipping Classes are prerequisite for product import
                if (s.ImportOtherSettings || (s.ImportProducts && s.SkipProductPrerequisites == false))
                {
                    ImportTaxSchedules();
                    ImportTaxes();
                }

                // Vendors and Manufacturers
                if ((s.ImportProducts && s.ImportProductImagesOnly == false && s.SkipProductPrerequisites == false) || s.ImportCategories)
                {
                    ImportVendors();
                    ImportManufacturers();
                }

                // Product Types
                if (s.ImportProducts && s.ImportProductImagesOnly == false && s.SkipProductPrerequisites == false)
                {
                    //ImportProductProperties();
                    ImportProductTypes();
                }

                // Categories
                if (s.ImportCategories)
                {
                    ImportCategories();
                }

                if (s.ImportProducts)
                {
                    if (s.ImportProductImagesOnly == false && s.SkipProductPrerequisites == false)
                    {                        
                        ImportProductChoices();
                    }

                    ImportProducts();                    

                    if (s.ImportProductImagesOnly == false)
                    {
                        ImportRelatedItems();
                    }
                }

                if (s.ImportOrders)
                {
                    ImportOrders();
                }

                if (s.ImportOtherSettings)
                {
                    ImportMailingLists();
                    ImportPolicies();
                    ImportFraudData();
                }
            }
            catch (Exception e)
            {
                wl("ERROR: " + e.Message);
                wl(e.StackTrace);
            }
        }
예제 #34
0
        public static void Test(MigrationWorkItem workItem)
        {
            //TODO: remove workItem depency, add context holder, uncomment broken bits

            IProject project = workItem.Services.Get<IProjectContextService>().ActiveProject;
            OrmModel orm = project.Models.Get<OrmModel>();
            QuickFormModel qfModel = project.Models.Get<QuickFormModel>();
            MigrationSettings s = new MigrationSettings();
            s.PackageName = "test";
            MigrationContext c = new MigrationContext(
                s,
                orm.Packages[0],
                null,
                null,
                null,
                null,
                null,
                workItem.Log,
                new EmptyOperationStatus(),
                null);

            OrmEntity entity = orm.Packages[1].Entities[0];
            IList<IQuickFormDefinition> forms = qfModel.LoadDefinitions(entity);
            FormInfo form = new FormInfo(null, "0", false, "0", "0", 0, 0);
            form.QuickForm = (IQuickFormDefinition) forms[0];
            c.Forms.Add("0", form);
            c.Forms.Add("0x", form);
            form = new FormInfo(null, "1", false, "1", "1", 1, 1);
            form.QuickForm = (IQuickFormDefinition) forms[1];
            form.Entity = entity;
            c.Forms.Add("1", form);
            c.Forms.Add("1x", form);

            entity = orm.Packages[1].Entities[12];
            forms = qfModel.LoadDefinitions(entity);
            form = new FormInfo(null, "2", false, "2", "2", 2, 2);
            form.QuickForm = (IQuickFormDefinition) forms[0];
            c.Forms.Add("2", form);
            c.Forms.Add("2x", form);
            form = new FormInfo(null, "3", false, "3", "3", 3, 3);
            form.QuickForm = (IQuickFormDefinition) forms[1];
            form.Entity = entity;
            c.Forms.Add("3", form);
            c.Forms.Add("3x", form);

            //c.Relationships.Add("0", new OrmRelationship(orm.Relationships[0], true));
            //c.Relationships.Add("0x", new OrmRelationship(orm.Relationships[0], true));
            //c.Relationships.Add("1", new OrmRelationship(orm.Relationships[1], true));
            //c.Relationships.Add("1x", new OrmRelationship(orm.Relationships[1], true));

            PortalApplication portalApp = PortalApplication.Get("SlxClient");
            portalApp.Model = project.Models.Get<PortalModel>();

            LinkedFile file = portalApp.SupportFiles.GetFiles()[0];
            c.LinkedFiles.Add(file);
            c.LinkedFiles.Add(file);
            file = portalApp.SupportFiles.GetFiles()[1];
            c.LinkedFiles.Add(file);
            c.LinkedFiles.Add(file);
            file = portalApp.SupportFiles.GetFolders()[1].GetFiles()[0];
            c.LinkedFiles.Add(file);
            c.LinkedFiles.Add(file);
            file = portalApp.SupportFiles.GetFolders()[1].GetFiles()[1];
            c.LinkedFiles.Add(file);
            c.LinkedFiles.Add(file);

            //SmartPartMapping part = portalApp.Pages[0].SmartParts[0];
            //c.SmartParts.Add("0", part);
            //c.SmartParts.Add("0x", part);
            //part = portalApp.Pages[0].SmartParts[1];
            //c.SmartParts.Add("1", part);
            //c.SmartParts.Add("1x", part);
            //part = portalApp.Pages[1].SmartParts[0];
            //c.SmartParts.Add("2", part);
            //c.SmartParts.Add("2x", part);
            //part = portalApp.Pages[1].SmartParts[1];
            //c.SmartParts.Add("3", part);
            //c.SmartParts.Add("3x", part);

            IManifestService b = workItem.Services.Get<IManifestService>();
            b.Generate();
        }
예제 #35
0
        public void Execute(MigrationSettings settings, IOperationStatus status)
        {
            Guard.ArgumentNotNull(settings, "settings");
            Guard.ArgumentNotNull(status, "status");

            _settings = settings;
            _status = status;
            int stepCount = _steps.Length;

            if (_settings.ProcessScripts)
            {
                stepCount += (_migrators.Length - 1)*3;
            }
            else
            {
                stepCount += (_migrators.Length - 1)*2;
            }

            _status.Reset(stepCount);

            foreach (StepHandler step in _steps)
            {
                step();

                if (_status.IsCancelled)
                {
                    break;
                }
            }

            if (!_status.IsCancelled && MigrationComplete != null)
            {
                MigrationComplete(this, new MigrationCompleteEventArgs(_report));
            }

            _settings = null;
            _status = null;
        }
예제 #36
0
        public void Migrate(MigrationSettings s)
        {
            wl("");
            wl("BVC 2004 Migrator Started");
            wl("");

            settings = s;

            try
            {
                data.bvc2004Entities oldTest = GetOldDatabase();                
            }
            catch (Exception ex2)
            {
                wl("EXCEPTION While attempting to create old database model!");
                wl(ex2.Message);
                wl(ex2.StackTrace);
                return;
            }


            try
            {

                // Clear Products
                if (s.ClearProducts && s.ImportProductImagesOnly == false)
                {
                    ClearProducts();
                }

                // Clear Categories
                if (s.ClearCategories)
                {
                    ClearCategories();
                }

                // Clear Users
                if (s.ClearUsers)
                {
                    ClearUsers();
                }

                // Users 
                if (s.ImportUsers)
                {
                    //ImportRoles();
                    ImportPriceGroups();
                    ImportUsers();
                }

                // Affiliates
                if (s.ImportAffiliates)
                {
                    ImportAffiliates();
                }

                // Tax Classes are prerequisite for product import
                if (s.ImportOtherSettings || (s.ImportProducts && s.SkipProductPrerequisites == false))
                {
                    ImportTaxSchedules();
                    ImportTaxes();
                }

                // Vendors and Manufacturers
                if ((s.ImportProducts && s.ImportProductImagesOnly == false && s.SkipProductPrerequisites == false) || s.ImportCategories)
                {
                    ImportVendors();
                    ImportManufacturers();
                }

                // Product Types
                if (s.ImportProducts && s.ImportProductImagesOnly == false && s.SkipProductPrerequisites == false)
                {
                    ImportProductProperties();
                    ImportProductTypes();
                }

                // Categories
                if (s.ImportCategories)
                {
                    ImportCategories();
                }

                if (s.ImportProducts)
                {
                    if (s.ImportProductImagesOnly == false && s.SkipProductPrerequisites == false)
                    {
                        ImportProductChoices();
                    }

                    MigrateProductFileDownloads();
                    ImportProducts();

                    if (s.ImportProductImagesOnly == false)
                    {
                        ImportRelatedItems();
                    }
                }

                if (s.ImportOrders)
                {
                    ImportOrders();
                }

                if (s.ImportOtherSettings)
                {
                    ImportMailingLists();
                    ImportPolicies();
                    ImportFraudData();
                }
            }
            catch (Exception e)
            {
                wl("ERROR: " + e.Message);
                wl(e.StackTrace);
            }
        }
예제 #37
0
        protected override void OnLoad(EventArgs e)
        {
            Icon = Icon.FromHandle(Resources.ToolIcon.GetHicon());
            _settings = MigrationSettings.GetCurrentMigrationSettings(_workItem);
            bindingSource.DataSource = _settings;

            switch (_settings.Language)
            {
                case Language.CSharp:
                    btnCSharp.Checked = true;
                    break;
                case Language.VBNet:
                    btnVBnet.Checked = true;
                    break;
                default:
                    btnOther.Checked = true;
                    txtCustomLanguage.ReadOnly = !btnOther.Checked;
                    break;
            }

            PopulateComboBoxes();

            chkMergeLabels.Checked = _settings.MergeLabels;

            base.OnLoad(e);
        }