Example #1
0
        private void RegisterGenericRepositories()
        {
            var dbContextTypes =
                _typeFinder.Find(type =>
                                 type.IsPublic &&
                                 !type.IsAbstract &&
                                 type.IsClass &&
                                 typeof(AbpDbContext).IsAssignableFrom(type)
                                 );

            if (dbContextTypes.IsNullOrEmpty())
            {
                return;
            }

            foreach (var item in dbContextTypes)
            {
                EntityFrameworkGenericBatchRepositoryRegistrar.RegisterForDbContext(item, IocManager);

                //var type = typeof(IAbpBatchRunner<>).MakeGenericType(item);
                //var implType = typeof(AbpSqlServerBatchRunner<>).MakeGenericType(item);
                //IocManager.RegisterIfNot(type, implType, DependencyLifeStyle.Transient);
            }
        }
        private void RegisterGenericRepositoriesAndMatchDbContexes()
        {
            var dbContextTypes =
                _typeFinder.Find(type =>
                                 type.IsPublic &&
                                 !type.IsAbstract &&
                                 type.IsClass &&
                                 typeof(CodeZeroDbContext).IsAssignableFrom(type)
                                 );

            if (dbContextTypes.IsNullOrEmpty())
            {
                Logger.Warn("No class found derived from CodeZeroDbContext.");
                return;
            }

            using (var scope = IocManager.CreateScope())
            {
                var repositoryRegistrar = scope.Resolve <IEfGenericRepositoryRegistrar>();

                foreach (var dbContextType in dbContextTypes)
                {
                    Logger.Debug("Registering DbContext: " + dbContextType.AssemblyQualifiedName);
                    repositoryRegistrar.RegisterForDbContext(dbContextType, IocManager, EfAutoRepositoryTypes.Default);

                    IocManager.IocContainer.Register(
                        Component.For <ISecondaryOrmRegistrar>()
                        .Named(Guid.NewGuid().ToString("N"))
                        .Instance(new EfBasedSecondaryOrmRegistrar(dbContextType, scope.Resolve <IDbContextEntityFinder>()))
                        .LifestyleTransient()
                        );
                }

                scope.Resolve <IDbContextTypeMatcher>().Populate(dbContextTypes);
            }
        }
