public AmbientContextSuppressor()
        {
            _savedScope = DbContextScope.GetAmbientScope();

            // We're hiding the ambient scope but not removing its instance
            // altogether. This is to be tolerant to some programming errors. 
            // 
            // Suppose we removed the ambient scope instance here. If someone
            // was to start a parallel task without suppressing
            // the ambient context and then tried to suppress the ambient
            // context within the parallel task while the original flow
            // of execution was still ongoing (a strange thing to do, I know,
            // but I'm sure this is going to happen), we would end up 
            // removing the ambient context instance of the original flow 
            // of execution from within the parallel flow of execution!
            // 
            // As a result, any code in the original flow of execution
            // that would attempt to access the ambient scope would end up 
            // with a null value since we removed the instance.
            //
            // It would be a fairly nasty bug to track down. So don't let
            // that happen. Hiding the ambient scope (i.e. clearing the CallContext
            // in our execution flow but leaving the ambient scope instance untouched)
            // is safe.
            DbContextScope.HideAmbientScope();
        }
예제 #2
0
        private Download CopyDownload(int downloadId)
        {
            var download = _downloadService.GetDownloadById(downloadId);

            if (download == null)
            {
                return(null);
            }

            var clone = new Download
            {
                DownloadGuid   = Guid.NewGuid(),
                UseDownloadUrl = download.UseDownloadUrl,
                DownloadUrl    = download.DownloadUrl,
                ContentType    = download.ContentType,
                Filename       = download.Filename,
                Extension      = download.Extension,
                IsNew          = download.IsNew,
                UpdatedOnUtc   = DateTime.UtcNow
            };

            using (var scope = new DbContextScope(ctx: _productRepository.Context, autoCommit: true))
            {
                _downloadService.InsertDownload(clone, download.MediaStorage?.Data);
            }

            return(clone);
        }
        public void CalculateFutureSchedules(IEnumerable <ScheduleTask> tasks, bool isAppStart = false)
        {
            Guard.ArgumentNotNull(() => tasks);

            using (var scope = new DbContextScope(autoCommit: false))
            {
                var now = DateTime.UtcNow;
                foreach (var task in tasks)
                {
                    task.NextRunUtc = GetNextSchedule(task);
                    if (isAppStart)
                    {
                        task.ProgressPercent = null;
                        task.ProgressMessage = null;
                        if (task.LastEndUtc.GetValueOrDefault() < task.LastStartUtc)
                        {
                            task.LastEndUtc = task.LastStartUtc;
                            task.LastError  = T("Admin.System.ScheduleTasks.AbnormalAbort");
                        }
                    }
                    this.UpdateTask(task);
                }

                scope.Commit();
            }
        }
예제 #4
0
        protected virtual async Task CheckOrderStatusAsync(Order order)
        {
            Guard.NotNull(order, nameof(order));

            using var scope = new DbContextScope(_db, deferCommit: true);

            if (order.PaymentStatus == PaymentStatus.Paid && !order.PaidDateUtc.HasValue)
            {
                order.PaidDateUtc = DateTime.UtcNow;
            }

            if (order.OrderStatus == OrderStatus.Pending &&
                (order.PaymentStatus == PaymentStatus.Authorized || order.PaymentStatus == PaymentStatus.Paid))
            {
                await SetOrderStatusAsync(order, OrderStatus.Processing, false);
            }

            if (order.OrderStatus == OrderStatus.Pending &&
                (order.ShippingStatus == ShippingStatus.PartiallyShipped || order.ShippingStatus == ShippingStatus.Shipped || order.ShippingStatus == ShippingStatus.Delivered))
            {
                await SetOrderStatusAsync(order, OrderStatus.Processing, false);
            }

            if (order.OrderStatus != OrderStatus.Cancelled &&
                order.OrderStatus != OrderStatus.Complete &&
                order.PaymentStatus == PaymentStatus.Paid &&
                (order.ShippingStatus == ShippingStatus.ShippingNotRequired || order.ShippingStatus == ShippingStatus.Delivered))
            {
                await SetOrderStatusAsync(order, OrderStatus.Complete, true);
            }

            await scope.CommitAsync();
        }
        private async Task MoveMedia()
        {
            if (_config.StoreMediaInDB)
            {
                return;
            }

            // All pictures have initially been stored in the DB. Move the binaries to disk as configured.
            var fileSystemStorageProvider = EngineContext.Current.ResolveService <Func <IMediaStorageProvider> >().Invoke();

            using (var scope = new DbContextScope(_db, autoDetectChanges: true))
            {
                var mediaFiles = await _db.MediaFiles
                                 .Include(x => x.MediaStorage)
                                 .Where(x => x.MediaStorageId != null)
                                 .ToListAsync();

                foreach (var mediaFile in mediaFiles)
                {
                    if (mediaFile.MediaStorage?.Data?.LongLength > 0)
                    {
                        await fileSystemStorageProvider.SaveAsync(mediaFile, MediaStorageItem.FromStream(mediaFile.MediaStorage.Data.ToStream()));

                        mediaFile.MediaStorageId = null;
                        mediaFile.MediaStorage   = null;
                    }
                }

                await scope.CommitAsync();
            }
        }
        private void MoveMedia()
        {
            if (!_config.StoreMediaInDB)
            {
                // All pictures have initially been stored in the DB. Move the binaries to disk.
                var fileSystemStorageProvider = new FileSystemMediaStorageProvider(new MediaFileSystem());
                var mediaStorages             = _ctx.Set <MediaStorage>();

                using (var scope = new DbContextScope(ctx: _ctx, autoDetectChanges: true, autoCommit: false))
                {
                    var mediaFiles = _ctx.Set <MediaFile>()
                                     .Expand(x => x.MediaStorage)
                                     .Where(x => x.MediaStorageId != null)
                                     .ToList();

                    foreach (var mediaFile in mediaFiles)
                    {
                        if (mediaFile.MediaStorage?.Data?.LongLength > 0)
                        {
                            fileSystemStorageProvider.Save(mediaFile, mediaFile.MediaStorage.Data.ToStream());
                            mediaFile.MediaStorageId = null;
                            mediaFile.MediaStorage   = null;
                        }
                    }

                    scope.Commit();
                }
            }
        }
