예제 #1
0
        public void ImportOne_WithSameTranslation_HasMoreTranslationsAlready()
        {
            var incoming = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "no", Value = "Resurs 1"
                        }
                    }
                }
            };
            var existing = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = null
                        },
                        new LocalizationResourceTranslation {
                            Language = "no", Value = "Resurs 1"
                        }
                    }
                }
            };
            var sut = new ResourceImporter();

            var result = sut.DetectChanges(incoming, existing);

            Assert.Empty(result);
        }
예제 #2
0
        public void ImportSome_EmptyDatabase_OnlyInserts()
        {
            var incoming = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1"
                        }
                    }
                },
                new LocalizationResource("key2")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 2"
                        }
                    }
                }
            };
            var sut = new ResourceImporter();

            var result = sut.DetectChanges(incoming, new List <LocalizationResource>());

            Assert.Equal(incoming.Count, result.Count(c => c.ChangeType == ChangeType.Insert));
        }
예제 #3
0
        /// <summary>
        /// Reads exported metadata json file and deploys all the source resources into destination subscription.
        /// </summary>
        /// <param name="parameters"> Collection of key value paired input parameters <example>
        /// Operation "Import" SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07"
        /// DestinationDCName "West US" SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings" SourceCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7"
        /// DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings" DestinationCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7"
        /// ImportMetadataFilePath "D:\\DataCenterMigration\mydata.json" MapperXmlFilePath "D:\\DataCenterMigration\mydata.xml" DestinationPrefixName "dc"
        /// RetryCount "5" MinBackoff "3" MaxBackoff "3" DeltaBackoff "90" QuietMode "True" RollBackOnFailure "True" ResumeImport "True" </example></param>
        public void ImportSubscriptionMetadata(IDictionary <string, string> parameters)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.ExecutionStarted);
            bool boolValue;

            if (!parameters.Keys.Contains(Constants.Parameters.QuietMode))
            {
                quietMode = false;
            }
            else
            {
                quietMode = bool.TryParse(parameters[Constants.Parameters.QuietMode], out boolValue) ? boolValue : false;
            }

            Logger.Info(methodName, string.Format(ProgressResources.ImportMetadataStarted, parameters[Constants.Parameters.ImportMetadataFilePath]));
            ReportProgress(string.Format(ProgressResources.ImportMetadataStarted, parameters[Constants.Parameters.ImportMetadataFilePath]));

            // Validate the input paramters and export them into parameters class.
            ImportParameters importParameters = ConfigurationReader.ValidateAndConvertImportParameters(parameters, true);

            // Import metadata.
            ResourceImporter importer = new ResourceImporter(importParameters, this);

            importer.ImportSubscriptionMetadata();

            ReportProgress(ProgressResources.ImportMetadataCompleted);

            Logger.Info(methodName, ProgressResources.ImportMetadataCompleted);
            Logger.Info(methodName, ProgressResources.ExecutionCompleted);
        }
        public override void OnFinish(object sender, EventArgs e)
        {
            var uploadedFile = GetBinding <UploadedFile>("UploadedFile");

            using (var sr = new StreamReader(uploadedFile.FileStream))
            {
                var txt = sr.ReadToEnd();

                var importModel = ImportExportModel.FromXml(txt);
                var importer    = new ResourceImporter(importModel);

                var result = importer.Import();

                var sb = new StringBuilder();

                sb.AppendLine("Languages: " + String.Join(", ", result.Languages.Select(l => l.Name)));
                sb.AppendLine("ResourceSets: " + String.Join(", ", result.ResourceSets.Select(s => s ?? "Website")));
                sb.AppendLine();
                sb.AppendLine("Keys added: " + result.KeysAdded);
                sb.AppendLine("Values added: " + result.ValuesAdded);
                sb.AppendLine("Values updated: " + result.ValuesUpdated + " (were the same: " + result.ValuesWereTheSame + ")");

                ShowMessage(DialogType.Message, "Import result", sb.ToString());
            }
        }
        protected override void Confirm(object sender, EventArgs e)
        {
            FileInfo level     = levelFile.File;
            FileInfo thumbnail = thumbnailFile.File;

            if (level?.Exists != true)
            {
                MessageBox.Show("The specified level file could not be found!", DIALOG_CAPTION_MISSING_FILE);
                return;
            }

            if (thumbnail?.Exists != true)
            {
                MessageBox.Show("The specified thumbnail file could not be found!", DIALOG_CAPTION_MISSING_FILE);
                return;
            }

            ResourceImporter.ImportFile(editor, level, "levels", out string levelPath);
            Data.file = levelPath;

            ResourceImporter.ImportFile(editor, thumbnail, "textures", out string thumbnailPath);
            Data.thumbnail = thumbnailPath;

            base.Confirm(sender, e);
        }
