Esempio n. 1
0
        public void DoImport(Stream backupStream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException(nameof(manifest));
            }

            var backupObject   = backupStream.DeserializeJson <BackupObject>();
            var originalObject = GetBackupObject(progressCallback, false);

            var progressInfo = new ExportImportProgressInfo
            {
                Description = String.Format("{0} menu link lists importing...", backupObject.MenuLinkLists.Count())
            };

            progressCallback(progressInfo);
            UpdateMenuLinkLists(backupObject.MenuLinkLists);

            if (manifest.HandleBinaryData)
            {
                progressInfo.Description = String.Format("importing binary data:  themes and pages importing...");
                progressCallback(progressInfo);
                foreach (var folder in backupObject.ContentFolders)
                {
                    SaveContentFolderRecursive(folder, progressCallback);
                }
            }
        }
Esempio n. 2
0
        public void DoExport_SuccessExport()
        {
            //Arrange
            var manifest       = new PlatformExportManifest();
            var fileStream     = new FileStream(Path.GetFullPath("export_test.json"), FileMode.Create);
            var entityForCount = AbstractTypeFactory <NotificationEntity> .TryCreateInstance(nameof(EmailNotificationEntity));

            entityForCount.Id   = Guid.NewGuid().ToString();
            entityForCount.Type = nameof(EmailNotification);
            entityForCount.Kind = nameof(EmailNotification);
            _repositoryMock.Setup(r => r.GetByTypeAsync(nameof(RegistrationEmailNotification), null, null, NotificationResponseGroup.Default.ToString())).ReturnsAsync(entityForCount);

            var entity = AbstractTypeFactory <NotificationEntity> .TryCreateInstance(nameof(EmailNotificationEntity));

            entity.Id        = entityForCount.Id;
            entity.Type      = nameof(EmailNotification);
            entity.Kind      = nameof(EmailNotification);
            entity.Templates = new ObservableCollection <NotificationTemplateEntity>()
            {
                new NotificationTemplateEntity()
                {
                    Body = "test", LanguageCode = "en-US"
                }
            };
            _repositoryMock.Setup(r => r.GetByTypeAsync(nameof(RegistrationEmailNotification), null, null, NotificationResponseGroup.Full.ToString())).ReturnsAsync(entity);

            //Act
            _notificationsExportImportManager.ExportAsync(fileStream, null, exportImportProgressInfo => { }, new CancellationTokenWrapper(CancellationToken.None));

            //Assert
            fileStream.Close();
        }
        public async Task DoExport_SuccessExport()
        {
            //Arrange
            var manifest   = new PlatformExportManifest();
            var fileStream = new FileStream(Path.GetFullPath("export_test.json"), FileMode.Create);
            var entity     = AbstractTypeFactory <Notification> .TryCreateInstance(nameof(EmailNotification));

            entity.Id   = Guid.NewGuid().ToString();
            entity.Type = nameof(RegistrationEmailNotification);

            entity.TenantIdentity = new TenantIdentity(Guid.NewGuid().ToString(), nameof(Notification));
            entity.Templates      = new ObservableCollection <NotificationTemplate>()
            {
                new EmailNotificationTemplate()
                {
                    Body = "test", LanguageCode = "en-US"
                },
            };

            _notificationSearchServiceMock
            .Setup(nss => nss.SearchNotificationsAsync(It.IsAny <NotificationSearchCriteria>()))
            .ReturnsAsync(new NotificationSearchResult {
                Results = new List <Notification> {
                    entity
                }, TotalCount = 1
            });

            //Act
            await _notificationsExportImportManager.DoExportAsync(fileStream, exportImportProgressInfo => { }, new CancellationTokenWrapper(CancellationToken.None));

            //Assert
            fileStream.Close();
        }
