public LocaleResourcesMigrator(SmartObjectContext ctx) { Guard.NotNull(ctx, nameof(ctx)); _ctx = ctx; _languages = _ctx.Set <Language>(); _resources = _ctx.Set <LocaleStringResource>(); }
public LocaleResourcesMigrator(SmartObjectContext ctx) { Guard.ArgumentNotNull(() => ctx); _ctx = ctx; _languages = _ctx.Set <Language>(); _resources = _ctx.Set <LocaleStringResource>(); }
public PermissionMigrator(SmartObjectContext ctx) { Guard.ArgumentNotNull(() => ctx); _ctx = ctx; _permissionRecords = _ctx.Set <PermissionRecord>(); _customerRoles = _ctx.Set <CustomerRole>().Expand(x => x.PermissionRecords); }
public LocaleResourcesMigrator(SmartObjectContext ctx) { Guard.ArgumentNotNull(() => ctx); _ctx = ctx; _languages = _ctx.Set<Language>(); _resources = _ctx.Set<LocaleStringResource>(); }
public PermissionMigrator(SmartObjectContext ctx) { Guard.NotNull(ctx, nameof(ctx)); _ctx = ctx; _permissionRecords = _ctx.Set <PermissionRecord>(); _customerRoles = _ctx.Set <CustomerRole>().Expand(x => x.PermissionRecords); }
public PermissionMigrator(SmartObjectContext ctx) { Guard.ArgumentNotNull(() => ctx); _ctx = ctx; _permissionRecords = _ctx.Set<PermissionRecord>(); _customerRoles = _ctx.Set<CustomerRole>().Expand(x => x.PermissionRecords); }
public SettingsMigrator(SmartObjectContext ctx) { Guard.NotNull(ctx, nameof(ctx)); _ctx = ctx; _settings = _ctx.Set <Setting>(); }
public SettingsMigrator(SmartObjectContext ctx) { Guard.ArgumentNotNull(() => ctx); _ctx = ctx; _settings = _ctx.Set <Setting>(); }
public ActivityLogTypeMigrator(SmartObjectContext ctx) { Guard.NotNull(ctx, nameof(ctx)); _ctx = ctx; _activityLogTypeRecords = _ctx.Set <ActivityLogType>(); }
public ActivityLogTypeMigrator(SmartObjectContext ctx) { Guard.ArgumentNotNull(() => ctx); _ctx = ctx; _activityLogTypeRecords = _ctx.Set<ActivityLogType>(); }
public SettingsMigrator(SmartObjectContext ctx) { Guard.ArgumentNotNull(() => ctx); _ctx = ctx; _settings = _ctx.Set<Setting>(); }
public ActivityLogTypeMigrator(SmartObjectContext ctx) { Guard.ArgumentNotNull(() => ctx); _ctx = ctx; _activityLogTypeRecords = _ctx.Set <ActivityLogType>(); }
/// <summary> /// Persistance test helper /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <param name="entity">Entity</param> /// <param name="disposeContext">A value indicating whether to dispose context</param> protected T SaveAndLoadEntity <T>(T entity, bool disposeContext = true) where T : BaseEntity { context.Set <T>().Add(entity); context.SaveChanges(); object id = entity.Id; if (disposeContext) { context.Dispose(); context = new SmartObjectContext(GetTestDbName()); } var fromDb = context.Set <T>().Find(id); return(fromDb); }
/// <summary> /// Imports all template xml files to MessageTemplate table /// </summary> /// <param name="virtualRootPath">The virtual root path of templates to import, e.g. "~/Plugins/MyPlugins/EmailTemplates". Default is "~/App_Data/EmailTemplates".</param> public void ImportAll(Language language, string virtualRootPath = null) { var table = _ctx.Set <MessageTemplate>(); var sourceTemplates = LoadAll(language, virtualRootPath); var dbTemplatesMap = table .ToList() .ToMultimap(x => x.Name, x => x, StringComparer.OrdinalIgnoreCase); foreach (var source in sourceTemplates) { if (dbTemplatesMap.ContainsKey(source.Name)) { foreach (var target in dbTemplatesMap[source.Name]) { if (source.To.HasValue()) { target.To = source.To; } if (source.ReplyTo.HasValue()) { target.ReplyTo = source.ReplyTo; } if (source.Subject.HasValue()) { target.Subject = source.Subject; } if (source.ModelTypes.HasValue()) { target.ModelTypes = source.ModelTypes; } if (source.Body.HasValue()) { target.Body = source.Body; } } } else { var template = new MessageTemplate { Name = source.Name, To = source.To, ReplyTo = source.ReplyTo, Subject = source.Subject, ModelTypes = source.ModelTypes, Body = source.Body, IsActive = true, EmailAccountId = (_defaultEmailAccount?.Id).GetValueOrDefault(), }; table.Add(template); } } _ctx.SaveChanges(); }
public MessageTemplateConverter(IDbContext context) { _ctx = context as SmartObjectContext; if (_ctx == null) { throw new ArgumentException("Passed context must be an instance of type '{0}'.".FormatInvariant(typeof(SmartObjectContext)), nameof(context)); } _defaultEmailAccount = _ctx.Set <EmailAccount>().FirstOrDefault(x => x.Email != null); }
public void MigrateMediaFiles_Old(SmartObjectContext ctx) { var query = ctx.Set <MediaFile>(); //.Where(x => x.Version == 0) //.Include(x => x.MediaStorage); var pager = new FastPager <MediaFile>(query, 1000); using (var scope = new DbContextScope(ctx, hooksEnabled: false, autoCommit: false, proxyCreation: false, validateOnSave: false, lazyLoading: false)) { while (pager.ReadNextPage(out var files)) { foreach (var file in files) { if (file.Version > 0) { continue; } if (file.Extension.IsEmpty()) { file.Extension = MimeTypes.MapMimeTypeToExtension(file.MimeType); } var name = file.Name; if (name.IsEmpty()) { name = file.Id.ToString(System.Globalization.CultureInfo.InvariantCulture); } else { name = MediaHelper.NormalizeFileName(file.Name.Truncate(292)); } file.Name = name + "." + file.Extension; file.CreatedOnUtc = file.UpdatedOnUtc; file.Version = 1; ProcessMediaFile(file); } // Save to DB int num = scope.Commit(); // Breathe ctx.DetachEntities <MediaFile>(deep: true); } } }
/// <summary> /// Imports all template xml files to MessageTemplate table /// </summary> public void ImportAll(Language language) { var table = _ctx.Set <MessageTemplate>(); var sourceTemplates = LoadAll(language); var dbTemplatesMap = table .ToList() .ToDictionarySafe(x => x.Name, StringComparer.OrdinalIgnoreCase); foreach (var source in sourceTemplates) { if (dbTemplatesMap.TryGetValue(source.Name, out var target)) { if (source.To.HasValue()) { target.To = source.To; } if (source.ReplyTo.HasValue()) { target.ReplyTo = source.ReplyTo; } if (source.Subject.HasValue()) { target.Subject = source.Subject; } if (source.ModelTypes.HasValue()) { target.ModelTypes = source.ModelTypes; } if (source.Body.HasValue()) { target.Body = source.Body; } } else { target = new MessageTemplate { Name = source.Name, To = source.To, ReplyTo = source.ReplyTo, Subject = source.Subject, ModelTypes = source.ModelTypes, Body = source.Body, IsActive = true, EmailAccountId = (_defaultEmailAccount?.Id).GetValueOrDefault(), }; table.Add(target); } } _ctx.SaveChanges(); }
public void AddActivityLogType(string systemKeyword, string enName, string deName) { Guard.NotEmpty(systemKeyword, nameof(systemKeyword)); Guard.NotEmpty(enName, nameof(enName)); Guard.NotEmpty(deName, nameof(deName)); var record = _activityLogTypeRecords.FirstOrDefault(x => x.SystemKeyword == systemKeyword); if (record == null) { var language = GetDefaultAdminLanguage(_ctx.Set <Setting>(), _ctx.Set <Language>()); _activityLogTypeRecords.Add(new ActivityLogType { Enabled = true, SystemKeyword = systemKeyword, Name = (language.UniqueSeoCode.IsCaseInsensitiveEqual("de") ? deName : enName) }); _ctx.SaveChanges(); } }
private void ReRefMessageTemplateAttachments( SmartObjectContext ctx, Dictionary <int, MessageTemplate> messageTemplatesDict, Dictionary <int, Download> downloads) { bool hasChanges = false; foreach (var kvp in messageTemplatesDict) { var downloadId = kvp.Key; var mt = kvp.Value; var idxProp = Array.IndexOf(new int?[] { mt.Attachment1FileId, mt.Attachment2FileId, mt.Attachment3FileId }, downloadId) + 1; if (idxProp > 0) { var d = downloads.Get(downloadId); if (d?.MediaFileId != null) { // Change Download.Id ref to MediaFile.Id if (idxProp == 1) { mt.Attachment1FileId = d.MediaFileId; } if (idxProp == 2) { mt.Attachment2FileId = d.MediaFileId; } if (idxProp == 3) { mt.Attachment3FileId = d.MediaFileId; } // We don't need Download entity anymore ctx.Set <Download>().Remove(d); hasChanges = true; } } } if (hasChanges) { ctx.SaveChanges(); } }
public void MigrateMediaFiles(SmartObjectContext ctx) { var query = ctx.Set <MediaFile>() //.Where(x => x.Version == 0) .Include(x => x.MediaStorage); var pager = new FastPager <MediaFile>(query, 1000); using (var scope = new DbContextScope(ctx, hooksEnabled: false, autoCommit: false, proxyCreation: false, validateOnSave: false, lazyLoading: false)) { while (pager.ReadNextPage(out var files)) { foreach (var file in files) { if (file.Version > 0) { continue; } if (file.Extension.IsEmpty()) { file.Extension = MimeTypes.MapMimeTypeToExtension(file.MimeType); } file.Name = file.Name + "." + file.Extension; file.CreatedOnUtc = file.UpdatedOnUtc; file.Version = 1; ProcessMediaFile(file); } // Save to DB int num = scope.Commit(); // Breathe ctx.DetachEntities <MediaFile>(deep: true); } } }
private static IDictionary <int, int> GetPoductPictureMap(SmartObjectContext context, IEnumerable <int> productIds) { var map = new Dictionary <int, int>(); var query = from pp in context.Set <ProductPicture>().AsNoTracking() where productIds.Contains(pp.ProductId) group pp by pp.ProductId into g select new { ProductId = g.Key, PictureIds = g.OrderBy(x => x.DisplayOrder) .Take(1) .Select(x => x.PictureId) }; map = query.ToList().ToDictionary(x => x.ProductId, x => x.PictureIds.First()); return(map); }
/// <summary> /// Imports all blog xml files to BlogPost table /// </summary> /// <param name="virtualRootPath">The virtual root path of blogs to import, e.g. "~/Plugins/MyPlugins/BlogPost". Default is "~/App_Data/Samples/blog".</param> /// <returns>List of new imported blog posts</returns> public IList <BlogPost> ImportAll(Language language, string virtualRootPath = null) { var blogsImported = new List <BlogPost>(); var table = _ctx.Set <BlogPost>(); var sourceBlogs = LoadAll(language); var dbBlogMap = table.ToList().ToMultimap(x => x.Title, x => x, StringComparer.OrdinalIgnoreCase); foreach (var source in sourceBlogs) { if (dbBlogMap.ContainsKey(source.Title)) { foreach (var target in dbBlogMap[source.Title]) { if (source.Title.HasValue()) { target.Title = source.Title; } if (source.MetaTitle.HasValue()) { target.MetaTitle = source.MetaTitle; } if (source.MetaDescription.HasValue()) { target.MetaDescription = source.MetaDescription; } if (source.Intro.HasValue()) { target.Intro = source.Intro; } if (source.Body.HasValue()) { target.Body = source.Body; } if (source.Tags.HasValue()) { target.Tags = source.Tags; } if (source.CreatedOnUtc != null) { target.CreatedOnUtc = source.CreatedOnUtc; } if (source.MediaFile != null) { target.MediaFile = source.MediaFile; } if (source.PreviewMediaFile != null) { target.PreviewMediaFile = source.PreviewMediaFile; } if (source.SectionBg.HasValue()) { target.SectionBg = source.SectionBg; } target.DisplayTagsInPreview = source.DisplayTagsInPreview; target.PreviewDisplayType = source.PreviewDisplayType; target.AllowComments = source.AllowComments; } } else { var blog = new BlogPost { Title = source.Title, MetaTitle = source.MetaTitle, MetaDescription = source.MetaDescription, Intro = source.Intro, Body = source.Body, Tags = source.Tags, DisplayTagsInPreview = source.DisplayTagsInPreview, CreatedOnUtc = source.CreatedOnUtc, PreviewDisplayType = source.PreviewDisplayType, MediaFile = source.MediaFile, PreviewMediaFile = source.PreviewMediaFile, AllowComments = source.AllowComments, SectionBg = source.SectionBg, IsPublished = true }; blogsImported.Add(blog); table.Add(blog); } } _ctx.SaveChanges(); return(blogsImported); }
public void Can_get_customer_content_by_type() { var customer = SaveAndLoadEntity <Customer>(GetTestCustomer(), false); var product = SaveAndLoadEntity <Product>(GetTestProduct(), false); var productReview = new ProductReview { Customer = customer, Product = product, Title = "Test", ReviewText = "A review", IpAddress = "192.168.1.1", IsApproved = true, CreatedOnUtc = new DateTime(2010, 01, 01), UpdatedOnUtc = new DateTime(2010, 01, 02), }; var productReviewHelpfulness = new ProductReviewHelpfulness { Customer = customer, ProductReview = productReview, WasHelpful = true, IpAddress = "192.168.1.1", IsApproved = true, CreatedOnUtc = new DateTime(2010, 01, 03), UpdatedOnUtc = new DateTime(2010, 01, 04) }; var blogComment = new BlogComment { Customer = customer, IpAddress = "192.168.1.1", IsApproved = true, CreatedOnUtc = new DateTime(2010, 01, 03), UpdatedOnUtc = new DateTime(2010, 01, 04), BlogPost = new BlogPost() { Title = "Title 1", Body = "Body 1", AllowComments = true, CreatedOnUtc = new DateTime(2010, 01, 01), Language = new Language() { Name = "English", LanguageCulture = "en-Us", } } }; context.Set <CustomerContent>().Add(productReview); context.Set <CustomerContent>().Add(productReviewHelpfulness); context.Set <CustomerContent>().Add(blogComment); context.SaveChanges(); context.Dispose(); context = new SmartObjectContext(GetTestDbName()); var query = context.Set <CustomerContent>(); query.ToList().Count.ShouldEqual(3); var dbReviews = query.OfType <ProductReview>().ToList(); dbReviews.Count().ShouldEqual(1); dbReviews.First().ReviewText.ShouldEqual("A review"); var dbHelpfulnessRecords = query.OfType <ProductReviewHelpfulness>().ToList(); dbHelpfulnessRecords.Count().ShouldEqual(1); dbHelpfulnessRecords.First().WasHelpful.ShouldEqual(true); var dbBlogCommentRecords = query.OfType <BlogComment>().ToList(); dbBlogCommentRecords.Count().ShouldEqual(1); }
public void Can_get_customer_content_by_type() { var customer = SaveAndLoadEntity<Customer>(GetTestCustomer(), false); var product = SaveAndLoadEntity<Product>(GetTestProduct(), false); var productReview = new ProductReview { Customer = customer, Product = product, Title = "Test", ReviewText = "A review", IpAddress = "192.168.1.1", IsApproved = true, CreatedOnUtc = new DateTime(2010, 01, 01), UpdatedOnUtc = new DateTime(2010, 01, 02), }; var productReviewHelpfulness = new ProductReviewHelpfulness { Customer = customer, ProductReview = productReview, WasHelpful = true, IpAddress = "192.168.1.1", IsApproved = true, CreatedOnUtc = new DateTime(2010, 01, 03), UpdatedOnUtc = new DateTime(2010, 01, 04) }; var blogComment = new BlogComment { Customer = customer, IpAddress = "192.168.1.1", IsApproved = true, CreatedOnUtc = new DateTime(2010, 01, 03), UpdatedOnUtc = new DateTime(2010, 01, 04), BlogPost = new BlogPost() { Title = "Title 1", Body = "Body 1", AllowComments = true, CreatedOnUtc = new DateTime(2010, 01, 01), Language = new Language() { Name = "English", LanguageCulture = "en-Us", } } }; var table = context.Set<CustomerContent>(); table.RemoveRange(table.ToList()); table.Add(productReview); table.Add(productReviewHelpfulness); table.Add(blogComment); context.SaveChanges(); context.Dispose(); context = new SmartObjectContext(GetTestDbName()); var query = context.Set<CustomerContent>(); query.ToList().Count.ShouldEqual(3); var dbReviews = query.OfType<ProductReview>().ToList(); dbReviews.Count().ShouldEqual(1); dbReviews.First().ReviewText.ShouldEqual("A review"); var dbHelpfulnessRecords = query.OfType<ProductReviewHelpfulness>().ToList(); dbHelpfulnessRecords.Count().ShouldEqual(1); dbHelpfulnessRecords.First().WasHelpful.ShouldEqual(true); var dbBlogCommentRecords = query.OfType<BlogComment>().ToList(); dbBlogCommentRecords.Count().ShouldEqual(1); }
public void MigrateDownloads(SmartObjectContext ctx) { var sql = "SELECT * FROM [Download] WHERE [MediaFileId] IS NULL AND [UseDownloadUrl] = 0"; var downloadStubs = ctx.SqlQuery <DownloadStub>(sql).ToDictionary(x => x.Id); var downloadsFolderId = _albumRegistry.GetAlbumByName(SystemAlbumProvider.Downloads)?.Id; var messagesFolderId = _albumRegistry.GetAlbumByName(SystemAlbumProvider.Messages)?.Id; var newFiles = new List <MediaFile>(); using (var scope = new DbContextScope(ctx, validateOnSave: false, hooksEnabled: false, autoCommit: false, autoDetectChanges: false)) { var messageTemplates = ctx.Set <MessageTemplate>() .Where(x => x.Attachment1FileId.HasValue || x.Attachment2FileId.HasValue || x.Attachment3FileId.HasValue) .ToList(); // Key = Download.Id var messageTemplatesDict = new Dictionary <int, MessageTemplate>(); foreach (var mt in messageTemplates) { if (mt.Attachment1FileId.HasValue) { messageTemplatesDict[mt.Attachment1FileId.Value] = mt; } if (mt.Attachment2FileId.HasValue) { messageTemplatesDict[mt.Attachment2FileId.Value] = mt; } if (mt.Attachment3FileId.HasValue) { messageTemplatesDict[mt.Attachment3FileId.Value] = mt; } } var hasPostProcessor = _isFsProvider || messageTemplatesDict.Count > 0; var query = ctx.Set <Download>().Where(x => x.MediaFileId == null); var pager = new FastPager <Download>(query, 1000); while (pager.ReadNextPage(out var downloads)) { foreach (var d in downloads) { var stub = downloadStubs.Get(d.Id); if (stub == null) { continue; } if (stub.UseDownloadUrl || string.IsNullOrEmpty(stub.Extension)) { // Something weird has happened in the past continue; } if (stub.Filename == "undefined" || string.IsNullOrEmpty(stub.Filename)) { stub.Filename = stub.Id.ToString(CultureInfo.InvariantCulture); } var isMailAttachment = false; if (messageTemplatesDict.TryGetValue(stub.Id, out var mt)) { isMailAttachment = true; } // Create and insert new MediaFile entity for the download var file = new MediaFile { CreatedOnUtc = stub.UpdatedOnUtc, UpdatedOnUtc = stub.UpdatedOnUtc, Extension = stub.Extension.TrimStart('.'), Name = stub.Filename.Truncate(292), // Extension appended later in MigrateFiles() MimeType = stub.ContentType, MediaType = MediaType.Image, // Resolved later in MigrateFiles() FolderId = isMailAttachment ? messagesFolderId : downloadsFolderId, IsTransient = stub.IsTransient, MediaStorageId = stub.MediaStorageId, Version = 0 // Ensure that this record gets processed by MigrateFiles() }; // Assign new file to download d.MediaFile = file; // To be able to move files later if (hasPostProcessor) { newFiles.Add(file); } } // Save to DB int num = scope.Commit(); if (hasPostProcessor) { var downloadsDict = downloads.ToDictionary(x => x.Id); if (_isFsProvider) { // Copy files from "Media/Downloads" to "Media/Storage" folder MoveDownloadFiles(newFiles.ToDictionary(x => x.Id), downloadsDict, downloadStubs); } // MessageTemplate attachments (Download > MediaFile) if (messageTemplatesDict.Count > 0) { ReRefMessageTemplateAttachments(ctx, messageTemplatesDict, downloadsDict); } newFiles.Clear(); } // Breathe ctx.DetachEntities <MessageTemplate>(); ctx.DetachEntities <Download>(deep: true); } } }
protected virtual InstallationResult InstallCore(ILifetimeScope scope, InstallModel model) { UpdateResult(x => { x.ProgressMessage = _locService.GetResource("Progress.CheckingRequirements"); x.Completed = false; Logger.Info(x.ProgressMessage); }); if (DataSettings.DatabaseIsInstalled()) { return(UpdateResult(x => { x.Success = true; x.RedirectUrl = Url.Action("Index", "Home"); Logger.Info("Application already installed"); })); } // set page timeout to 5 minutes this.Server.ScriptTimeout = 300; if (model.DatabaseConnectionString != null) { model.DatabaseConnectionString = model.DatabaseConnectionString.Trim(); } // SQL Server if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase)) { if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase)) { // raw connection string if (string.IsNullOrEmpty(model.DatabaseConnectionString)) { UpdateResult(x => { x.Errors.Add(_locService.GetResource("ConnectionStringRequired")); Logger.Error(x.Errors.Last()); }); } try { // try to create connection string new SqlConnectionStringBuilder(model.DatabaseConnectionString); } catch (Exception ex) { UpdateResult(x => { x.Errors.Add(_locService.GetResource("ConnectionStringWrongFormat")); Logger.Error(ex, x.Errors.Last()); }); } } else { // values if (string.IsNullOrEmpty(model.SqlServerName)) { UpdateResult(x => { x.Errors.Add(_locService.GetResource("SqlServerNameRequired")); Logger.Error(x.Errors.Last()); }); } if (string.IsNullOrEmpty(model.SqlDatabaseName)) { UpdateResult(x => { x.Errors.Add(_locService.GetResource("DatabaseNameRequired")); Logger.Error(x.Errors.Last()); }); } // authentication type if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase)) { // SQL authentication if (string.IsNullOrEmpty(model.SqlServerUsername)) { UpdateResult(x => { x.Errors.Add(_locService.GetResource("SqlServerUsernameRequired")); Logger.Error(x.Errors.Last()); }); } if (string.IsNullOrEmpty(model.SqlServerPassword)) { UpdateResult(x => { x.Errors.Add(_locService.GetResource("SqlServerPasswordRequired")); Logger.Error(x.Errors.Last()); }); } } } } // Consider granting access rights to the resource to the ASP.NET request identity. // ASP.NET has a base process identity // (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, // and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. // If the application is impersonating via <identity impersonate="true"/>, // the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user. var webHelper = scope.Resolve <IWebHelper>(); // validate permissions var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper); foreach (string dir in dirsToCheck) { if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false)) { UpdateResult(x => { x.Errors.Add(string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir)); Logger.Error(x.Errors.Last()); }); } } var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper); foreach (string file in filesToCheck) { if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true)) { UpdateResult(x => { x.Errors.Add(string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file)); Logger.Error(x.Errors.Last()); }); } } if (GetInstallResult().HasErrors) { return(UpdateResult(x => { x.Completed = true; x.Success = false; x.RedirectUrl = null; Logger.Error("Aborting installation."); })); } else { SmartObjectContext dbContext = null; var shouldDeleteDbOnFailure = false; try { string connectionString = null; if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase)) { //SQL Server if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase)) { //raw connection string //we know that MARS option is required when using Entity Framework //let's ensure that it's specified var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString); sqlCsb.MultipleActiveResultSets = true; connectionString = sqlCsb.ToString(); } else { // values connectionString = CreateConnectionString( model.SqlAuthenticationType == "windowsauthentication", model.SqlServerName, model.SqlDatabaseName, model.SqlServerUsername, model.SqlServerPassword); } if (model.SqlServerCreateDatabase) { if (!SqlServerDatabaseExists(connectionString)) { //create database var collation = model.UseCustomCollation ? model.Collation : ""; var errorCreatingDatabase = CreateDatabase(connectionString, collation); if (errorCreatingDatabase.HasValue()) { return(UpdateResult(x => { x.Errors.Add(errorCreatingDatabase); x.Completed = true; x.Success = false; x.RedirectUrl = null; Logger.Error(errorCreatingDatabase); })); } else { // Database cannot be created sometimes. Weird! Seems to be Entity Framework issue // that's just wait 3 seconds Thread.Sleep(3000); shouldDeleteDbOnFailure = true; } } } else { // check whether database exists if (!SqlServerDatabaseExists(connectionString)) { return(UpdateResult(x => { x.Errors.Add(_locService.GetResource("DatabaseNotExists")); x.Completed = true; x.Success = false; x.RedirectUrl = null; Logger.Error(x.Errors.Last()); })); } } } else { // SQL CE string databaseFileName = "SmartStore.Db.sdf"; string databasePath = @"|DataDirectory|\Tenants\{0}\{1}".FormatInvariant(DataSettings.Current.TenantName, databaseFileName); connectionString = "Data Source=" + databasePath + "; Persist Security Info=False"; // drop database if exists string databaseFullPath = HostingEnvironment.MapPath(DataSettings.Current.TenantPath.EnsureEndsWith("/")) + databaseFileName; if (System.IO.File.Exists(databaseFullPath)) { System.IO.File.Delete(databaseFullPath); } shouldDeleteDbOnFailure = true; } // save settings var dataProvider = model.DataProvider; var settings = DataSettings.Current; settings.AppVersion = SmartStoreVersion.Version; settings.DataProvider = dataProvider; settings.DataConnectionString = connectionString; settings.Save(); // init data provider var dataProviderInstance = scope.Resolve <IEfDataProvider>(); // Although obsolete we have no other chance than using this here. // Delegating this to DbConfiguration is not possible during installation. #pragma warning disable 618 Database.DefaultConnectionFactory = dataProviderInstance.GetConnectionFactory(); #pragma warning restore 618 // resolve SeedData instance from primary language var lazyLanguage = _locService.GetAppLanguage(model.PrimaryLanguage); if (lazyLanguage == null) { return(UpdateResult(x => { x.Errors.Add(_locService.GetResource("Install.LanguageNotRegistered").FormatInvariant(model.PrimaryLanguage)); x.Completed = true; x.Success = false; x.RedirectUrl = null; Logger.Error(x.Errors.Last()); })); } // create the DataContext dbContext = new SmartObjectContext(); // AuditableHook must run during install dbContext.DbHookHandler = new DefaultDbHookHandler(new[] { new Lazy <IDbHook, HookMetadata>(() => new AuditableHook(), HookMetadata.Create <AuditableHook>(typeof(IAuditable), true), false) }); // IMPORTANT: Migration would run way too early otherwise Database.SetInitializer <SmartObjectContext>(null); // create Language domain object from lazyLanguage var languages = dbContext.Set <Language>(); var primaryLanguage = languages.Create(); // create a proxied type, resources cannot be saved otherwise primaryLanguage.Name = lazyLanguage.Metadata.Name; primaryLanguage.LanguageCulture = lazyLanguage.Metadata.Culture; primaryLanguage.UniqueSeoCode = lazyLanguage.Metadata.UniqueSeoCode; primaryLanguage.FlagImageFileName = lazyLanguage.Metadata.FlagImageFileName; // Build the seed configuration model var seedConfiguration = new SeedDataConfiguration { DefaultUserName = model.AdminEmail, DefaultUserPassword = model.AdminPassword, SeedSampleData = model.InstallSampleData, Data = lazyLanguage.Value, Language = primaryLanguage, StoreMediaInDB = model.MediaStorage == "db", ProgressMessageCallback = msg => UpdateResult(x => x.ProgressMessage = _locService.GetResource(msg)) }; var seeder = new InstallDataSeeder(seedConfiguration, Logger); Database.SetInitializer(new InstallDatabaseInitializer() { DataSeeders = new[] { seeder } }); UpdateResult(x => { x.ProgressMessage = _locService.GetResource("Progress.BuildingDatabase"); Logger.Info(x.ProgressMessage); }); // ===>>> actually performs the installation by calling "InstallDataSeeder.Seed()" internally. dbContext.Database.Initialize(true); // Install plugins. PluginManager.MarkAllPluginsAsUninstalled(); var pluginFinder = scope.Resolve <IPluginFinder>(); var plugins = pluginFinder.GetPlugins <IPlugin>(false) //.ToList() .OrderBy(x => x.PluginDescriptor.Group) .ThenBy(x => x.PluginDescriptor.DisplayOrder) .ToList(); var ignoredPluginsSetting = CommonHelper.GetAppSetting <string>("sm:PluginsIgnoredDuringInstallation"); var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(ignoredPluginsSetting) ? new List <string>() : ignoredPluginsSetting .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .ToList(); if (pluginsIgnoredDuringInstallation.Count > 0) { plugins = plugins.Where(x => !pluginsIgnoredDuringInstallation.Contains(x.PluginDescriptor.SystemName, StringComparer.OrdinalIgnoreCase)).ToList(); } var pluginsCount = plugins.Count; var idx = 0; using (var dbScope = new DbContextScope(autoDetectChanges: false, hooksEnabled: false)) { foreach (var plugin in plugins) { try { idx++; UpdateResult(x => { x.ProgressMessage = _locService.GetResource("Progress.InstallingPlugins").FormatInvariant(idx, pluginsCount); Logger.InfoFormat("Installing plugin '{0}'.", plugin.PluginDescriptor.FriendlyName ?? plugin.PluginDescriptor.SystemName); }); plugin.Install(); dbScope.Commit(); } catch (Exception ex) { Logger.Error(ex); if (plugin.PluginDescriptor.Installed) { PluginManager.MarkPluginAsUninstalled(plugin.PluginDescriptor.SystemName); } } } } // Detect media file tracks (must come after plugins installation) UpdateResult(x => { x.ProgressMessage = _locService.GetResource("Progress.ProcessingMedia"); Logger.Info(x.ProgressMessage); }); var mediaTracker = scope.Resolve <IMediaTracker>(); foreach (var album in scope.Resolve <IAlbumRegistry>().GetAlbumNames(true)) { mediaTracker.DetectAllTracks(album, false); } UpdateResult(x => { x.ProgressMessage = _locService.GetResource("Progress.Finalizing"); Logger.Info(x.ProgressMessage); }); // Do not ignore settings migrated by data seeder (e.g. default media storage provider). scope.Resolve <ISettingService>().ClearCache(); // SUCCESS: Redirect to home page return(UpdateResult(x => { x.Completed = true; x.Success = true; x.RedirectUrl = Url.Action("Index", "Home"); Logger.Info("Installation completed successfully"); })); } catch (Exception ex) { Logger.Error(ex); // Clear provider settings if something got wrong DataSettings.Delete(); // Delete Db if it was auto generated if (dbContext != null && shouldDeleteDbOnFailure) { try { Logger.Debug("Deleting database"); dbContext.Database.Delete(); } catch { } } var msg = ex.Message; var realException = ex; while (realException.InnerException != null) { realException = realException.InnerException; } if (!Object.Equals(ex, realException)) { msg += " (" + realException.Message + ")"; } return(UpdateResult(x => { x.Errors.Add(string.Format(_locService.GetResource("SetupFailed"), msg)); x.Success = false; x.Completed = true; x.RedirectUrl = null; })); } finally { if (dbContext != null) { dbContext.Dispose(); } } } }
public void MigrateMediaFiles(SmartObjectContext ctx) { string prevName = null; int fileIndex = 0; var query = ctx.Set <MediaFile>().OrderBy(x => x.Name); var totalCount = query.Count(); var pageSize = Math.Max(1000, Math.Min(5000, totalCount / 200)); var pageIndex = 0; using (var scope = new DbContextScope(ctx, hooksEnabled: false, autoCommit: false, proxyCreation: false, validateOnSave: false, lazyLoading: false)) { while (true) { var files = new PagedList <MediaFile>(query, pageIndex, pageSize); if (files.Count == 0) { break; } foreach (var file in files) { if (file.Version > 0) { continue; } if (file.Extension.IsEmpty()) { file.Extension = MimeTypes.MapMimeTypeToExtension(file.MimeType); } var name = file.Name; var fixedName = name; if (name.IsEmpty()) { name = fixedName = file.Id.ToString(System.Globalization.CultureInfo.InvariantCulture); } else { name = fixedName = MediaHelper.NormalizeFileName(file.Name.Truncate(292)); if (name == prevName) { // Make file name unique fixedName = name + "-" + ++fileIndex; } else { fileIndex = 0; } } prevName = name; file.Name = fixedName + "." + file.Extension; file.CreatedOnUtc = file.UpdatedOnUtc; file.Version = 1; ProcessMediaFile(file); } // Save to DB int num = scope.Commit(); // Breathe ctx.DetachEntities <MediaFile>(deep: true); if (!files.HasNextPage) { break; } pageIndex++; } } }
public void MigrateUploadedFiles(SmartObjectContext ctx) { var fileSet = ctx.Set <MediaFile>(); var folderSet = ctx.Set <MediaFolder>(); using (var scope = new DbContextScope(ctx, hooksEnabled: false, autoCommit: false, validateOnSave: false, lazyLoading: false, autoDetectChanges: false)) { var albumId = _albumRegistry.GetAlbumByName(SystemAlbumProvider.Files)?.Id; var rootFolder = _mediaFileSystem.GetFolder("Uploaded"); if (!rootFolder.Exists) { return; } ProcessFolder(rootFolder, albumId.Value); void ProcessFolder(IFolder folder, int mediaFolderId) { var newFiles = new List <FilePair>(); foreach (var uploadedFile in _mediaFileSystem.ListFiles(folder.Path)) { var file = new MediaFile { CreatedOnUtc = uploadedFile.LastUpdated, UpdatedOnUtc = uploadedFile.LastUpdated, Extension = uploadedFile.Extension.TrimStart('.'), Name = uploadedFile.Name, MimeType = MimeTypes.MapNameToMimeType(uploadedFile.Name), Size = Convert.ToInt32(uploadedFile.Size), FolderId = mediaFolderId, Version = 2 }; ProcessMediaFile(file); newFiles.Add(new FilePair { MediaFile = file, UploadedFile = uploadedFile }); fileSet.Add(file); } // Process/save files of current folder try { // Save files to DB int num = scope.Commit(); // Copy/Move files foreach (var newFile in newFiles) { if (_isFsProvider) { var newPath = GetStoragePath(newFile.MediaFile); if (!_mediaFileSystem.FileExists(newPath)) { // TODO: (mm) (mc) should we actually MOVE the file? _mediaFileSystem.CopyFile(newFile.UploadedFile.Path, newPath); } } else { _mediaStorageProvider.Save(newFile.MediaFile, MediaStorageItem.FromFile(newFile.UploadedFile)); } } if (!_isFsProvider) { // MediaFile.MediaStorageId has been updated, we need to save again. num = scope.Commit(); } } catch { throw; } finally { newFiles.Clear(); // Breathe ctx.DetachEntities <MediaFile>(deep: true); } foreach (var uploadedFolder in _mediaFileSystem.ListFolders(folder.Path)) { var mediaFolder = new MediaFolder { Name = uploadedFolder.Name, ParentId = mediaFolderId }; // Add folder and save ASAP, we need the folder id folderSet.Add(mediaFolder); ctx.SaveChanges(); ProcessFolder(uploadedFolder, mediaFolder.Id); } } } }
/// <summary> /// Imports all news xml files to NewsItem table /// </summary> /// <param name="virtualRootPath">The virtual root path of blogs to import, e.g. "~/Plugins/MyPlugins/NewsItem". Default is "~/App_Data/Samples/news".</param> /// <returns>List of new imported news items</returns> public IList <NewsItem> ImportAll(Language language, string virtualRootPath = null) { var newsImported = new List <NewsItem>(); var table = _ctx.Set <NewsItem>(); var sourceBlogs = LoadAll(language); var dbNewsMap = table.ToList().ToMultimap(x => x.Title, x => x, StringComparer.OrdinalIgnoreCase); foreach (var source in sourceBlogs) { if (dbNewsMap.ContainsKey(source.Title)) { foreach (var target in dbNewsMap[source.Title]) { if (source.Title.HasValue()) { target.Title = source.Title; } if (source.MetaTitle.HasValue()) { target.MetaTitle = source.MetaTitle; } if (source.MetaDescription.HasValue()) { target.MetaDescription = source.MetaDescription; } if (source.Short.HasValue()) { target.Short = source.Short; } if (source.Full.HasValue()) { target.Full = source.Full; } if (source.CreatedOnUtc != null) { target.CreatedOnUtc = source.CreatedOnUtc; } if (source.MediaFile != null) { target.MediaFile = source.MediaFile; } if (source.PreviewMediaFile != null) { target.PreviewMediaFile = source.PreviewMediaFile; } target.AllowComments = source.AllowComments; } } else { var news = new NewsItem { Title = source.Title, MetaTitle = source.MetaTitle, MetaDescription = source.MetaDescription, Short = source.Short, Full = source.Full, CreatedOnUtc = source.CreatedOnUtc, MediaFile = source.MediaFile, PreviewMediaFile = source.PreviewMediaFile, AllowComments = source.AllowComments, Published = true }; newsImported.Add(news); table.Add(news); } } _ctx.SaveChanges(); return(newsImported); }