예제 #7
0
 public void ShouldFailWhenJoiningToDbTransaction()
 {
     using (var dbContextScope = new DbContextScope(DbContextScopeOption.JoinExisting, false, IsolationLevel.ReadUncommitted, null))
     {
         Assert.Fail();
     }
 }
예제 #8
0
        public virtual string ExportResourcesToXml(Language language)
        {
            Guard.NotNull(language, nameof(language));

            var sb           = new StringBuilder();
            var stringWriter = new StringWriter(sb);
            var xmlWriter    = new XmlTextWriter(stringWriter);

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("Language");
            xmlWriter.WriteAttributeString("Name", language.Name);

            using (var scope = new DbContextScope(forceNoTracking: true))
            {
                var resources = All(language.Id).ToList();
                foreach (var resource in resources)
                {
                    if (resource.IsFromPlugin.GetValueOrDefault() == false)
                    {
                        xmlWriter.WriteStartElement("LocaleResource");
                        xmlWriter.WriteAttributeString("Name", resource.ResourceName);
                        xmlWriter.WriteElementString("Value", null, resource.ResourceValue);
                        xmlWriter.WriteEndElement();
                    }
                }
            }

            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndDocument();
            xmlWriter.Close();
            return(stringWriter.ToString());
        }
 public List <Alumno> ListarConQueryPersonalizado()
 {
     using (var ctx = new DbContextScope())
     {
         return(repoAlumno.SqlQuery("SELECT * FROM Alumno")
                .ToList());
     }
 }
 public void ActualizarNombre(Alumno alumno)
 {
     using (var ctx = new DbContextScope())
     {
         repoAlumno.PartialUpdate(alumno, x => x.Nombre, x => x.Apellido);
         ctx.SaveChanges();
     }
 }
예제 #11
0
        public void HasDbContext_WithDbContext_ShouldReturnExpectedResult()
        {
            using var scope = DbContextScope.Create(TestDbContext.Create, AmbientScopeOption.NoNesting);

            var result = this.Accessor.HasDbContext;

            Assert.True(result);
        }
예제 #12
0
 public void SeedDatabase(SmartObjectContext context)
 {
     using (var scope = new DbContextScope(context, hooksEnabled: false))
     {
         Seed(context);
         scope.Commit();
     }
 }
