Ejemplo n.º 1
0
        public SettingsMigrator(SmartObjectContext ctx)
        {
            Guard.NotNull(ctx, nameof(ctx));

            _ctx      = ctx;
            _settings = _ctx.Set <Setting>();
        }
        public ActivityLogTypeMigrator(SmartObjectContext ctx)
        {
            Guard.ArgumentNotNull(() => ctx);

            _ctx = ctx;
            _activityLogTypeRecords = _ctx.Set<ActivityLogType>();
        }
Ejemplo n.º 3
0
        public ActivityLogTypeMigrator(SmartObjectContext ctx)
        {
            Guard.NotNull(ctx, nameof(ctx));

            _ctx = ctx;
            _activityLogTypeRecords = _ctx.Set <ActivityLogType>();
        }
Ejemplo n.º 4
0
        public void SetUp()
        {
            var ctx = new SmartObjectContext(GetTestDbName());

            Database.SetInitializer(new DropCreateDatabaseAlways <SmartObjectContext>());
            ctx.Database.Initialize(true);
        }
Ejemplo n.º 5
0
 public virtual void SetUp()
 {
     context = new SmartObjectContext(GetTestDbName());
     context.Database.Delete();
     Database.SetInitializer(new TestDatabaseInitializer <SmartObjectContext, MigrationsConfiguration>(GetTestDbName()));
     context.Database.Initialize(true);
 }
Ejemplo n.º 6
0
        public SettingsMigrator(SmartObjectContext ctx)
        {
            Guard.ArgumentNotNull(() => ctx);

            _ctx      = ctx;
            _settings = _ctx.Set <Setting>();
        }
		public SettingsMigrator(SmartObjectContext ctx)
		{
			Guard.ArgumentNotNull(() => ctx);

			_ctx = ctx;
			_settings = _ctx.Set<Setting>();
		}
Ejemplo n.º 8
0
        public ActivityLogTypeMigrator(SmartObjectContext ctx)
        {
            Guard.ArgumentNotNull(() => ctx);

            _ctx = ctx;
            _activityLogTypeRecords = _ctx.Set <ActivityLogType>();
        }
Ejemplo n.º 9
0
        public LocaleResourcesMigrator(SmartObjectContext ctx)
        {
            Guard.NotNull(ctx, nameof(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);
        }
Ejemplo n.º 11
0
 public NewsItemConverter(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));
     }
 }
        public LocaleResourcesMigrator(SmartObjectContext ctx)
        {
            Guard.ArgumentNotNull(() => 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>();
        }
Ejemplo n.º 14
0
        public PermissionMigrator(SmartObjectContext ctx)
        {
            Guard.ArgumentNotNull(() => ctx);

            _ctx = ctx;
            _permissionRecords = _ctx.Set <PermissionRecord>();
            _customerRoles     = _ctx.Set <CustomerRole>().Expand(x => x.PermissionRecords);
        }
        public void Can_generate_schema()
        {
            var ctx = new SmartObjectContext("Test");
			Database.SetInitializer<SmartObjectContext>(null);
            string result = ctx.CreateDatabaseScript();
            result.ShouldNotBeNull();
            Console.Write(result);
        }
Ejemplo n.º 16
0
        public PermissionMigrator(SmartObjectContext ctx)
        {
            Guard.NotNull(ctx, nameof(ctx));

            _ctx = ctx;
            _permissionRecords = _ctx.Set <PermissionRecord>();
            _customerRoles     = _ctx.Set <CustomerRole>().Expand(x => x.PermissionRecords);
        }
Ejemplo n.º 17
0
        public void Can_generate_schema()
        {
            var ctx = new SmartObjectContext("Test");

            Database.SetInitializer <SmartObjectContext>(null);
            string result = ctx.CreateDatabaseScript();

            result.ShouldNotBeNull();
            Console.Write(result);
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        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);
                }
            }
        }
Ejemplo n.º 20
0
        public void CreateSettings(SmartObjectContext ctx)
        {
            var prefix = nameof(MediaSettings) + ".";

            ctx.MigrateSettings(x =>
            {
                x.Add(prefix + nameof(MediaSettings.ImageTypes), string.Join(" ", MediaType.Image.DefaultExtensions));
                x.Add(prefix + nameof(MediaSettings.VideoTypes), string.Join(" ", MediaType.Video.DefaultExtensions));
                x.Add(prefix + nameof(MediaSettings.AudioTypes), string.Join(" ", MediaType.Audio.DefaultExtensions));
                x.Add(prefix + nameof(MediaSettings.DocumentTypes), string.Join(" ", MediaType.Document.DefaultExtensions));
                x.Add(prefix + nameof(MediaSettings.TextTypes), string.Join(" ", MediaType.Text.DefaultExtensions));
            });
        }