Example #3
0
        public virtual EntityChange CreateEntityChange(object entity)
        {
            if (!IsEntityHistoryEnabled)
            {
                return(null);
            }
            if (IsChangesEntity(entity))
            {
                return(null);
            }

            var typeOfEntity = entity.GetType();

            if (typeOfEntity.HasInterface(typeof(INHibernateProxy)) ||
                typeOfEntity.HasInterface(typeof(IFieldInterceptorAccessor)))
            {
                if (typeOfEntity.BaseType == null)
                {
                    throw new Exception($"Base type of proxy `{typeOfEntity.Name}`, object `{entity}`");
                }
                // unproxy
                typeOfEntity = typeOfEntity.BaseType;
            }

            if (!IsTypeOfEntity(typeOfEntity))
            {
                return(null);
            }

            var isTracked = IsTypeOfTrackedEntity(typeOfEntity);

            if (isTracked != null && !isTracked.Value)
            {
                return(null);
            }

            var isAudited = IsTypeOfAuditedEntity(typeOfEntity);

            if (isAudited != null && !isAudited.Value)
            {
                return(null);
            }

            if (isAudited == null && isTracked == null)
            {
                if (!typeOfEntity.GetProperties()
                    .Any(p =>
                         (IsAuditedPropertyInfo(p) ?? false) ||
                         (IsAditedBooleanPropertyInfo(p) ?? false) ||
                         (IsAditedAsEventPropertyInfo(p) ?? false)))
                {
                    return(null);
                }
            }

            var         entityTypeFullName = typeOfEntity.FullName;
            EntityEntry entityEntry;

            if ((entityEntry = Session?.GetEntry(entity, false)) == null)
            {
                return(null);
            }
            var id = entityEntry.Id;

            EntityChangeType changeType;

            if (Session.IsEntityDeleted(entity))
            {
                changeType = EntityChangeType.Deleted;
            }
            else if (entityEntry.LoadedState == null)
            {
                changeType = EntityChangeType.Created;
            }
            else
            {
                changeType = EntityChangeType.Updated;
            }

            var className   = NHibernateProxyHelper.GuessClass(entity).FullName;
            var sessionImpl = Session.GetSessionImplementation();
            var persister   = sessionImpl.Factory.GetEntityPersister(className);

            Object[] currentState = persister.GetPropertyValues(entity);
            Int32[]  dirtyP       = changeType != EntityChangeType.Created && entityEntry.LoadedState != null
                ? persister.FindDirty(currentState, entityEntry.LoadedState, entity, sessionImpl) // changed properties
                : Enumerable.Range(0, currentState.Length - 1).ToArray();                         // all properties for new entity

            var ioc          = StaticContext.IocManager;
            var creatorTypes = _typeFinder.Find(t => typeof(IEntityHistoryCreator).IsAssignableFrom(t) && t.IsClass).ToList();

            foreach (var creatorType in creatorTypes)
            {
                if (ioc.Resolve(creatorType) is IEntityHistoryCreator creator && creator.TypeAllowed(entity.GetType()))
                {
                    return(creator.GetEntityChange(entity, AbpSession, persister.PropertyNames, entityEntry.LoadedState, currentState, dirtyP));
                }
            }

            var dirtyProps = dirtyP.Select(i => new SessionExtensions.DirtyPropertyInfo
            {
                Name = persister.PropertyNames[i], OldValue = entityEntry.LoadedState?[i], NewValue = currentState[i]
            })
                             .ToList();

            var entityChange = new EntityChange
            {
                ChangeType         = changeType,
                ChangeTime         = Clock.Now,
                EntityEntry        = entity, // [NotMapped]
                EntityId           = id?.ToString(),
                EntityTypeFullName = entityTypeFullName,
                TenantId           = AbpSession.TenantId,
            };

            var propertyChanges = new List <EntityPropertyChange>();

            if (changeType != EntityChangeType.Created)
            {
                propertyChanges.AddRange(GetPropertyChanges((isAudited ?? false) || (isTracked ?? false), entityChange,
                                                            typeOfEntity, entity, dirtyProps));
                if (propertyChanges.Count == 0 && //changeType != EntityChangeType.Created &&
                    EntityHistoryEvents.All(x => x.EntityChange != entityChange))
                {
                    return(null);
                }
            }
            entityChange.PropertyChanges = propertyChanges;

            return(entityChange);
        }
 public ICollection <Type> FindAll()
 {
     return(_typeFinder.Find(AbpModule.IsAbpModule).ToList());
 }
Example #5
0
 private bool HasImpl(Type interfaceType)
 {
     return(_typeFinder.Find(t => interfaceType.IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract).Any());
 }
 /// <summary>
 /// 获取类型集合
 /// </summary>
 /// <typeparam name="T">对象类型</typeparam>
 /// <returns></returns>
 private Type[] GetTypes <T>()
 {
     return(_finder.Find <T>(_assemblies).ToArray());
 }
		private static IList<ControlsAttribute> FindControllers(ITypeFinder typeFinder)
		{
			var controllerLookup = new Dictionary<Type, ControlsAttribute>();
			foreach (Type controllerType in typeFinder.Find(typeof(IController)))
			{
				foreach (ControlsAttribute attr in controllerType.GetCustomAttributes(typeof(ControlsAttribute), false))
				{
					if (controllerLookup.ContainsKey(attr.ItemType))
						throw new N2Exception("Duplicate controller " + controllerType.Name + " declared for item type " +
						                      attr.ItemType.Name +
											  " The controller " + controllerLookup[attr.ItemType].AdapterType.Name +
											  " already handles this type and two controllers cannot handle the same item type.");

					attr.AdapterType = controllerType;
					controllerLookup.Add(attr.ItemType, attr);
				}
			}

			var controllerDefinitions = new List<ControlsAttribute>(controllerLookup.Values);
			controllerDefinitions.Sort();

			return controllerDefinitions;
		}