Esempio n. 4
0
        public async Task ExportAsync(Stream outStream, PlatformExportManifest exportOptions, Action <ExportImportProgressInfo> progressCallback, ICancellationToken сancellationToken)
        {
            if (exportOptions == null)
            {
                throw new ArgumentNullException(nameof(exportOptions));
            }

            using (var zipArchive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
            {
                //Export all selected platform entries
                await ExportPlatformEntriesInternalAsync(zipArchive, exportOptions, progressCallback, сancellationToken);

                //Export all selected  modules
                await ExportModulesInternalAsync(zipArchive, exportOptions, progressCallback, сancellationToken);

                //Write system information about exported modules
                var manifestZipEntry = zipArchive.CreateEntry(ManifestZipEntryName, CompressionLevel.Optimal);

                //After all modules exported need write export manifest part
                using (var stream = manifestZipEntry.Open())
                {
                    exportOptions.SerializeJson(stream, GetJsonSerializer());
                }
            }
        }
Esempio n. 5
0
        public async Task ImportAsync(Stream stream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback, CancellationToken cancellationToken)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException("manifest");
            }

            var progressInfo = new ExportImportProgressInfo();

            progressInfo.Description = "Starting platform import...";
            progressCallback(progressInfo);

            using (var zipArchive = new ZipArchive(stream))
            {
                //Import selected platform entries
                await ImportPlatformEntriesInternalAsync(zipArchive, manifest, progressCallback, cancellationToken);

                //Import selected modules
                await ImportModulesInternalAsync(zipArchive, manifest, progressCallback, cancellationToken);

                //Reset cache
                //TODO:
                //_memoryCache.Clear();
            }
        }
Esempio n. 6
0
        public void Import(Stream stream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException("manifest");
            }

            var progressInfo = new ExportImportProgressInfo
            {
                Description = "Starting platform import..."
            };

            progressCallback(progressInfo);

            using (var package = Package.Open(stream, FileMode.Open))
                using (var guard = EventSupressor.SupressEvents())
                {
                    //Import selected platform entries
                    ImportPlatformEntriesInternal(package, manifest, progressCallback);
                    //Import selected modules
                    ImportModulesInternal(package, manifest, progressCallback);
                    //Reset cache
                    _cacheManager.Clear();
                }
        }
Esempio n. 7
0
        private void ImportModulesInternal(Package package, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();

            foreach (var moduleInfo in manifest.Modules)
            {
                var moduleDescriptor = InnerGetModulesWithInterface(typeof(ISupportExportImportModule)).FirstOrDefault(x => x.Id == moduleInfo.Id);
                if (moduleDescriptor != null)
                {
                    var modulePart = package.GetPart(new Uri(moduleInfo.PartUri, UriKind.Relative));
                    using (var modulePartStream = modulePart.GetStream())
                    {
                        Action <ExportImportProgressInfo> modulePorgressCallback = (x) =>
                        {
                            progressInfo.Description = $"{moduleInfo.Id}: {x.Description}";
                            progressInfo.Errors      = x.Errors;
                            progressCallback(progressInfo);
                        };
                        try
                        {
                            ((ISupportExportImportModule)moduleDescriptor.ModuleInstance).DoImport(modulePartStream, manifest, modulePorgressCallback);
                        }
                        catch (Exception ex)
                        {
                            progressInfo.Errors.Add($"{moduleInfo.Id}: {ex.ExpandExceptionMessage()}");
                            progressCallback(progressInfo);
                        }
                    }
                }
            }
        }