예제 #6
0
        public void UpdateAndCheckHistory()
        {
            _store.EraseData();

            var importer = new ResourceImporter(new Uri("http://localhost"));

            importer.QueueNewEntry(_stockPatient);
            importer.QueueNewEntry(_stockOrg);

            var dd = (ResourceEntry)clone(_stockPatient);

            ((Patient)dd.Resource).Name[0].Text = "Donald Duck";
            dd.Links.SelfLink = null;
            importer.QueueNewEntry(dd);

            importer.QueueNewDeletedEntry(_stockPatient.Id);
            importer.QueueNewDeletedEntry(_stockOrg.Id);

            var imported = importer.ImportQueued();
            var origId   = imported.First().Id;

            _store.AddEntries(imported);

            var history = _store.ListVersionsById(origId)
                          .OrderBy(be => new ResourceLocation(be.Links.SelfLink).VersionId);

            Assert.IsNotNull(history);
            Assert.AreEqual(3, history.Count());

            Assert.IsTrue(history.All(be => be.Id == origId));

            Assert.IsTrue(history.Last() is DeletedEntry);

            var ver1 = new ResourceLocation(history.First().Links.SelfLink).VersionId;
            var ver2 = new ResourceLocation(history.ElementAt(1).Links.SelfLink).VersionId;
            var ver3 = new ResourceLocation(history.ElementAt(2).Links.SelfLink).VersionId;

            Assert.AreNotEqual(Int32.Parse(ver1), Int32.Parse(ver2));
            Assert.AreNotEqual(Int32.Parse(ver2), Int32.Parse(ver3));
            Assert.AreNotEqual(Int32.Parse(ver1), Int32.Parse(ver3));

            var firstVersionAsEntry = _store.FindVersionByVersionId(history.First().Links.SelfLink);

            //TODO: There's a bug here...the cr+lf in the _stockPatient gets translated to \r\n in the 'firstVersion'.
            //Cannot see this in the stored version though.
            Assert.AreEqual(FhirSerializer.SerializeResourceToJson(_stockPatient.Resource),
                            FhirSerializer.SerializeResourceToJson(((ResourceEntry)firstVersionAsEntry).Resource));

            var secondVersionAsEntry = _store.FindVersionByVersionId(history.ElementAt(1).Links.SelfLink);

            Assert.AreEqual("Donald Duck", ((Patient)((ResourceEntry)secondVersionAsEntry).Resource).Name[0].Text);

            var allHistory = _store.ListVersions();

            Assert.AreEqual(5, allHistory.Count());
            Assert.AreEqual(3, allHistory.Count(be => be.Id.ToString().Contains("patient")));
            Assert.AreEqual(2, allHistory.Count(be => be.Id.ToString().Contains("organization")));
            Assert.AreEqual(2, allHistory.Count(be => be is DeletedEntry));
        }
예제 #7
0
 public RollBack(ImportParameters importParameters, Subscription subscription, DCMigrationManager dcMigrationManager,
                 ResourceImporter resourceImporter)
 {
     this.subscription       = subscription;
     this.importParameters   = importParameters;
     this.dcMigrationManager = dcMigrationManager;
     this.resourceImporter   = resourceImporter;
 }