Example #8
0
 private static IList<ControlsAttribute> FindControllers(ITypeFinder typeFinder)
 {
     var controllerDefinitions = new List<ControlsAttribute>();
     foreach (Type controllerType in typeFinder.Find(typeof(IController)))
     {
         foreach (ControlsAttribute attr in controllerType.GetCustomAttributes(typeof(ControlsAttribute), false))
         {
             attr.AdapterType = controllerType;
             controllerDefinitions.Add(attr);
         }
     }
     controllerDefinitions.Sort();
     return controllerDefinitions;
 }
Example #9
0
        public void PushNewPage(string xaml)
        {
            var tcs = new TaskCompletionSource <bool>();

            Device.BeginInvokeOnMainThread(async() =>
            {
                try
                {
                    Page page;

                    var discovery  = new XamlDocumentDiscovery(xaml);
                    var xClassName = discovery.GetPageClassName();

                    if (string.IsNullOrWhiteSpace(xClassName))
                    {
                        page       = new ContentPage();
                        var loaded = _xamlLoader.Load(page, xaml, ShowError);
                        if (loaded == null)
                        {
                            return;
                        }
                    }
                    else
                    {
                        var type = _typeFinder.Find(xClassName);
                        if (type == null)
                        {
                            ShowError($"The type {xClassName} was not found. Try loading the project assemblies, first.");
                            return;
                        }

                        try
                        {
                            page = Activator.CreateInstance(type) as Page;
                        }
                        catch (Exception e)
                        {
                            ShowError(e);
                            return;
                        }
                    }

                    await Navigation.PopAsync(false);
                    await Navigation.PushAsync(page, false);

                    App.CurrentDesignSurface = page;
                    SetPageId(page);

                    DesignerAppEvents.SetupDesignSurface(page);
                }
                catch (Exception)
                {
                    ShowError();
                }
                finally
                {
                    tcs.SetResult(true);
                }
            });

            tcs.Task.Wait();
        }
        private async Task DoProcess()
        {
            var jobs = _typeFinder
                       .Find(type => type != null && type.IsPublic && type.HasAttribute <ScheduledJobAttribute>())
                       .Select(e => new
            {
                Class     = e,
                Attribute = e.GetAttribute <ScheduledJobAttribute>()
            })
                       .ToList();

            // deactivate all jobs which are missing in the code
            var dbItems = await _jobRepo.GetAll().ToListAsync();

            var toDelete = dbItems.Where(i => !jobs.Any(j => j.Attribute.Uid == i.Id)).ToList();

            foreach (var scheduledJob in toDelete)
            {
                await _jobRepo.DeleteAsync(scheduledJob);
            }

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

            foreach (var jobInfo in jobs)
            {
                try
                {
                    using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
                    {
                        var existingJob = await _jobRepo.GetAll().FirstOrDefaultAsync(j => j.Id == jobInfo.Attribute.Uid);

                        // job already exists - activate  if inactive it and continue processing
                        // note: the user can't create/delete jobs manually, so we assume that the job was inactivated by this bootstrapper
                        if (existingJob != null)
                        {
                            if (existingJob.IsDeleted)
                            {
                                existingJob.IsDeleted     = false;
                                existingJob.DeletionTime  = null;
                                existingJob.DeleterUserId = null;
                                await _jobRepo.UpdateAsync(existingJob);
                            }

                            continue;
                        }
                    }

                    // create job and default trigger only if the job is missing in the DB
                    var job = new ScheduledJob()
                    {
                        Id             = jobInfo.Attribute.Uid,
                        JobName        = jobInfo.Class.Name,
                        JobNamespace   = jobInfo.Class.Namespace,
                        StartupMode    = jobInfo.Attribute.StartupMode,
                        JobStatus      = JobStatus.Active,
                        JobDescription = jobInfo.Attribute.Description
                    };

                    await _jobRepo.InsertAsync(job);

                    // create a trigger
                    if (jobInfo.Attribute.StartupMode == StartUpMode.Automatic &&
                        CronStringHelper.IsValidCronExpression(jobInfo.Attribute.CronString ?? string.Empty))
                    {
                        var trigger = new ScheduledJobTrigger()
                        {
                            Job         = job,
                            Description = "Default trigger (created automatically)",
                            CronString  = jobInfo.Attribute.CronString
                        };

                        await _triggerRepo.InsertAsync(trigger);
                    }

                    await _unitOfWorkManager.Current.SaveChangesAsync();
                }
                catch (Exception e)
                {
                    throw new Exception($"An error occured during bootstrapping of the scheduled job {jobInfo.Attribute.Uid}", e);
                }
            }

            // sync to Hangfire
            await _jobManager.EnqueueAllAsync();
        }