Esempio n. 8
0
        public void DoExport(Stream outStream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback,
                             CancellationToken cancellationToken)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException("manifest");
            }

            if (cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }

            var progressInfo = new ExportImportProgressInfo {
                Description = "loading data..."
            };

            progressCallback(progressInfo);

            using (var sw = new StreamWriter(outStream, System.Text.Encoding.UTF8))
                using (var writer = new JsonTextWriter(sw))
                {
                    writer.WriteStartObject();

                    progressInfo.Description = "Notifications exporting...";
                    progressCallback(progressInfo);

                    var notificationsResult = _notificationSearchService.SearchNotifications(new NotificationSearchCriteria {
                        Take = Int32.MaxValue, ResponseGroup = NotificationResponseGroup.Default.ToString()
                    });
                    writer.WritePropertyName("NotificationsTotalCount");
                    writer.WriteValue(notificationsResult.TotalCount);

                    if (cancellationToken.IsCancellationRequested)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                    }

                    writer.WritePropertyName("Notifications");
                    writer.WriteStartArray();
                    for (var i = 0; i < notificationsResult.TotalCount; i += _batchSize)
                    {
                        var searchResponse = _notificationSearchService.SearchNotifications(new NotificationSearchCriteria {
                            Skip = i, Take = _batchSize, ResponseGroup = NotificationResponseGroup.Full.ToString()
                        });

                        foreach (var notification in searchResponse.Results)
                        {
                            GetJsonSerializer().Serialize(writer, notification);
                        }
                        writer.Flush();
                        progressInfo.Description = $"{ Math.Min(notificationsResult.TotalCount, i + _batchSize) } of { notificationsResult.TotalCount } notifications exported";
                        progressCallback(progressInfo);
                    }
                    writer.WriteEndArray();

                    writer.WriteEndObject();
                    writer.Flush();
                }
        }