예제 #13
0
 private void ProcessSlug(Product clone)
 {
     using (var scope = new DbContextScope(ctx: _productRepository.Context, autoCommit: true))
     {
         var slug = clone.ValidateSeName("", clone.Name, true, _urlRecordService, _seoSettings);
         _urlRecordService.SaveSlug(clone, slug, 0);
     }
 }
        private void SaveRuleData(RuleEditItem[] ruleData, RuleScope ruleScope)
        {
            var rules = _ruleStorage.GetRulesByIds(ruleData?.Select(x => x.RuleId)?.ToArray(), true);

            if (!rules.Any())
            {
                return;
            }

            using (var scope = new DbContextScope(ctx: Services.DbContext, autoCommit: false))
            {
                var rulesDic = rules.ToDictionarySafe(x => x.Id);
                var provider = _ruleProvider(ruleScope);

                foreach (var data in ruleData)
                {
                    if (rulesDic.TryGetValue(data.RuleId, out var entity))
                    {
                        // TODO? Ugly. There should be a better way. Do not store culture variant values.
                        if (data.Value.HasValue())
                        {
                            var descriptor = provider.RuleDescriptors.FindDescriptor(entity.RuleType);

                            if (descriptor.RuleType == RuleType.Money)
                            {
                                data.Value = data.Value.Convert <decimal>(CultureInfo.CurrentCulture).ToString(CultureInfo.InvariantCulture);
                            }
                            else if (descriptor.RuleType == RuleType.Float || descriptor.RuleType == RuleType.NullableFloat)
                            {
                                data.Value = data.Value.Convert <float>(CultureInfo.CurrentCulture).ToString(CultureInfo.InvariantCulture);
                            }
                            else if (descriptor.RuleType == RuleType.DateTime || descriptor.RuleType == RuleType.NullableDateTime)
                            {
                                data.Value = data.Value.Convert <DateTime>(CultureInfo.CurrentCulture).ToString(CultureInfo.InvariantCulture);
                            }
                        }
                        //if (data.Value?.Contains(',') ?? false)
                        //{
                        //    var provider = _ruleProvider(ruleScope);
                        //    var descriptor = provider.RuleDescriptors.FindDescriptor(entity.RuleType);
                        //    var floatingPointTypes = new Type[] { typeof(decimal), typeof(decimal?), typeof(float), typeof(float?), typeof(double), typeof(double?) };

                        //    if (floatingPointTypes.Contains(descriptor.RuleType.ClrType))
                        //    {
                        //        data.Value = data.Value.Replace(",", ".");
                        //    }
                        //}

                        entity.Operator = data.Op;
                        entity.Value    = data.Value;

                        _ruleStorage.UpdateRule(entity);
                    }
                }

                scope.Commit();
            }
        }
예제 #15
0
        public void CurrentDbContext_WithDbContext_ShouldReturnExpectedResult()
        {
            using var scope = DbContextScope.Create(TestDbContext.Create, AmbientScopeOption.NoNesting);

            var result = this.Accessor.CurrentDbContext;

            Assert.NotNull(result);
            Assert.Equal(scope.DbContext, result);
        }
 public List <Pais> Listar()
 {
     using (var ctx = new DbContextScope())
     {
         return(repoPais.GetAll()
                .OrderBy(x => x.Nombre)
                .ToList());
     }
 }
예제 #17
0
        /// <summary>
        /// Install permissions
        /// </summary>
        /// <param name="permissionProvider">Permission provider</param>
        public virtual void InstallPermissions(IPermissionProvider permissionProvider)
        {
            using (var scope = new DbContextScope(_permissionRecordRepository.Context, autoDetectChanges: false, autoCommit: false))
            {
                //install new permissions
                var permissions = permissionProvider.GetPermissions();
                foreach (var permission in permissions)
                {
                    var permission1 = GetPermissionRecordBySystemName(permission.SystemName);
                    if (permission1 == null)
                    {
                        //new permission (install it)
                        permission1 = new PermissionRecord()
                        {
                            Name       = permission.Name,
                            SystemName = permission.SystemName,
                            Category   = permission.Category,
                        };

                        // default customer role mappings
                        var defaultPermissions = permissionProvider.GetDefaultPermissions();
                        foreach (var defaultPermission in defaultPermissions)
                        {
                            var customerRole = _customerService.GetCustomerRoleBySystemName(defaultPermission.CustomerRoleSystemName);
                            if (customerRole == null)
                            {
                                //new role (save it)
                                customerRole = new CustomerRole
                                {
                                    Name       = defaultPermission.CustomerRoleSystemName,
                                    Active     = true,
                                    SystemName = defaultPermission.CustomerRoleSystemName
                                };
                                _customerService.InsertCustomerRole(customerRole);
                            }


                            var defaultMappingProvided = (from p in defaultPermission.PermissionRecords
                                                          where p.SystemName == permission1.SystemName
                                                          select p).Any();
                            var mappingExists = (from p in customerRole.PermissionRecords
                                                 where p.SystemName == permission1.SystemName
                                                 select p).Any();
                            if (defaultMappingProvided && !mappingExists)
                            {
                                permission1.CustomerRoles.Add(customerRole);
                            }
                        }

                        //save new permission
                        InsertPermissionRecord(permission1);
                    }
                }

                scope.Commit();
            }
        }
        public override void Hook(ISoftDeletable entity, HookEntityMetadata metadata)
        {
            var baseEntity = entity as BaseEntity;

            if (baseEntity == null)
            {
                return;
            }

            var dbContext     = _ctx.Resolve <IDbContext>();
            var modifiedProps = dbContext.GetModifiedProperties(baseEntity);

            if (!modifiedProps.ContainsKey("Deleted"))
            {
                return;
            }

            var entityType = baseEntity.GetUnproxiedType();

            using (var scope = new DbContextScope(ctx: dbContext, autoCommit: false))
            {
                // mark orphaned ACL records as idle
                var aclSupported = baseEntity as IAclSupported;
                if (aclSupported != null && aclSupported.SubjectToAcl)
                {
                    var shouldSetIdle = entity.Deleted;
                    var rsAclRecord   = _ctx.Resolve <IRepository <AclRecord> >();

                    var aclService = _ctx.Resolve <IAclService>();
                    var records    = aclService.GetAclRecordsFor(entityType.Name, baseEntity.Id);
                    foreach (var record in records)
                    {
                        record.IsIdle = shouldSetIdle;
                        aclService.UpdateAclRecord(record);
                    }
                }

                // Delete orphaned inactive UrlRecords.
                // We keep the active ones on purpose in order to be able to fully restore a soft deletable entity once we implemented the "recycle bin" feature
                var slugSupported = baseEntity as ISlugSupported;
                if (slugSupported != null && entity.Deleted)
                {
                    var rsUrlRecord = _ctx.Resolve <IRepository <UrlRecord> >();

                    var urlRecordService = _ctx.Resolve <IUrlRecordService>();
                    var activeRecords    = urlRecordService.GetUrlRecordsFor(entityType.Name, baseEntity.Id);
                    foreach (var record in activeRecords)
                    {
                        if (!record.IsActive)
                        {
                            urlRecordService.DeleteUrlRecord(record);
                        }
                    }
                }
            }
        }