Example #11
0
 public ICollection <Type> FindAll()
 {
     return(typeFinder.Find(NsModule.IsNsModule).ToList());
 }
Example #12
0
        /// <summary>
        /// Seed database (applies migrations, runs bootstrappers/seeders)
        /// </summary>
        private void SeedDatabase()
        {
            var ioc = StaticContext.IocManager;

            var lockFactory  = ioc.Resolve <ILockFactory>();
            var cacheManager = ioc.Resolve <ICacheManager>();

            // Note: the application may work in the multiple instance environment (e.g. on Azure)
            // We are trying to acquire a lock and initialize the application, possible cases:
            // 1. lock successfully acquired - initialize the application
            // 2. initialization is locked by another process - wait for completion and check the result of initialization. If the initialization failed - we can't continue the process and just throw exception

            Logger.Warn("Try to initialize database...");

            var expiry = TimeSpan.FromSeconds(30);
            var wait   = TimeSpan.FromSeconds(10);
            var retry  = TimeSpan.FromSeconds(1);

            const string seedDbKey           = "AppStart:SeedDb";
            const string seedDbFinishedOnKey = "SeedDbFinishedOn";
            var          cache = CacheManagerExtensions.GetCache <string, DateTime>(cacheManager, seedDbKey);

            var initializationStart          = DateTime.Now.ToUniversalTime();
            var initializedByCurrentInstance = false;

            lockFactory.DoExclusive(seedDbKey, expiry, wait, retry, () =>
            {
                // get last initialization time
                var seedDbTime = cache.Get(seedDbFinishedOnKey, key => DateTime.MinValue);

                if (seedDbTime != DateTime.MinValue && (
                        seedDbTime.Ticks > initializationStart.Ticks ||       /* DB was initialized while we were waiting for the lock */
                        (initializationStart - seedDbTime).TotalSeconds <= 30 /* DB was initialized less than 30 seconds ago */
                        ))
                {
                    Logger.Warn("Database initialized by another application instance");
                    return;
                }

                initializedByCurrentInstance = true;
                Logger.Warn("Database initialization started");

                Logger.Warn("Apply migrations...");
                var dbMigrator = ioc.Resolve <IAbpZeroDbMigrator>();
                dbMigrator?.CreateOrMigrateForHost();
                Logger.Warn("Apply migrations - finished");

                // find all seeders/bootstrappers and run them
                var bootstrapperTypes = _typeFinder.Find(t => typeof(IBootstrapper).IsAssignableFrom(t) && t.IsClass).ToList();
                bootstrapperTypes     = SortByDependencies(bootstrapperTypes);

                foreach (var bootstrapperType in bootstrapperTypes)
                {
                    AsyncHelper.RunSync(async() =>
                    {
                        if (ioc.Resolve(bootstrapperType) is IBootstrapper bootstrapper)
                        {
                            Logger.Warn($"Run bootstrapper: {bootstrapperType.Name}...");

                            var uowManager = ioc.Resolve <IUnitOfWorkManager>();
                            using (var unitOfWork = uowManager.Begin())
                            {
                                await bootstrapper.Process();
                                await unitOfWork.CompleteAsync();
                            }

                            Logger.Warn($"Run bootstrapper: {bootstrapperType.Name} - finished");
                        }
                    });
                }

                // update the DB seeding time
                cache.Set(seedDbFinishedOnKey, initializationStart, TimeSpan.FromMinutes(10));
            });

            Logger.Warn(initializedByCurrentInstance
                ? "Database initialization finished" :
                        "Database initialization skipped (locked by another instance)");

            //SeedHelper.SeedHostDb(IocManager);
        }