Esempio n. 9
0
        private void ImportModulesInternal(ZipArchive zipArchive, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();

            foreach (var moduleInfo in manifest.Modules)
            {
                var moduleDescriptor = InnerGetModulesWithInterface(typeof(ISupportExportImportModule)).FirstOrDefault(x => x.Id == moduleInfo.Id);
                if (moduleDescriptor != null)
                {
                    var modulePart = zipArchive.GetEntry(moduleInfo.PartUri);
                    using (var modulePartStream = modulePart.Open())
                    {
                        Action <ExportImportProgressInfo> modulePorgressCallback = (x) =>
                        {
                            progressInfo.Description = $"{moduleInfo.Id}: {x.Description}";
                            progressCallback(progressInfo);
                        };
                        try
                        {
                            ((ISupportExportImportModule)moduleDescriptor.ModuleInstance).DoImport(modulePartStream, manifest, modulePorgressCallback);
                        }
                        catch (Exception ex)
                        {
                            progressInfo.Errors.Add($"{moduleInfo.Id}: {ex.ToString()}");
                            progressCallback(progressInfo);
                        }
                    }
                }
            }
        }
        private void ExportPlatformEntriesInternal(Package package, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo      = new ExportImportProgressInfo();
            var platformExportObj = new PlatformExportEntries();

            if (manifest.HandleSecurity)
            {
                //Roles
                platformExportObj.Roles = _roleManagementService.SearchRoles(new RoleSearchRequest {
                    SkipCount = 0, TakeCount = int.MaxValue
                }).Roles;
                //users
                var usersResult = Task.Run(() => _securityService.SearchUsersAsync(new UserSearchRequest {
                    TakeCount = int.MaxValue
                })).Result;
                progressInfo.Description = String.Format("Security: {0} users exporting...", usersResult.Users.Count());
                progressCallback(progressInfo);

                foreach (var user in usersResult.Users)
                {
                    var userExt = Task.Run(() => _securityService.FindByIdAsync(user.Id, UserDetails.Export)).Result;
                    if (userExt != null)
                    {
                        platformExportObj.Users.Add(userExt);
                    }
                }
            }

            //Export setting for selected modules
            if (manifest.HandleSettings)
            {
                progressInfo.Description = String.Format("Settings: selected modules settings exporting...");
                progressCallback(progressInfo);

                platformExportObj.Settings = manifest.Modules.SelectMany(x => _settingsManager.GetModuleSettings(x.Id)).ToList();
            }

            //Dynamic properties
            var allTypes = _dynamicPropertyService.GetAvailableObjectTypeNames();

            progressInfo.Description = String.Format("Dynamic properties: load properties...");
            progressCallback(progressInfo);

            platformExportObj.DynamicProperties = allTypes.SelectMany(x => _dynamicPropertyService.GetProperties(x)).ToList();
            platformExportObj.DynamicPropertyDictionaryItems = platformExportObj.DynamicProperties.Where(x => x.IsDictionary).SelectMany(x => _dynamicPropertyService.GetDictionaryItems(x.Id)).ToList();

            //Notification templates
            progressInfo.Description = String.Format("Notifications: load templates...");
            progressCallback(progressInfo);
            platformExportObj.NotificationTemplates = _notificationTemplateService.GetAllTemplates().ToList();

            //Create part for platform entries
            var platformEntiriesPart = package.CreatePart(_platformEntriesPartUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Normal);

            using (var partStream = platformEntiriesPart.GetStream())
            {
                platformExportObj.SerializeJson <PlatformExportEntries>(partStream);
            }
        }
        public void DoImport(Stream backupStream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();

            var backupObject   = backupStream.DeserializeJson <BackupObject>();
            var originalObject = GetBackupObject(progressCallback, false);

            progressInfo.Description = String.Format("{0} catalogs importing...", backupObject.Catalogs.Count());
            progressCallback(progressInfo);

            UpdateCatalogs(originalObject.Catalogs, backupObject.Catalogs);

            progressInfo.Description = String.Format("{0} categories importing...", backupObject.Categories.Count());
            progressCallback(progressInfo);
            //Categories should be sorted right way (because it have a hierarchy structure and links to virtual categories)
            backupObject.Categories = backupObject.Categories.Where(x => x.Links == null || !x.Links.Any())
                                      .OrderBy(x => x.Parents != null ? x.Parents.Count() : 0)
                                      .Concat(backupObject.Categories.Where(x => x.Links != null && x.Links.Any()))
                                      .ToList();
            backupObject.Products = backupObject.Products.OrderBy(x => x.MainProductId).ToList();
            UpdateCategories(originalObject.Categories, backupObject.Categories);
            UpdateProperties(originalObject.Properties, backupObject.Properties);

            //Binary data
            if (manifest.HandleBinaryData)
            {
                var allBackupImages = backupObject.Products.SelectMany(x => x.Images);
                allBackupImages = allBackupImages.Concat(backupObject.Categories.SelectMany(x => x.Images));
                allBackupImages = allBackupImages.Concat(backupObject.Products.SelectMany(x => x.Variations).SelectMany(x => x.Images));

                var allOrigImages = originalObject.Products.SelectMany(x => x.Images);
                allOrigImages = allOrigImages.Concat(originalObject.Categories.SelectMany(x => x.Images));
                allOrigImages = allOrigImages.Concat(originalObject.Products.SelectMany(x => x.Variations).SelectMany(x => x.Images));

                var allNewImages     = allBackupImages.Where(x => !allOrigImages.Contains(x)).Where(x => x.BinaryData != null);
                var index            = 0;
                var progressTemplate = "{0} of " + allNewImages.Count() + " images uploading";
                foreach (var image in allNewImages)
                {
                    progressInfo.Description = String.Format(progressTemplate, index);
                    progressCallback(progressInfo);
                    using (var stream = new MemoryStream(image.BinaryData))
                    {
                        image.Url = _blobStorageProvider.Upload(new UploadStreamInfo {
                            FileByteStream = stream, FileName = image.Name, FolderName = "catalog"
                        });
                    }

                    index++;
                }
            }

            progressInfo.Description = String.Format("{0} products importing...", backupObject.Products.Count());
            progressCallback(progressInfo);
            UpdateCatalogProducts(originalObject.Products, backupObject.Products);
        }
        private void ImportPlatformEntriesInternal(Package package, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();

            var platformEntriesPart = package.GetPart(_platformEntriesPartUri);

            if (platformEntriesPart != null)
            {
                PlatformExportEntries platformEntries;
                using (var stream = platformEntriesPart.GetStream())
                {
                    platformEntries = stream.DeserializeJson <PlatformExportEntries>(GetJsonSerializer());
                }

                //Import security objects
                if (manifest.HandleSecurity)
                {
                    progressInfo.Description = String.Format("Import {0} users with roles...", platformEntries.Users.Count());
                    progressCallback(progressInfo);

                    //First need import roles
                    foreach (var role in platformEntries.Roles)
                    {
                        _roleManagementService.AddOrUpdateRole(role);
                    }
                    //Next create or update users
                    foreach (var user in platformEntries.Users)
                    {
                        if (_securityService.FindByIdAsync(user.Id, UserDetails.Reduced).Result != null)
                        {
                            var dummy = _securityService.UpdateAsync(user).Result;
                        }
                        else
                        {
                            var dummy = _securityService.CreateAsync(user).Result;
                        }
                    }
                }

                //Import modules settings
                if (manifest.HandleSettings)
                {
                    //Import dynamic properties
                    _dynamicPropertyService.SaveProperties(platformEntries.DynamicProperties.ToArray());
                    foreach (var propDicGroup in platformEntries.DynamicPropertyDictionaryItems.GroupBy(x => x.PropertyId))
                    {
                        _dynamicPropertyService.SaveDictionaryItems(propDicGroup.Key, propDicGroup.ToArray());
                    }

                    foreach (var module in manifest.Modules)
                    {
                        _settingsManager.SaveSettings(platformEntries.Settings.Where(x => x.ModuleId == module.Id).ToArray());
                    }
                }
            }
        }
        public IHttpActionResult LoadExportManifest([FromUri] string fileUrl)
        {
            PlatformExportManifest retVal = null;

            using (var stream = _blobStorageProvider.OpenReadOnly(fileUrl))
            {
                retVal = _platformExportManager.ReadExportManifest(stream);
            }
            return(Ok(retVal));
        }