예제 #8
0
파일: Factory.cs 프로젝트: schellack/spark
        public static ResourceImporter GetResourceImporter()
        {
            IGenerator generator = Spark.Store.MongoStoreFactory.GetMongoFhirStorage();
            var        localhost = GetLocalhost();
            var        importer  = new ResourceImporter(localhost, generator);

            return(importer);
        }
예제 #9
0
 private static void MemoriaExport()
 {
     if (Interlocked.CompareExchange(ref _initialized, 1, 0) == 0)
     {
         ResourceExporter.ExportSafe();
         ResourceImporter.Initialize();
     }
 }
예제 #10
0
        internal async Task ImportResourcesAsync(string resourceDocumentFilePath, string baseFilePath)
        {
            var importer = new ResourceImporter(_config, _httpClient);

            await ExecuteWithinLockAsync(
                () =>
                importer.ImportResources(resourceDocumentFilePath, baseFilePath), $"Failed to import resource file {resourceDocumentFilePath} to Episerver."
                );
        }
        private void CreateTestObject(string data, bool isImportCancelled)
        {
            _testObj = new ResourceImporter(_web.Instance, data, true);
            _testObj.IsImportCancelled      = isImportCancelled;
            _testObj.ImportCompleted       += ResourceImportCompleted;
            _testObj.ImportProgressChanged += ResourceImportProgressChanged;

            _privateObj = new PrivateObject(_testObj);
        }
예제 #12
0
        public static ResourceImporter GetResourceImporter()
        {
            IFhirStore       store    = GetMongoFhirStore();
            ResourceImporter importer = new ResourceImporter(store, Settings.Endpoint);

            importer.SharedEndpoints.Add("http://hl7.org/fhir/");

            importer.SharedEndpoints.Add("localhost");
            importer.SharedEndpoints.Add("localhost.");

            return(importer);
        }
예제 #13
0
        public void ListRecordsByResourceType()
        {
            _store.EraseData();

            DateTimeOffset now    = DateTimeOffset.UtcNow;
            DateTime       stampi = new DateTime(now.Ticks, DateTimeKind.Unspecified);

            stampi = stampi.AddHours(5);

            DateTimeOffset stamp = new DateTimeOffset(stampi, new TimeSpan(5, 0, 0));

            var importer = new ResourceImporter(new Uri("http://localhost"));

            for (int i = 0; i < 5; i++)
            {
                var tst = _stockPatients[i];
                importer.QueueNewEntry(tst);
            }
            for (int i = 0; i < 5; i++)
            {
                var tst = _stockOrgs[i];
                importer.QueueNewEntry(tst);
            }

            importer.QueueNewDeletedEntry("patient", "31415");

            var imported = importer.ImportQueued();

            _store.AddEntries(imported);

            var recentList = _store.ListCollection("patient");

            Assert.AreEqual(5, recentList.Count(), "Should not contain deleted entries");

            var recentOrgList = _store.ListCollection("organization");

            Assert.AreEqual(5, recentOrgList.Count(), "Should not contain patients");

            recentList = _store.ListCollection("patient", includeDeleted: true);
            Assert.AreEqual(6, recentList.Count(), "Should contain deleted entries");

            var recentListWithFilter = _store.ListCollection("patient", limit: 3);

            Assert.AreEqual(3, recentListWithFilter.Count());

            var recentListWithFilter2 = _store.ListCollection("patient", since: now.AddMinutes(-1));

            Assert.AreEqual(5, recentListWithFilter2.Count());

            var recentListWithFilter3 = _store.ListCollection("patient", since: now.AddMinutes(-1), limit: 3);

            Assert.AreEqual(3, recentListWithFilter3.Count());
        }