예제 #19
0
 public void ShouldFailWhenNestingReadWriteScopeInReadOnlyScope()
 {
     using (var dbReadOnlyContextScope = new DbContextScope(true, null))
     {
         using (var dbReadWriteContextScope = new DbContextScope(null))
         {
             Assert.Fail();
         }
     }
 }
예제 #20
0
        public void AddUsingAmbientDbContextScope(Company comp, User user)
        {
            using (var scope = new DbContextScope(DbContextScopePurpose.Writing))
            {
                this.repoComp.Insert(comp);
                user.Company = comp;
                this.repoUser.Insert(user);

                scope.SaveChanges();
            }
        }
예제 #21
0
        private void ProcessLocalization(Product product, Product clone, IEnumerable <Language> languages)
        {
            using (var scope = new DbContextScope(ctx: _productRepository.Context, autoCommit: true))
            {
                foreach (var lang in languages)
                {
                    var name = product.GetLocalized(x => x.Name, lang, false, false);
                    if (!String.IsNullOrEmpty(name))
                    {
                        _localizedEntityService.SaveLocalizedValue(clone, x => x.Name, name, lang.Id);
                    }

                    var shortDescription = product.GetLocalized(x => x.ShortDescription, lang, false, false);
                    if (!String.IsNullOrEmpty(shortDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(clone, x => x.ShortDescription, shortDescription, lang.Id);
                    }

                    var fullDescription = product.GetLocalized(x => x.FullDescription, lang, false, false);
                    if (!String.IsNullOrEmpty(fullDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(clone, x => x.FullDescription, fullDescription, lang.Id);
                    }

                    var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang, false, false);
                    if (!String.IsNullOrEmpty(metaKeywords))
                    {
                        _localizedEntityService.SaveLocalizedValue(clone, x => x.MetaKeywords, metaKeywords, lang.Id);
                    }

                    var metaDescription = product.GetLocalized(x => x.MetaDescription, lang, false, false);
                    if (!String.IsNullOrEmpty(metaDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(clone, x => x.MetaDescription, metaDescription, lang.Id);
                    }

                    var metaTitle = product.GetLocalized(x => x.MetaTitle, lang, false, false);
                    if (!String.IsNullOrEmpty(metaTitle))
                    {
                        _localizedEntityService.SaveLocalizedValue(clone, x => x.MetaTitle, metaTitle, lang.Id);
                    }

                    var bundleTitleText = product.GetLocalized(x => x.BundleTitleText, lang, false, false);
                    if (!String.IsNullOrEmpty(bundleTitleText))
                    {
                        _localizedEntityService.SaveLocalizedValue(clone, x => x.BundleTitleText, bundleTitleText, lang.Id);
                    }

                    // Search engine name.
                    var slug = clone.ValidateSeName("", name, false, _urlRecordService, _seoSettings, lang.Id);
                    _urlRecordService.SaveSlug(clone, slug, lang.Id);
                }
            }
        }
예제 #22
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);
                }
            }
        }
 public Alumno Obtener(int id)
 {
     using (var ctx = new DbContextScope())
     {
         return(repoAlumno.Get(
                    x => x.id == id,
                    x => x.AlumnoCurso.Select(ac => ac.Curso),
                    x => x.Pais
                    ));
     }
 }
    public TDbContext Get <TDbContext>() where TDbContext : DbContext
    {
        var ambientDbContextScope = DbContextScope.GetAmbientScope();

        if (ambientDbContextScope == null)
        {
            throw new InvalidOperationException(
                      "No ambient DbContext scope found. The method has been called outside of the DbContextScope.");
        }

        return(ambientDbContextScope.DbContexts.Get <TDbContext>());
    }