Esempio n. 14
0
        public void DoExport(Stream backupStream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException(nameof(manifest));
            }

            var backupObject = GetBackupObject(progressCallback, manifest.HandleBinaryData);

            backupObject.SerializeJson(backupStream);
        }
Esempio n. 15
0
        public void DoImport_SuccessImport()
        {
            //Arrange
            var manifest   = new PlatformExportManifest();
            var fileStream = new FileStream(Path.GetFullPath("export_test.json"), FileMode.Open);

            //Act
            _notificationsExportImportManager.ImportAsync(fileStream, null, exportImportProgressInfo => { }, new CancellationTokenWrapper(CancellationToken.None));

            //Assert
            fileStream.Close();
        }
        public PlatformExportManifest ReadPlatformExportManifest(Stream stream)
        {
            PlatformExportManifest retVal = null;

            using (var package = ZipPackage.Open(stream, FileMode.Open))
            {
                var manifestPart = package.GetPart(_manifestPartUri);
                using (var streamReader = new StreamReader(manifestPart.GetStream()))
                {
                    retVal = streamReader.ReadToEnd().DeserializeXML <PlatformExportManifest>();
                }
            }
            return(retVal);
        }
        public PlatformExportManifest ReadExportManifest(Stream stream)
        {
            PlatformExportManifest retVal = null;

            using (var package = new ZipArchive(stream))
            {
                var manifestPart = package.GetEntry(_manifestZipEntryName.ToString());
                using (var manifestStream = manifestPart.Open())
                {
                    retVal = manifestStream.DeserializeJson <PlatformExportManifest>(GetJsonSerializer());
                }
            }
            return(retVal);
        }
Esempio n. 18
0
        public PlatformExportManifest GetNewExportManifest(string author)
        {
            var retVal = new PlatformExportManifest
            {
                Author          = author,
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Modules         = InnerGetModulesWithInterface(typeof(IImportSupport)).Select(x => new ExportModuleInfo
                {
                    Id      = x.Id,
                    Version = x.Version.ToString()
                }).ToArray()
            };

            return(retVal);
        }