예제 #14
0
        public ViewResult ImportResources(bool?previewImport, HttpPostedFileBase importFile, bool?showMenu)
        {
            var model = new ImportResourcesViewModel {
                ShowMenu = showMenu ?? false
            };

            if (importFile == null || importFile.ContentLength == 0)
            {
                return(View("ImportResources", model));
            }

            var fileInfo = new FileInfo(importFile.FileName);

            if (fileInfo.Extension.ToLower() != ".json")
            {
                ModelState.AddModelError("file", "Uploaded file has different extension. Json file expected");
                return(View("ImportResources", model));
            }

            var importer     = new ResourceImporter();
            var serializer   = new JsonDataSerializer();
            var streamReader = new StreamReader(importFile.InputStream);
            var fileContent  = streamReader.ReadToEnd();

            try
            {
                var newResources = serializer.Deserialize <IEnumerable <LocalizationResource> >(fileContent);

                if (previewImport.HasValue && previewImport.Value)
                {
                    var changes = importer.DetectChanges(newResources, new GetAllResources.Query().Execute());

                    var availableLanguagesQuery = new AvailableLanguages.Query();
                    var languages = availableLanguagesQuery.Execute();

                    var previewModel = new PreviewImportResourcesViewModel(changes, showMenu ?? false, languages);

                    return(View("ImportPreview", previewModel));
                }

                var result = importer.Import(newResources, previewImport ?? true);

                ViewData["LocalizationProvider_ImportResult"] = result;
            }
            catch (Exception e)
            {
                ModelState.AddModelError("importFailed", $"Import failed! Reason: {e.Message}");
            }

            return(View("ImportResources", model));
        }
예제 #15
0
        /// <inheritdoc />
        protected override void Load(ContainerBuilder builder)
        {
            var connectionSupplier = new DefaultDbConnectionSupplier();
            var iotaRepository     = new CachedIotaRestRepository(
                new FallbackIotaClient(new List <string> {
                "https://nodes.devnet.thetangle.org:443"
            }, 5000),
                new PoWSrvService(),
                null,
                connectionSupplier,
                $"{DependencyResolver.LocalStoragePath}\\iotacache.sqlite");

            var channelFactory      = new MamChannelFactory(CurlMamFactory.Default, CurlMerkleTreeFactory.Default, iotaRepository);
            var subscriptionFactory = new MamChannelSubscriptionFactory(iotaRepository, CurlMamParser.Default, CurlMask.Default);

            var encryption      = new RijndaelEncryption("somenicekey", "somenicesalt");
            var resourceTracker = new SqlLiteResourceTracker(
                channelFactory,
                subscriptionFactory,
                encryption,
                connectionSupplier,
                $"{DependencyResolver.LocalStoragePath}\\iotafhir.sqlite");

            var seedManager = new SqlLiteDeterministicSeedManager(
                resourceTracker,
                new IssSigningHelper(new Curl(), new Curl(), new Curl()),
                new AddressGenerator(),
                iotaRepository,
                encryption,
                connectionSupplier,
                $"{DependencyResolver.LocalStoragePath}\\iotafhir.sqlite");

            var fhirRepository   = new IotaFhirRepository(iotaRepository, new FhirJsonTryteSerializer(), resourceTracker, seedManager);
            var fhirParser       = new FhirJsonParser();
            var searchRepository = new SqlLiteSearchRepository(fhirParser, connectionSupplier, $"{DependencyResolver.LocalStoragePath}\\resources.sqlite");

            var createInteractor     = new CreateResourceInteractor(fhirRepository, fhirParser, searchRepository);
            var readInteractor       = new ReadResourceInteractor(fhirRepository, searchRepository);
            var validationInteractor = new ValidateResourceInteractor(fhirRepository, fhirParser);
            var searchInteractor     = new SearchResourcesInteractor(fhirRepository, searchRepository);

            var resourceImporter = new ResourceImporter(searchRepository, fhirRepository, seedManager);

            builder.RegisterInstance(createInteractor);
            builder.RegisterInstance(readInteractor);
            builder.RegisterInstance(validationInteractor);
            builder.RegisterInstance(searchInteractor);
            builder.RegisterInstance(resourceImporter);
            builder.RegisterInstance(seedManager).As <ISeedManager>();
            builder.RegisterInstance(subscriptionFactory);
        }