예제 #25
0
        public void Remove(params MediaFile[] mediaFiles)
        {
            using (var scope = new DbContextScope(ctx: _mediaFileRepo.Context, autoCommit: false))
            {
                foreach (var media in mediaFiles)
                {
                    media.ApplyBlob(null);
                }

                scope.Commit();
            }
        }
예제 #26
0
        public void Migrate(IEnumerable <SettingEntry> entries)
        {
            Guard.ArgumentNotNull(() => entries);

            if (!entries.Any())
            {
                return;
            }

            using (var scope = new DbContextScope(_ctx, autoDetectChanges: false))
            {
                var toDelete = new List <Setting>();
                var toAdd    = new List <Setting>();

                // First perform DELETE actions
                foreach (var entry in entries.Where(x => x.Value == null))
                {
                    bool isPattern = entry.KeyIsGroup;
                    if (!HasSettings(entry.Key, isPattern))
                    {
                        continue; // nothing to delete
                    }
                    var db = GetSettings(entry.Key, isPattern);
                    _settings.RemoveRange(db);
                }

                _ctx.SaveChanges();

                // Then perform ADD actions
                foreach (var entry in entries.Where(x => x.Value.HasValue()))
                {
                    var existing = toAdd.FirstOrDefault(x => x.Name.Equals(entry.Key, StringComparison.InvariantCultureIgnoreCase));
                    if (existing != null)
                    {
                        existing.Value = entry.Value;
                        continue;
                    }

                    if (HasSettings(entry.Key, false))
                    {
                        continue; // skip existing (we don't perform updates)
                    }
                    _settings.Add(new Setting
                    {
                        Name  = entry.Key,
                        Value = entry.Value,
                        Id    = 0
                    });
                }

                _ctx.SaveChanges();
            }
        }
예제 #27
0
        public async Task MigrateAsync(IEnumerable <SettingEntry> entries)
        {
            Guard.NotNull(entries, nameof(entries));

            if (!entries.Any())
            {
                return;
            }

            var toDelete = new List <Setting>();
            var toAdd    = new List <Setting>();

            using var scope = new DbContextScope(_db, autoDetectChanges: false, minHookImportance: HookImportance.Essential);

            // First perform DELETE actions
            foreach (var entry in entries.Where(x => x.Value == null))
            {
                bool isPattern = entry.KeyIsGroup;
                if (!await HasSettingsAsync(entry.Key, isPattern))
                {
                    continue; // nothing to delete
                }
                var dbSettings = await GetSettingsAsync(entry.Key, isPattern);

                _settings.RemoveRange(dbSettings);
            }

            await _db.SaveChangesAsync();

            // Then perform ADD actions
            foreach (var entry in entries.Where(x => x.Value.HasValue()))
            {
                var existing = toAdd.FirstOrDefault(x => x.Name.Equals(entry.Key, StringComparison.InvariantCultureIgnoreCase));
                if (existing != null)
                {
                    existing.Value = entry.Value;
                    continue;
                }

                if (await HasSettingsAsync(entry.Key, false))
                {
                    continue; // skip existing (we don't perform updates)
                }
                _settings.Add(new Setting
                {
                    Name    = entry.Key,
                    Value   = entry.Value,
                    StoreId = 0
                });
            }

            await _db.SaveChangesAsync();
        }
        public ResponseModel Eliminar(int id)
        {
            using (var ctx = new DbContextScope())
            {
                repoAlumno.PartialUpdate(new Alumno {
                    id = id, Eliminado = true
                }, x => x.Eliminado);
                ctx.SaveChanges();

                rm.SetResponse(true);
                return(rm);
            }
        }