Esempio n. 19
0
        public PlatformExportManifest ReadExportManifest(Stream stream)
        {
            PlatformExportManifest retVal = null;

            using (var package = Package.Open(stream, FileMode.Open))
            {
                var manifestPart = package.GetPart(_manifestPartUri);
                using (var manifestStream = manifestPart.GetStream())
                {
                    retVal = manifestStream.DeserializeJson <PlatformExportManifest>(GetJsonSerializer());
                }
            }

            return(retVal);
        }
        private async Task ImportModulesInternalAsync(ZipArchive zipArchive, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback, ICancellationToken cancellationToken)
        {
            var errors       = new StringBuilder();
            var progressInfo = new ExportImportProgressInfo();

            foreach (var moduleInfo in manifest.Modules)
            {
                var moduleDescriptor = InnerGetModulesWithInterface(typeof(IImportSupport)).FirstOrDefault(x => x.Id == moduleInfo.Id);
                if (moduleDescriptor != null)
                {
                    var modulePart = zipArchive.GetEntry(moduleInfo.PartUri.TrimStart('/'));
                    using (var modulePartStream = modulePart.Open())
                    {
                        void ModuleProgressCallback(ExportImportProgressInfo x)
                        {
                            progressInfo.Description = $"{moduleInfo.Id}: {x.Description}";
                            progressInfo.Errors      = x.Errors;
                            progressCallback(progressInfo);
                        }

                        if (moduleDescriptor.ModuleInstance is IImportSupport importer)
                        {
                            try
                            {
                                //TODO: Add JsonConverter which will be materialized concrete ExportImport option type
                                var options = manifest.Options
                                              .DefaultIfEmpty(new ExportImportOptions {
                                    HandleBinaryData = manifest.HandleBinaryData, ModuleIdentity = new ModuleIdentity(moduleDescriptor.Identity.Id, moduleDescriptor.Identity.Version)
                                })
                                              .FirstOrDefault(x => x.ModuleIdentity.Id == moduleDescriptor.Identity.Id);
                                await importer.ImportAsync(modulePartStream, options, ModuleProgressCallback, cancellationToken);
                            }
                            catch (Exception ex)
                            {
                                errors.AppendLine($"<b> {moduleInfo.Id} </b>: {ex} <br><br>");
                                progressInfo.Errors.Add($"{moduleInfo.Id}: {ex}");
                                progressCallback(progressInfo);
                            }
                        }
                    }
                }
            }

            if (errors.Length != 0)
            {
                throw new InvalidOperationException(errors.ToString());
            }
        }
Esempio n. 21
0
        public PlatformExportManifest GetNewExportManifest(string author)
        {
            var retVal = new PlatformExportManifest
            {
                Author          = author,
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Modules         = InnerGetModulesWithInterface(typeof(ISupportExportImportModule)).Select(x => new ExportModuleInfo
                {
                    Id           = x.Id,
                    Dependencies = x.Dependencies != null ? x.Dependencies.ToArray() : null,
                    Version      = x.Version,
                    Description  = ((ISupportExportImportModule)x.ModuleInfo.ModuleInstance).ExportDescription
                }).ToArray()
            };

            return(retVal);
        }