예제 #16
0
        /// <summary>
        /// Combination of Export and Import functionality.
        /// Exports information about source subscription and stores the metadata into 'SourceDataCenterName-MM-DD-YYYY-hh-mm.json format
        /// on specified ExportMetadataFolderPath.
        /// Reads exported metadata json file and deploys all the source resources into destination subscription.
        /// </summary>
        /// <param name="parameters"> Collection of key value paired input parameters <example> Operation "Migrate"
        /// SourceSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" DestinationSubscriptionID "5d14d4a2-8c5a-4fc5-8d7d-86efb48b3a07" SourceDCName "East Asia"
        /// DestinationDCName "West US" SourcePublishSettingsFilePath "D:\\PublishSettings.PublishSettings" SourceCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7"
        /// DestinationPublishSettingsFilePath "D:\\PublishSettings.PublishSettings" DestinationCertificateThumbprint "2180d782768926ee0e5ddbcc6e8d2efa8ddb98c7"
        /// ExportMetadataFolderPath "D:\\DataCenterMigration" DestinationPrefixName "dc" RetryCount "5" MinBackoff "3" MaxBackoff "3" DeltaBackoff "90"
        /// QuietMode "True" RollBackOnFailure "True" </example></param>
        public void MigrateSubscription(IDictionary <string, string> parameters)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.ExecutionStarted);
            bool boolValue;

            if (!parameters.Keys.Contains(Constants.Parameters.QuietMode))
            {
                quietMode = false;
            }
            else
            {
                quietMode = bool.TryParse(parameters[Constants.Parameters.QuietMode], out boolValue) ? boolValue : false;
            }

            ReportProgress(ProgressResources.ExportMetadataStarted);
            Logger.Info(methodName, ProgressResources.ExportMetadataStarted);

            // Validate the input paramters and export them into parameters class.
            ExportParameters exportParameters = ConfigurationReader.ValidateAndConvertExportParameters(parameters);

            // Validate the input paramters and export them into parameters class.
            ImportParameters importParameters = ConfigurationReader.ValidateAndConvertImportParameters(parameters, false);

            // Export metadata.
            ResourceExporter exporter     = new ResourceExporter(exportParameters, this);
            Subscription     subscription = exporter.ExportSubscriptionMetadata();

            File.WriteAllText(exportParameters.ExportMetadataFolderPath,
                              JsonConvert.SerializeObject(subscription, Formatting.Indented));
            ReportProgress(string.Format(ProgressResources.ExportMetadataCompleted, exportParameters.ExportMetadataFolderPath));
            Logger.Info(methodName, string.Format(ProgressResources.ExportMetadataCompleted, exportParameters.ExportMetadataFolderPath));
            Logger.Info(methodName, ProgressResources.ExecutionCompleted);

            importParameters.ImportMetadataFilePath = exportParameters.ExportMetadataFolderPath;
            // Import metadata.
            Logger.Info(methodName, string.Format(ProgressResources.ImportMetadataStarted, importParameters.ImportMetadataFilePath));
            ReportProgress(string.Format(ProgressResources.ImportMetadataStarted, importParameters.ImportMetadataFilePath));

            ResourceImporter importer = new ResourceImporter(importParameters, this);

            importer.ImportSubscriptionMetadata();

            ReportProgress(ProgressResources.ImportMetadataCompleted);
            Logger.Info(methodName, ProgressResources.ImportMetadataCompleted);

            Logger.Info(methodName, ProgressResources.ExecutionCompleted);
        }