Ejemplo n.º 21
0
        public static void MigrateLocaleResources(this SmartObjectContext ctx, Action <LocaleResourcesBuilder> fn, bool updateTouchedResources = false)
        {
            Guard.NotNull(ctx, nameof(ctx));
            Guard.NotNull(fn, nameof(fn));

            var builder = new LocaleResourcesBuilder();

            fn(builder);
            var entries = builder.Build();

            var migrator = new LocaleResourcesMigrator(ctx);

            migrator.Migrate(entries, updateTouchedResources);
        }
Ejemplo n.º 22
0
        public static void ExecutePendingResourceMigrations(string resPath, SmartObjectContext dbContext)
        {
            Guard.ArgumentNotNull(() => dbContext);

            string headPath = Path.Combine(resPath, "head.txt");

            if (!File.Exists(headPath))
            {
                return;
            }

            string resHead = File.ReadAllText(headPath).Trim();

            if (!MigratorUtils.IsValidMigrationId(resHead))
            {
                return;
            }

            var migrator   = new DbMigrator(new MigrationsConfiguration());
            var migrations = GetPendingResourceMigrations(migrator, resHead);

            foreach (var id in migrations)
            {
                if (IsAutomaticMigration(id))
                {
                    continue;
                }

                if (!IsValidMigrationId(id))
                {
                    continue;
                }

                // Resolve and instantiate the DbMigration instance from the assembly
                var migration = CreateMigrationInstanceByMigrationId(id, migrator.Configuration);

                var provider = migration as ILocaleResourcesProvider;
                if (provider == null)
                {
                    continue;
                }

                var builder = new LocaleResourcesBuilder();
                provider.MigrateLocaleResources(builder);

                var resEntries  = builder.Build();
                var resMigrator = new LocaleResourcesMigrator(dbContext);
                resMigrator.Migrate(resEntries);
            }
        }
Ejemplo n.º 23
0
        public static void MigrateSettings(this SmartObjectContext ctx, Action <SettingsBuilder> fn)
        {
            Guard.NotNull(ctx, nameof(ctx));
            Guard.NotNull(fn, nameof(fn));

            var builder = new SettingsBuilder();

            fn(builder);
            var entries = builder.Build();

            var migrator = new SettingsMigrator(ctx);

            migrator.Migrate(entries);
        }
Ejemplo n.º 24
0
 public void Add(Country country)
 {
     using (var ctx = new SmartObjectContext())
     {
         country.Name               = "China";
         country.AllowsBilling      = true;
         country.AllowsShipping     = true;
         country.LimitedToStores    = false;
         country.NumericIsoCode     = 1;
         country.Published          = true;
         country.ThreeLetterIsoCode = "a";
         ctx.Countries.Add(country);
         var id = ctx.SaveChanges();
     }
 }
Ejemplo n.º 25
0
        /// <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);
        }
Ejemplo n.º 26
0
        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();
            }
        }
Ejemplo n.º 27
0
        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);
                }
            }
        }
Ejemplo n.º 28
0
        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);
        }
Ejemplo n.º 29
0
        /// <remarks>
        /// Lazy storing... fired on app shut down. Note that items with CacheItemPriority.NotRemovable are not removed when the cache is emptied.
        /// We're beyond infrastructure and cannot use IOC objects here. It would lead to ComponentNotRegisteredException from autofac.
        /// </remarks>
        private static void OnDataRemoved(string key, object value, CacheItemRemovedReason reason)
        {
            try
            {
                if (key == Key)
                {
                    var cacheData = value as List <WebApiUserCacheData>;

                    if (cacheData != null)
                    {
                        var dataToStore = cacheData.Where(x => x.LastRequest.HasValue && x.IsValid);

                        if (dataToStore.Count() > 0)
                        {
                            if (DataSettings.Current.IsValid())
                            {
                                var dbContext = new SmartObjectContext(DataSettings.Current.DataConnectionString);

                                foreach (var user in dataToStore)
                                {
                                    try
                                    {
                                        dbContext.Execute("Update GenericAttribute Set Value = {1} Where Id = {0}", user.GenericAttributeId, user.ToString());
                                    }
                                    catch (Exception exc)
                                    {
                                        exc.Dump();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                exc.Dump();
            }
        }
		public void SetUp()
		{
			var ctx = new SmartObjectContext(GetTestDbName());
			Database.SetInitializer(new DropCreateDatabaseAlways<SmartObjectContext>());
			ctx.Database.Initialize(true);
		}
Ejemplo n.º 31
0
        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);
        }
Ejemplo n.º 32
0
 protected void ReloadContext()
 {
     context.Dispose();
     context = new SmartObjectContext(GetTestDbName());
 }
Ejemplo n.º 33
0
        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);
                    }
                }
            }
        }
Ejemplo n.º 34
0
 public virtual void SetUp()
 {
     context = new SmartObjectContext(GetTestDbName());
 }
Ejemplo n.º 35
0
        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();
                    }
                }
            }
        }
Ejemplo n.º 36
0
        public void TearDown()
        {
            var ctx = new SmartObjectContext(GetTestDbName());

            ctx.Database.Delete();
        }
        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 TearDown()
		{
			var ctx = new SmartObjectContext(GetTestDbName());
			ctx.Database.Delete();
		}