Esempio n. 22
0
        private async Task ExportModulesInternalAsync(ZipArchive zipArchive, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback, ICancellationToken cancellationToken)
        {
            var progressInfo = new ExportImportProgressInfo();

            foreach (var module in manifest.Modules)
            {
                var moduleDescriptor = InnerGetModulesWithInterface(typeof(IImportSupport)).FirstOrDefault(x => x.Id == module.Id);
                if (moduleDescriptor != null)
                {
                    //Create part for module
                    var moduleZipEntryName = module.Id + ".json";
                    var zipEntry           = zipArchive.CreateEntry(moduleZipEntryName, CompressionLevel.Optimal);

                    void ModuleProgressCallback(ExportImportProgressInfo x)
                    {
                        progressInfo.Description = $"{ module.Id }: { x.Description }";
                        progressInfo.Errors      = x.Errors;
                        progressCallback(progressInfo);
                    }

                    progressInfo.Description = $"{module.Id}: exporting...";
                    progressCallback(progressInfo);
                    if (moduleDescriptor.ModuleInstance is IExportSupport exporter)
                    {
                        try
                        {
                            //TODO: Add JsonConverter which will be materialized concrete ExportImport option type
                            //ToDo: Added check ExportImportOptions for modules (DefaultIfEmpty)
                            var options = manifest.Options
                                          .DefaultIfEmpty(new ExportImportOptions {
                                HandleBinaryData = manifest.HandleBinaryData, ModuleIdentity = new ModuleIdentity(module.Id, SemanticVersion.Parse(module.Version))
                            })
                                          .FirstOrDefault(x => x.ModuleIdentity.Id == moduleDescriptor.Identity.Id);
                            await exporter.ExportAsync(zipEntry.Open(), options, ModuleProgressCallback, cancellationToken);
                        }
                        catch (Exception ex)
                        {
                            progressInfo.Errors.Add($"{ module.Id}: {ex}");
                            progressCallback(progressInfo);
                        }
                    }
                    module.PartUri = moduleZipEntryName;
                }
            }
        }
        public void Import(Stream stream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException("manifest");
            }

            var progressInfo = new ExportImportProgressInfo();

            progressInfo.Description = "Starting platform import...";
            progressCallback(progressInfo);

            using (var package = ZipPackage.Open(stream, FileMode.Open))
            {
                //Import selected platform entries
                ImportPlatformEntriesInternal(package, manifest, progressCallback);
                //Import selected modules
                ImportModulesInternal(package, manifest, progressCallback);
            }
        }
        public void DoExport(Stream outStream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo {
                Description = "loading data..."
            };

            progressCallback(progressInfo);

            using (StreamWriter sw = new StreamWriter(outStream, Encoding.UTF8))
            {
                using (JsonTextWriter writer = new JsonTextWriter(sw))
                {
                    writer.WriteStartObject();

                    ExportDerivativeContractEntity(writer, _serializer, manifest, progressInfo, progressCallback);
                    ExportDerivativeContractItemEntity(writer, _serializer, manifest, progressInfo, progressCallback);

                    writer.WriteEndObject();
                    writer.Flush();
                }
            }
        }
        public void DoExport(Stream outStream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo {
                Description = "loading data..."
            };

            progressCallback(progressInfo);

            using (StreamWriter sw = new StreamWriter(outStream, Encoding.UTF8))
                using (JsonTextWriter writer = new JsonTextWriter(sw))
                {
                    writer.WriteStartObject();

                    ExportCatalogs(writer, _serializer, manifest, progressInfo, progressCallback);
                    ExportCategories(writer, _serializer, manifest, progressInfo, progressCallback);
                    ExportProperties(writer, _serializer, manifest, progressInfo, progressCallback);
                    ExportProducts(writer, _serializer, manifest, progressInfo, progressCallback);

                    writer.WriteEndObject();
                    writer.Flush();
                }
        }