예제 #29
0
        public void Seed(SmartObjectContext context)
        {
            using (var scope = new DbContextScope(ctx: context, validateOnSave: false, hooksEnabled: false))
            {
                var gdprAdminEmail = context.Set <MessageTemplate>().Where(x => x.Name.Equals("Admin.AnonymizeRequest")).FirstOrDefault();
                if (gdprAdminEmail != null && gdprAdminEmail.To.Equals("{{ Customer.FullName }} &lt;{{ Customer.Email }}&gt;"))
                {
                    gdprAdminEmail.To = "{{ Email.DisplayName }} &lt;{{ Email.Email }}&gt;";
                }

                context.SaveChanges();
            }
        }
        public void Dispose()
        {
            if (_disposed)
                return;

            if (_savedScope != null)
            {
                DbContextScope.SetAmbientScope(_savedScope);
                _savedScope = null;
            }

            _disposed = true;
        }
예제 #31
0
        private async Task ProcessBundleItems(DbContextScope scope, Product product, Product clone, IEnumerable <Language> languages)
        {
            var localizedKeySelectors = new List <Expression <Func <ProductBundleItem, string> > >
            {
                x => x.Name,
                x => x.ShortDescription
            };

            var bundledItems = await _db.ProductBundleItem
                               .AsNoTracking()
                               .Include(x => x.AttributeFilters)
                               .ApplyBundledProductsFilter(new[] { product.Id }, true)
                               .ToListAsync();

            if (!bundledItems.Any())
            {
                return;
            }

            var itemMap = new Dictionary <int, ProductBundleItem>();

            foreach (var bundledItem in bundledItems)
            {
                var newBundleItem = bundledItem.Clone();
                newBundleItem.BundleProductId = clone.Id;
                itemMap[bundledItem.Id]       = newBundleItem;
            }

            _db.ProductBundleItem.AddRange(itemMap.Select(x => x.Value).Reverse());
            await scope.CommitAsync();

            foreach (var bundledItem in bundledItems)
            {
                if (!itemMap.TryGetValue(bundledItem.Id, out var newBundleItem))
                {
                    continue;
                }

                foreach (var itemFilter in bundledItem.AttributeFilters)
                {
                    var newItemFilter = itemFilter.Clone();
                    newItemFilter.BundleItemId = newBundleItem.Id;

                    _db.ProductBundleItemAttributeFilter.Add(newItemFilter);
                }

                await ProcessLocalizations(bundledItem, newBundleItem, localizedKeySelectors, languages);
            }

            await scope.CommitAsync();
        }
예제 #32
0
        public override TResult ExecuteAsync <TResult>(Expression expression, CancellationToken cancellationToken = default)
        {
            var cachingResult = ReadFromCache <TResult>(expression);

            if (cachingResult.HasResult)
            {
                return(cachingResult.WrapAsyncResult(cachingResult.CacheEntry.Value));
            }

            var result = base.ExecuteAsync <TResult>(cachingResult.Expression, cancellationToken);

            if (!cachingResult.CanPut || cancellationToken.IsCancellationRequested)
            {
                return(result);
            }

            using (var scope = new DbContextScope((HookingDbContext)_currentContext.Context, lazyLoading: false))
            {
                var cacheValue = cachingResult.ConvertQueryAsyncResult(result).Await();

                if (cacheValue.Count <= cachingResult.Policy.MaxRows.Value)
                {
                    var entry = new DbCacheEntry
                    {
                        Key       = cachingResult.CacheKey,
                        Value     = cacheValue.Value,
                        ValueType = cacheValue.Value?.GetType()
                    };

                    _cache.Put(cachingResult.CacheKey, entry, cachingResult.Policy);

                    Log(DbCachingEventId.QueryResultCached,
                        "Has put query result to cache. Key: {0}, Type: {1}, Policy: {2}.",
                        cachingResult.CacheKey.Key,
                        typeof(TResult),
                        cachingResult.Policy);
                }
                else
                {
                    Log(DbCachingEventId.MaxRowsExceeded,
                        "Max rows limit exceeded. Will not cache. Actual: {0}, Limit: {1} Key: {2}, Type: {3}.",
                        cacheValue.Count,
                        cachingResult.Policy.MaxRows.Value,
                        cachingResult.CacheKey.Key,
                        typeof(TResult));
                }

                return(cachingResult.WrapAsyncResult(cacheValue.Value));
            }
        }