예제 #17
0
        private void InjectDependencies(IServiceCollection services)
        {
            var iotaRepository = new CachedIotaRestRepository(
                new FallbackIotaClient(new List <string> {
                "https://nodes.devnet.thetangle.org:443"
            }, 5000),
                new PoWService(new CpuPearlDiver()));

            var channelFactory      = new MamChannelFactory(CurlMamFactory.Default, CurlMerkleTreeFactory.Default, iotaRepository);
            var subscriptionFactory = new MamChannelSubscriptionFactory(iotaRepository, CurlMamParser.Default, CurlMask.Default);

            var encryption      = new RijndaelEncryption("somenicekey", "somenicesalt");
            var resourceTracker = new SqlLiteResourceTracker(channelFactory, subscriptionFactory, encryption);

            var seedManager = new SqlLiteDeterministicSeedManager(
                resourceTracker,
                new IssSigningHelper(new Curl(), new Curl(), new Curl()),
                new AddressGenerator(),
                iotaRepository,
                encryption);

            var fhirRepository   = new IotaFhirRepository(iotaRepository, new FhirJsonTryteSerializer(), resourceTracker, seedManager);
            var fhirParser       = new FhirJsonParser();
            var searchRepository = new SqlLiteSearchRepository(fhirParser);

            var createInteractor       = new CreateResourceInteractor(fhirRepository, fhirParser, searchRepository);
            var readInteractor         = new ReadResourceInteractor(fhirRepository, searchRepository);
            var readVersionInteractor  = new ReadResourceVersionInteractor(fhirRepository);
            var readHistoryInteractor  = new ReadResourceHistoryInteractor(fhirRepository);
            var capabilitiesInteractor = new GetCapabilitiesInteractor(fhirRepository, new AppConfigSystemInformation(this.Configuration));
            var validationInteractor   = new ValidateResourceInteractor(fhirRepository, fhirParser);
            var searchInteractor       = new SearchResourcesInteractor(fhirRepository, searchRepository);
            var deleteInteractor       = new DeleteResourceInteractor(fhirRepository, searchRepository);

            var resourceImporter = new ResourceImporter(searchRepository, fhirRepository, seedManager);

            services.AddScoped(provider => createInteractor);
            services.AddScoped(provider => readInteractor);
            services.AddScoped(provider => capabilitiesInteractor);
            services.AddScoped(provider => validationInteractor);
            services.AddScoped(provider => searchInteractor);
            services.AddScoped(provider => resourceImporter);
            services.AddScoped(provider => readVersionInteractor);
            services.AddScoped(provider => readHistoryInteractor);
            services.AddScoped(provider => deleteInteractor);

            services.AddScoped <ISeedManager>(provider => seedManager);
            services.AddSingleton <IMemoryCache>(new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions()));
        }
예제 #18
0
        protected override void Confirm(object sender, EventArgs e)
        {
            FileInfo file = textureFile.File;

            if (file?.Exists != true)
            {
                MessageBox.Show("The specified texture file could not be found!", DIALOG_CAPTION_MISSING_FILE);
                return;
            }

            ResourceImporter.ImportFile(editor, file, "textures", out string filePath);

            Data.file = filePath;

            base.Confirm(sender, e);
        }
예제 #19
0
        public void ImportSome_TheSameWithDifferentTranslationInDatabase_InsertsAndUpdates()
        {
            var incoming = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1"
                        }
                    }
                },
                new LocalizationResource("key2")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 2 - Changed!"
                        }
                    }
                }
            };
            var existing = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1 English"
                        },
                        new LocalizationResourceTranslation {
                            Language = "no", Value = "Resurs 1 Norsk"
                        }
                    }
                }
            };

            var sut = new ResourceImporter();

            var result = sut.DetectChanges(incoming, existing);

            Assert.Equal(1, result.Count(c => c.ChangeType == ChangeType.Insert));
            Assert.Equal(1, result.Count(c => c.ChangeType == ChangeType.Update));
        }
예제 #20
0
        internal void ImportResources(string resourceDocumentFilePath, string baseFilePath)
        {
            lock (EpiLockObject.Instance)
            {
                try
                {
                    var importer = new ResourceImporter(_config, _httpClient);
                    importer.ImportResources(resourceDocumentFilePath, baseFilePath);

                    IntegrationLogger.Write(LogLevel.Information, $"Resource file {resourceDocumentFilePath} imported to Episerver.");
                }
                catch (Exception exception)
                {
                    IntegrationLogger.Write(LogLevel.Error, $"Failed to import resource file {resourceDocumentFilePath} to Episerver.", exception);
                    throw;
                }
            }
        }