Esempio n. 26
0
        public async Task ImportAsync(Stream inputStream, PlatformExportManifest importOptions, Action <ExportImportProgressInfo> progressCallback, ICancellationToken сancellationToken)
        {
            if (importOptions == null)
            {
                throw new ArgumentNullException(nameof(importOptions));
            }

            var progressInfo = new ExportImportProgressInfo();

            progressInfo.Description = "Starting platform import...";
            progressCallback(progressInfo);

            using (var zipArchive = new ZipArchive(inputStream, ZipArchiveMode.Read, true))
                using (EventSuppressor.SupressEvents())
                {
                    //Import selected platform entries
                    await ImportPlatformEntriesInternalAsync(zipArchive, importOptions, progressCallback, сancellationToken);

                    //Import selected modules
                    await ImportModulesInternalAsync(zipArchive, importOptions, progressCallback, сancellationToken);
                }
        }
        public void DoImport(Stream inputStream, PlatformExportManifest manifest,
                             Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();

            using (StreamReader streamReader = new StreamReader(inputStream))
            {
                using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                {
                    while (jsonReader.Read())
                    {
                        if (jsonReader.TokenType != JsonToken.PropertyName)
                        {
                            continue;
                        }

                        switch (jsonReader.Value.ToString())
                        {
                        case "Options":
                            jsonReader.Read();
                            var options = _serializer.Deserialize <ThumbnailOption[]>(jsonReader);
                            progressInfo.Description = $"Importing {options.Length} options...";
                            progressCallback(progressInfo);
                            _optionService.SaveOrUpdate(options);
                            break;

                        case "Tasks":
                            jsonReader.Read();
                            var tasks = _serializer.Deserialize <ThumbnailTask[]>(jsonReader);
                            progressInfo.Description = $"Importing {tasks.Length} tasks...";
                            progressCallback(progressInfo);
                            _taskService.SaveOrUpdate(tasks);
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 28
0
        private void ExportModulesInternal(Package package, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();

            foreach (var module in manifest.Modules)
            {
                var moduleDescriptor = InnerGetModulesWithInterface(typeof(ISupportExportImportModule)).FirstOrDefault(x => x.Id == module.Id);
                if (moduleDescriptor != null)
                {
                    //Create part for module
                    var modulePartUri = PackUriHelper.CreatePartUri(new Uri(module.Id + ".json", UriKind.Relative));
                    var modulePart    = package.CreatePart(modulePartUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Normal);

                    Action <ExportImportProgressInfo> modulePorgressCallback = (x) =>
                    {
                        progressInfo.Description = $"{module.Id}: {x.Description}";
                        progressInfo.Errors      = x.Errors;
                        progressCallback(progressInfo);
                    };

                    progressInfo.Description = $"{module.Id}: exporting...";
                    progressCallback(progressInfo);

                    try
                    {
                        ((ISupportExportImportModule)moduleDescriptor.ModuleInstance).DoExport(modulePart.GetStream(), manifest, modulePorgressCallback);
                    }
                    catch (Exception ex)
                    {
                        progressInfo.Errors.Add($"{module.Id}: {ex.ExpandExceptionMessage()}");
                        progressCallback(progressInfo);
                    }

                    module.PartUri = modulePartUri.ToString();
                }
            }
        }
        private void ExportTasks(JsonTextWriter writer, JsonSerializer serializer, PlatformExportManifest manifest,
                                 ExportImportProgressInfo progressInfo, Action <ExportImportProgressInfo> progressCallback)
        {
            progressInfo.Description = "Exporting tasks...";
            progressCallback(progressInfo);

            var totalCount = _taskSearchService.Search(new ThumbnailTaskSearchCriteria()
            {
                Take = 0, Skip = 0
            })
                             .TotalCount;

            writer.WritePropertyName("TakskTotalCount");
            writer.WriteValue(totalCount);

            writer.WritePropertyName("Tasks");
            writer.WriteStartArray();

            for (int i = 0; i < totalCount; i += _batchSize)
            {
                var tasks = _taskSearchService.Search(new ThumbnailTaskSearchCriteria {
                    Take = _batchSize, Skip = i
                })
                            .Results;

                foreach (var task in tasks)
                {
                    serializer.Serialize(writer, task);
                }

                writer.Flush();
                progressInfo.Description = $"{Math.Min(totalCount, i + _batchSize)} of {totalCount} tasks exported";
                progressCallback(progressInfo);
            }

            writer.WriteEndArray();
        }
Esempio n. 30
0
        public void Export(Stream outStream, PlatformExportManifest manifest, Action <ExportImportProgressInfo> progressCallback)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException("manifest");
            }

            using (var package = Package.Open(outStream, FileMode.Create))
            {
                //Export all selected platform entries
                ExportPlatformEntriesInternal(package, manifest, progressCallback);
                //Export all selected  modules
                ExportModulesInternal(package, manifest, progressCallback);

                //Write system information about exported modules
                var manifestPart = package.CreatePart(_manifestPartUri, "application/javascript");

                //After all modules exported need write export manifest part
                using (var stream = manifestPart.GetStream())
                {
                    manifest.SerializeJson(stream, GetJsonSerializer());
                }
            }
        }