예제 #33
0
        public void DeleteCampaign(int campaign_id, int company_id)
        {
            this.CheckIsEqualCompany(company_id, campaign_id);
            using (var scope = new DbContextScope(DbContextScopePurpose.Writing))
            {
                var campaign = this.GetCampaignById(campaign_id, company_id);
                campaign.CampaignTag.ToList().ForEach(q =>
                {
                    this.RepoCampaignTagInfo.DeleteByID(q.CampaignTagID);
                });

                campaign.CampaignChannel.ToList()
                    .ForEach(q =>
                    {
                        this.RepoCampaignChannelMapping.DeleteByID(q.ID);
                    });

                this.RepoSMS.Find().Where(q => q.CampaignID == campaign_id).ToList()
                    .ForEach(sms => this.RepoSMS.Delete(sms));

                this.RepoCampaignKeywordSetting.Find().Where(q => q.CampaignId == campaign_id).ToList()
                    .ForEach(keywordSetting =>
                    {
                        keywordSetting.CampaignKeywordReplaces.ToList().ForEach(keywordReplace =>
                        {
                            this.RepoCampaignKeywordReplace.Delete(keywordReplace);
                        });
                        this.RepoCampaignKeywordSetting.Delete(keywordSetting);
                    });

                this.RepoTaExportInfo.Find().Where(q => q.CampaignID == campaign_id).ToList()
                    .ForEach(taExportInfo => this.RepoTaExportInfo.Delete(taExportInfo));

                this.RepoSystemJobInfo.Find().Where(q => q.CampaignID == campaign_id).ToList()
                    .ForEach(systemJobInfo => this.RepoSystemJobInfo.Delete(systemJobInfo));

                this.RepoCampaign.DeleteByID(campaign_id);

                scope.SaveChanges();
            }
        }
예제 #34
0
        public Model.EF.Campaign GetCampaignById(int campaign_id, int company_id)
        {
            using (var scope = new DbContextScope(DbContextScopePurpose.Reading))
            {
                var query = this.RepoCampaign.Find();
                query = query.AsQueryable().Include(q => q.CampaignTag.Select(w => w.TagInfo)).Include(c => c.CampaignChannel.Select(q => q.ChannelInfo)).Include(c => c.AccountCompany);
                var result = query.FirstOrDefault(q => q.CampaignID == campaign_id && q.AcctCompanyID == company_id);

                if (result != null)
                {
                    var langKeyList = this.RepoLangKey.Find().Where(q => q.Local == "zh-TW").ToList();
                    result.CampaignChannel.ToList().ForEach(channel =>
                    {
                        var lang = langKeyList.FirstOrDefault(q => q.Key == channel.ChannelInfo.LanguageKey);
                        if (lang != null)
                        {
                            channel.ChannelInfo.LanguageKey = lang.Word;
                        }
                    });
                }

                return result;
            }
        }
예제 #35
0
 public void GetCampaignDateRange(int accompanyId, out DateTime minDate, out DateTime maxDate)
 {
     using (var scope = new DbContextScope(DbContextScopePurpose.Reading))
     {
         var query = this.RepoCampaign.Find();
         minDate = query.Min(q => q.DateStart);
         maxDate = query.Max(q => q.DateEnd);
     }
 }