예제 #21
0
        public void ImportNewResource_OneAlreadyExists_OnlyInserts()
        {
            var incoming = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1"
                        }
                    }
                },
                new LocalizationResource("key2")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 2"
                        }
                    }
                }
            };
            var existing = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1"
                        }
                    }
                }
            };

            var sut = new ResourceImporter();

            var result = sut.DetectChanges(incoming, existing);

            Assert.Equal(1, result.Count(c => c.ChangeType == ChangeType.Insert));
            Assert.Equal(0, result.Count(c => c.ChangeType == ChangeType.Update));
        }
예제 #22
0
        public void TestIdReassignOnImport()
        {
            var importer = new ResourceImporter(new Uri("http://fhir.furore.com/fhir/"));

            importer.AddSharedIdSpacePrefix("http://localhost");

            importer.QueueNewResourceEntry(new Uri("http://someserver.nl/fhir/patient/@1012"), new Patient());
            importer.QueueNewResourceEntry(new Uri("http://fhir.furore.com/fhir/patient/@13"), new Patient());
            importer.QueueNewResourceEntry(new Uri("http://localhost/svc/patient/@24"), new Patient());
            importer.QueueNewResourceEntry(new Uri("cid:332211223316"), new Patient());
            importer.QueueNewDeletedEntry(new Uri("http://someserver.nl/fhir/patient/@17"));
            var imported = importer.ImportQueued();

            Assert.AreEqual("patient/@1", imported.First().Id.ToString());
            Assert.AreEqual("patient/@13", imported.Skip(1).First().Id.ToString());
            Assert.AreEqual("patient/@24", imported.Skip(2).First().Id.ToString());
            Assert.AreEqual("patient/@25", imported.Skip(3).First().Id.ToString());
            Assert.AreEqual("patient/@26", imported.Skip(4).First().Id.ToString());
        }
예제 #23
0
        public void ImportNewResource_OneDelete_InsertsAndDeletes()
        {
            var incoming = new List <LocalizationResource>
            {
                new LocalizationResource("new1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1"
                        }
                    }
                },
                new LocalizationResource("new2")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 2"
                        }
                    }
                }
            };
            var existing = new List <LocalizationResource>
            {
                new LocalizationResource("existing")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1"
                        }
                    }
                }
            };

            var sut = new ResourceImporter();

            var result = sut.DetectChanges(incoming, existing);

            Assert.Equal(2, result.Count(c => c.ChangeType == ChangeType.Insert));
            Assert.Equal(1, result.Count(c => c.ChangeType == ChangeType.Delete));
        }
예제 #24
0
        public void ImportOne_CheckChangedLanguageWithDifferentTranslations()
        {
            var incoming = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1 CHANGED"
                        },
                        new LocalizationResourceTranslation {
                            Language = "no", Value = "Resurs 1 CHANGED"
                        }
                    }
                }
            };
            var existing = new List <LocalizationResource>
            {
                new LocalizationResource("key1")
                {
                    Translations = new List <LocalizationResourceTranslation>
                    {
                        new LocalizationResourceTranslation {
                            Language = "en", Value = "Resource 1 English"
                        },
                        new LocalizationResourceTranslation {
                            Language = "no", Value = "Resurs 1 Norsk"
                        }
                    }
                }
            };
            var sut = new ResourceImporter();

            var result = sut.DetectChanges(incoming, existing);

            Assert.Equal(1, result.Count(c => c.ChangeType == ChangeType.Update));

            var firstChange = result.First();

            Assert.Equal(new[] { "en", "no" }, firstChange.ChangedLanguages.ToArray());
        }
        public async Task TestResourceCanBeImportedAndIsAddedToSearch()
        {
            var fhirRepository   = new InMemoryFhirRepository();
            var resourceTracker  = new InMemoryResourceTracker();
            var searchRepository = new InMemorySearchRepository();

            var resourceImporter = new ResourceImporter(searchRepository, fhirRepository, new RandomSeedManager(resourceTracker));

            var rootHash = Seed.Random().Value;
            var patient  = FhirResourceProvider.Patient;

            patient.Id = rootHash.Substring(0, 64);

            fhirRepository.Resources.Add(patient);

            await resourceImporter.ImportResourceAccessAsync(rootHash, Seed.Random().Value);

            Assert.IsNotNull(await resourceTracker.GetEntryAsync(rootHash));
            Assert.AreEqual(1, (await searchRepository.FindResourcesByTypeAsync("Patient")).Count);
        }
예제 #26
0
        public ViewResult CommitImportResources(bool?previewImport, bool?showMenu, ICollection <DetectedImportChange> changes)
        {
            var model = new ImportResourcesViewModel
            {
                ShowMenu = showMenu ?? false
            };

            try
            {
                var importer = new ResourceImporter();
                var result   = importer.ImportChanges(changes.Where(c => c.Selected).ToList());

                ViewData["LocalizationProvider_ImportResult"] = string.Join("<br/>", result);
            }
            catch (Exception e)
            {
                ModelState.AddModelError("importFailed", $"Import failed! Reason: {e.Message}");
            }

            return(View("ImportResources", model));
        }
예제 #27
0
        public ViewResult ImportResources(bool?importOnlyNewContent, HttpPostedFileBase importFile, bool?showMenu)
        {
            var model = new ImportResourcesViewModel
            {
                ShowMenu = showMenu ?? false
            };

            if (importFile == null || importFile.ContentLength == 0)
            {
                return(View("ImportResources", model));
            }

            var fileInfo = new FileInfo(importFile.FileName);

            if (fileInfo.Extension.ToLower() != ".json")
            {
                ModelState.AddModelError("file", "Uploaded file has different extension. Json file expected");
                return(View("ImportResources", model));
            }

            var importer     = new ResourceImporter();
            var serializer   = new JsonDataSerializer();
            var streamReader = new StreamReader(importFile.InputStream);
            var fileContent  = streamReader.ReadToEnd();

            try
            {
                var newResources = serializer.Deserialize <IEnumerable <LocalizationResource> >(fileContent);
                var result       = importer.Import(newResources, importOnlyNewContent ?? true);

                ViewData["LocalizationProvider_ImportResult"] = result;
            }
            catch (Exception e)
            {
                ModelState.AddModelError("importFailed", $"Import failed! Reason: {e.Message}");
            }

            return(View("ImportResources", model));
        }
        // Public Methods (1) 

        /// <summary>
        ///     Executes the import job.
        /// </summary>
        /// <param name="site">The site.</param>
        /// <param name="web">The web.</param>
        /// <param name="data">The data.</param>
        public void execute(SPSite site, SPWeb web, string data)
        {
            try
            {
                _done = false;

                totalCount = 2;

                resourceImporter = new ResourceImporter(web, data, false);

                resourceImporter.ImportCompleted       += ResourceImportCompleted;
                resourceImporter.ImportProgressChanged += ResourceImportProgressChanged;

                resourceImporter.ImportAsync();

                while (!_done)
                {
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
                data = null;
            }
        }
예제 #29
0
        public void FullExampleImport()
        {
            ExampleImporter examples = new ExampleImporter();

            examples.ImportZip("examples.zip");

            var importer = new ResourceImporter(new Uri("http://hl7.org/fhir/"));

            foreach (var resourceName in ModelInfo.SupportedResources)
            {
                var key = resourceName.ToLower();
                if (examples.ImportedEntries.ContainsKey(key))
                {
                    var exampleEntries = examples.ImportedEntries[key];

                    foreach (var exampleEntry in exampleEntries)
                    {
                        importer.QueueNewEntry(exampleEntry);
                    }
                }
            }

            var importedEntries = importer.ImportQueued();
        }
예제 #30
0
 public IotaController(ResourceImporter resourceImporter, ISeedManager seedManager)
 {
     this.ResourceImporter = resourceImporter;
     this.SeedManager      = seedManager;
 }