예제 #36
0
        // clcondition = CampaignList Condition
        public List<Model.EF.Campaign> GetCampaignList(CampaignList condition, out int total, int company_id)
        {
            using (var scope = new DbContextScope(DbContextScopePurpose.Reading))
            {
                var query = this.RepoCampaign.Find().Where(q => q.AcctCompanyID == company_id);
                query = query.AsQueryable().Include(q => q.CampaignTag.Select(w => w.TagInfo)).Include(q => q.CampaignType)
                    .OrderByDescending(q => q.CampaignID);

                if (condition.TypeID.HasValue)
                {
                    query = query.Where(q => q.TypeID == condition.TypeID.Value);
                }

                if (!string.IsNullOrEmpty(condition.Sort))
                {
                    query = query.AsQueryable().Sort(condition.Sort);
                }

                if (condition.DateStart.HasValue)
                {
                    query = query.Where(q => q.DateStart >= condition.DateStart.Value);
                }

                if (condition.DateEnd.HasValue)
                {
                    query = query.Where(q => q.DateStart <= condition.DateEnd);
                }

                if (!string.IsNullOrEmpty(condition.Keyword))
                {
                    query = query.Where(q => q.Name.ToUpper().Contains(condition.Keyword.ToUpper())
                        || q.CampaignTag.Any(w => w.TagInfo.TagName.ToUpper().Contains(condition.Keyword.ToUpper())));
                }

                if (condition.StatusID.HasValue)
                {
                    query = query.Where(q => q.CampStatus == condition.StatusID);
                }

                if (!string.IsNullOrEmpty(condition.Sort))
                {
                    bool isAsc = condition.Sort.StartsWith("+");

                    switch (condition.Sort.ToLower().Replace("+", string.Empty).Replace("-", string.Empty))
                    {
                        case "camp_status_id":
                            if (isAsc)
                            {
                                query = query.OrderBy(q => q.CampStatus);
                            }
                            else
                            {
                                query = query.OrderByDescending(q => q.CampStatus);
                            }

                            break;
                        case "campaign_id":
                            if (isAsc)
                            {
                                query = query.OrderBy(q => q.CampaignID);
                            }
                            else
                            {
                                query = query.OrderByDescending(q => q.CampaignID);
                            }

                            break;
                        case "date_end":
                            if (isAsc)
                            {
                                query = query.OrderBy(q => q.DateEnd);
                            }
                            else
                            {
                                query = query.OrderByDescending(q => q.DateEnd);
                            }

                            break;
                        case "date_start":
                            if (isAsc)
                            {
                                query = query.OrderBy(q => q.DateStart);
                            }
                            else
                            {
                                query = query.OrderByDescending(q => q.DateStart);
                            }

                            break;
                        case "name":
                            if (isAsc)
                            {
                                query = query.OrderBy(q => q.Name);
                            }
                            else
                            {
                                query = query.OrderByDescending(q => q.Name);
                            }

                            break;
                        case "type_id":
                            if (isAsc)
                            {
                                query = query.OrderBy(q => q.TypeID);
                            }
                            else
                            {
                                query = query.OrderByDescending(q => q.TypeID);
                            }

                            break;
                    }
                }

                if (!condition.Limit.HasValue)
                {
                    condition.Limit = 10;
                }

                if (!condition.Offset.HasValue)
                {
                    condition.Offset = 0;
                }

                query = query.AsQueryable().Paged(condition.Offset.Value, condition.Limit.Value, out total);

                var result = query.ToList();

                //// 如果沒有做以下的Code的話會沒辦法找到TagInfo 會Disposed掉,導致無法

                var langKeyList = this.RepoLangKey.Find().Where(q => q.Local == "zh-TW").ToList();
                result.ForEach(campaign =>
                {
                    campaign.CampaignType = campaign.CampaignType;
                    var lang = langKeyList.FirstOrDefault(q => q.Key == campaign.CampaignType.LanguageKey);
                    if (lang != null)
                    {
                        campaign.CampaignType.LanguageKey = lang.Word;
                    }

                    campaign.CampaignTag.ToList().ForEach(campaignTag => campaignTag.TagInfo = campaignTag.TagInfo);
                });
                return result;
            }
        }
예제 #37
0
 public void UpdateCampaign(Model.EF.Campaign campaign, int company_id)
 {
     this.CheckIsEqualCompany(company_id, campaign.CampaignID);
     using (var scope = new DbContextScope(DbContextScopePurpose.Writing))
     {
         campaign.DateModified = DateTime.Now;
         this.RepoCampaign.Update(campaign);
         scope.SaveChanges();
     }
 }
예제 #38
0
        public int AddCampaign(Model.EF.Campaign campaign, AccountUser user)
        {
            //Updated by Action_Chen 20150805
            //EventHandling & Logger框架程式範例
            var baseLogger = new _BaseLogger();

            //Updated by Action_Chen 20150805
            //EventHandling & Logger框架程式範例
            try
            {
                using (var scope = new DbContextScope(DbContextScopePurpose.Writing))
                {
                    campaign.DateCreated = DateTime.Now;
                    campaign.DateModified = campaign.DateCreated;
                    this.RepoCampaign.Insert(campaign);
                    scope.SaveChanges();
                }

            }

            //Updated by Action_Chen 20150805
            //EventHandling & Logger框架程式範例

            //catch (DbUpdateException ex)
            catch (Exception ex)
            {
                //throw new MigoDbUpdateException();
                throw new MigoCommitFailedException(user);
            }

            return campaign.CampaignID;
        }
예제 #39
0
 private void DeleteCampaignTagMapping(int id)
 {
     using (var scope = new DbContextScope(DbContextScopePurpose.Writing))
     {
         this.RepoCampaignTagInfo.DeleteByID(id);
         scope.SaveChanges();
     }
 }
예제 #40
0
 private void CheckIsEqualCompany(int company_id, int campaign_id)
 {
     using (var scope = new DbContextScope(DbContextScopePurpose.Reading))
     {
         if (!this.RepoCampaign.Find().Any(q => q.AcctCompanyID == company_id && q.CampaignID == campaign_id))
         {
             throw new Exception("Not Found");
         }
     }
 }