Пример #1
0
        public void WithParamsMultipleConstructors()
        {
            var Result = FastActivator.CreateInstance <ParamsMultipleTestClass>("A", true);

            Assert.Equal("A", Result.A);
            Assert.True(Result.B);
        }
Пример #2
0
        public void StructCreation()
        {
            var Result = FastActivator.CreateInstance <StructTest>(1, 2);

            Assert.Equal(1, Result.A);
            Assert.Equal(2, Result.B);
        }
Пример #3
0
 public void SimpleValue()
 {
     Assert.Equal(0, FastActivator.CreateInstance <int>());
     Assert.Equal(0, FastActivator.CreateInstance(typeof(int)));
     Assert.Null(FastActivator.CreateInstance <string>());
     Assert.Null(FastActivator.CreateInstance(typeof(string)));
 }
Пример #4
0
        public void Simple()
        {
            var Result = FastActivator.CreateInstance <SimpleTestClass>();

            Assert.Null(Result.A);
            Assert.False(Result.B);
        }
Пример #5
0
        public void ThrowsIfUnableToFindDefaultCtor()
        {
            var ex = Assert.Throws <InvalidOperationException>(
                () => FastActivator.CreateInstance <TestClassWithArgs>());

            Assert.Equal(string.Format("No default constructor exists for class {0}", typeof(TestClassWithArgs).FullName), ex.Message);
        }
Пример #6
0
        public void Save(Type projectionType, CronusMessage cronusMessage)
        {
            var projection = FastActivator.CreateInstance(projectionType) as IProjectionDefinition;

            if (projection != null)
            {
                var    projectionIds = projection.GetProjectionIds(cronusMessage.Payload as IEvent);
                string contractId    = projectionType.GetContractId();

                foreach (var projectionId in projectionIds)
                {
                    foreach (var version in GetProjectionVersions(contractId))
                    {
                        ISnapshot        snapshot         = snapshotStore.Load(contractId, projectionId, version);
                        ProjectionStream projectionStream = LoadProjectionStream(projectionType, version, projectionId, snapshot);
                        int snapshotMarker = snapshotStrategy.GetSnapshotMarker(projectionStream.Commits, snapshot.Revision);

                        EventOrigin eventOrigin = cronusMessage.GetEventOrigin();
                        DateTime    timestamp   = DateTime.UtcNow;
                        IEvent      @event      = cronusMessage.Payload as IEvent;

                        var commit = new ProjectionCommit(projectionId, version, @event, snapshotMarker, eventOrigin, timestamp);
                        projectionStore.Save(commit);
                    }
                }
            }
        }
            private void SetFormatter()
            {
                var prop    = ReflectionHelper.GetPropertyInfo(EntityType, PropertyPath);
                var attribs = (ModelPropertyAttribute[])prop.GetCustomAttributes(typeof(ModelPropertyAttribute), true);

                if (attribs.Length > 0 && attribs[0].DefaultFormatterType != null)
                {
                    formatter = FastActivator.CreateInstance <IDataFormatter>(attribs[0].DefaultFormatterType);
                }

                if (formatter == null)
                {
                    // Guess the best data formatter
                    foreach (var fter in ServiceLocator.GetAll <IDataFormatter>())
                    {
                        if (fter.TargetType == prop.PropertyType)
                        {
                            formatter = fter;
                            break;
                        }
                    }

                    // if the formatter is still not valid, error
                    if (Formatter == null)
                    {
                        var errorText = string.Format("There's no formatter valid for property '{0}.{1}', of type '{2}'",
                                                      prop.ReflectedType, prop.Name, prop.PropertyType.FullName);
                        throw new NotSupportedException(errorText);
                    }
                }
            }
Пример #8
0
        private CachingResult <TResult> ReadFromCache <TResult>(Expression expression)
        {
            var visitor = new CachingExpressionVisitor(_currentContext.Context, _extension);

            expression = visitor.ExtractPolicy(expression);

            var policy = visitor.CachingPolicy;

            if (policy == null)
            {
                return(new CachingResult <TResult>(expression, visitor));
            }

            var cachingResultType = typeof(CachingResult <,>).MakeGenericType(typeof(TResult), visitor.ElementType);
            var cachingResult     = (CachingResult <TResult>)FastActivator.CreateInstance(cachingResultType, expression, visitor);

            cachingResult.CacheKey   = _queryKeyGenerator.GenerateQueryKey(expression, policy);
            cachingResult.CacheEntry = _cache.Get(cachingResult.CacheKey, policy);

            if (cachingResult.CacheEntry != null)
            {
                Log(DbCachingEventId.CacheHit,
                    "Has read query result from cache. Key: {0}, Type: {1}, Policy: {2}.",
                    cachingResult.CacheKey.Key,
                    typeof(TResult),
                    policy);
            }

            return(cachingResult);
        }
Пример #9
0
        private void ExecuteOpenUserMessageCommand(UserMessageCommandParameter p)
        {
            var message = p.ViewModel;

            message.IsRead    = true;
            message.IsChecked = true;
            NotifyPropertyChanged(UNREADMESSAGECOUNT);

            switch (p.Command)
            {
            case MessageCommand.OpenUrl:
                if (Web.Browse((string)p.Parameter))
                {
                    if (message.Flags.HasFlag(MessageFlags.IgnoreAfterOpen))
                    {
                        _userSettings.IgnoreMessage(message.Message);
                    }
                }
                break;

            case MessageCommand.OpenDialog:
                var dialogType = (Type)p.Parameter;
                var stat       = Container.Resolve <IStatisticsViewModel>();
                var d          = FastActivator <IWorkHandler, IWindowManager, IStatisticsViewModel> .CreateInstance(dialogType, WorkHandler, WindowManager, stat) as Window;

                if (d.ShowDialog() == true)
                {
                    _userSettings.IgnoreMessage(message.Message);
                }
                break;
            }
        }
Пример #10
0
        public IHandlerInstance Create(Type handlerType)
        {
            object instance = FastActivator.CreateInstance(handlerType);

            ((dynamic)instance).State = (dynamic)State;
            return(new DefaultHandlerInstance(instance));
        }
Пример #11
0
        public bool Rebuild(Type projectionType, ProjectionVersion version, DateTime replayUntil)
        {
            DateTime startRebuildTimestamp = DateTime.UtcNow;
            int      progressCounter       = 0;

            log.Info(() => $"Start rebuilding projection `{projectionType.Name}` for version {version}. Deadline is {replayUntil}");

            var projection           = FastActivator.CreateInstance(projectionType) as IProjectionDefinition;
            var projectionEventTypes = GetInvolvedEvents(projectionType).ToList();

            projectionStore.InitializeProjectionStore(version);
            snapshotStore.InitializeProjectionSnapshotStore(version);
            var indexState = index.GetIndexState();

            if (indexState.IsPresent() == false)
            {
                return(false);
            }
            foreach (var eventType in projectionEventTypes)
            {
                log.Debug(() => $"Rebuilding projection `{projectionType.Name}` for version {version} using eventType `{eventType}`. Deadline is {replayUntil}");

                var indexId = new EventStoreIndexEventTypeId(eventType);
                IEnumerable <ProjectionCommit> indexCommits = index.EnumerateCommitsByEventType(indexId);

                foreach (var indexCommit in indexCommits)
                {
                    progressCounter++;
                    if (progressCounter % 1000 == 0)
                    {
                        log.Trace(() => $"Rebuilding projection {projectionType.Name} => PROGRESS:{progressCounter} Version:{version} EventType:{eventType} Deadline:{replayUntil} Total minutes working:{(DateTime.UtcNow - startRebuildTimestamp).TotalMinutes}. logId:{Guid.NewGuid().ToString()}");
                    }
                    // if the replay did not finish in time (specified by the AR) we need to abort.
                    if (DateTime.UtcNow >= replayUntil)
                    {
                        log.Info(() => $"Rebuilding projection `{projectionType.Name}` stopped bacause the deadline has been reached. PROGRESS:{progressCounter} Version:{version} EventType:`{eventType}` Deadline:{replayUntil}.");
                        return(false);
                    }
                    IAggregateRootId arId       = GetAggregateRootId(indexCommit.EventOrigin.AggregateRootId);
                    IEventStore      eventStore = eventStoreFactory.GetEventStore(tenantResolver.Resolve(arId));
                    EventStream      stream     = eventStore.Load(arId, theId => projectionType.GetBoundedContext().BoundedContextName);

                    foreach (AggregateCommit arCommit in stream.Commits)
                    {
                        for (int i = 0; i < arCommit.Events.Count; i++)
                        {
                            IEvent theEvent = arCommit.Events[i].Unwrap();

                            if (projectionEventTypes.Contains(theEvent.GetType().GetContractId()))
                            {
                                var origin = new EventOrigin(Convert.ToBase64String(arCommit.AggregateRootId), arCommit.Revision, i, arCommit.Timestamp);
                                projectionRepository.Save(projectionType, theEvent, origin); // overwrite
                            }
                        }
                    }
                }
            }
            log.Info(() => $"Finish rebuilding projection `{projectionType.Name}` for version {version}. Deadline was {replayUntil}");
            return(true);
        }
Пример #12
0
        public void Save(Type projectionType, IEvent @event, EventOrigin eventOrigin)
        {
            string contractId = projectionType.GetContractId();
            var    instance   = FastActivator.CreateInstance(projectionType);

            var statefullProjection = instance as IProjectionDefinition;

            if (statefullProjection != null)
            {
                var projectionIds = statefullProjection.GetProjectionIds(@event);

                foreach (var version in GetProjectionVersions(contractId))
                {
                    foreach (var projectionId in projectionIds)
                    {
                        ISnapshot        snapshot         = snapshotStore.Load(contractId, projectionId, version);
                        ProjectionStream projectionStream = LoadProjectionStream(projectionType, version, projectionId, snapshot);
                        int snapshotMarker = snapshotStrategy.GetSnapshotMarker(projectionStream.Commits, snapshot.Revision);

                        var commit = new ProjectionCommit(projectionId, version, @event, snapshotMarker, eventOrigin, DateTime.UtcNow);
                        projectionStore.Save(commit);
                    }
                }
            }
        }
Пример #13
0
        public virtual async Task PublishAsync <T>(T message, CancellationToken cancelToken = default) where T : class
        {
            var descriptors = _registry.GetConsumers(message);

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

            var envelopeType = typeof(ConsumeContext <>).MakeGenericType(typeof(T));
            var envelope     = (ConsumeContext <T>)FastActivator.CreateInstance(envelopeType, message);

            foreach (var d in descriptors)
            {
                var consumer = _resolver.Resolve(d);
                if (consumer != null)
                {
                    if (d.FireForget)
                    {
                        // No await
                        // "_ =" to discard 'async/await' compiler warning
                        _ = _invoker.InvokeAsync(d, consumer, envelope, cancelToken);
                    }
                    else
                    {
                        // Await the task
                        await _invoker.InvokeAsync(d, consumer, envelope, cancelToken);
                    }
                }
            }
        }
Пример #14
0
 public void ExpressionTreeConstructor()
 {
     for (int i = 0; i < IterationCount; i++)
     {
         FastActivator.CreateInstance <Node>();
     }
 }
Пример #15
0
        /// <summary>
        /// Create a new repository context.
        /// </summary>
        /// <returns>The new repository context.</returns>
        public IRepositoryContext Create()
        {
            var underlyingContext = _contextOptions != null
                ? (TDbContext)FastActivator.CreateInstance(typeof(TDbContext), _contextOptions)
                : RepositoryDependencyResolver.Current.Resolve <TDbContext>();

            return(new EfCoreRepositoryContext(underlyingContext));
        }
Пример #16
0
            public object Create(Type handlerType)
            {
                var handler = FastActivator
                              .CreateInstance(handlerType)
                              .AssignPropertySafely <IPort>(x => x.CommandPublisher = container.Resolve <IPublisher <ICommand> >(namedInstance));

                return(handler);
            }
        private static TServiceInterface CreateProxy <TServiceInterface, TActionInvokerProvider>()
            where TServiceInterface : class
            where TActionInvokerProvider : IActionInvokerProvider <TServiceInterface>
        {
            var types = GetGeneratedTypes <TServiceInterface, TActionInvokerProvider>();

            return((TServiceInterface)FastActivator.CreateInstance(types.Proxy));
        }
        public object CreateHandler(Type t)
        {
            object instance = externalFactory == null
                ? FastActivator.CreateInstance(t)
                : externalFactory.CreateHandler(t);

            return(instance);
        }
Пример #19
0
            public object Create(Type appServiceType)
            {
                var appService = FastActivator
                                 .CreateInstance(appServiceType)
                                 .AssignPropertySafely <IAggregateRootApplicationService>(x => x.Repository = container.Resolve <IAggregateRepository>(namedInstance));

                return(appService);
            }
        public void Type_CanBeActivated_UsingParameterlessConstructor()
        {
            var inst = FastActivator.CreateInstance(typeof(TestClass)) as TestClass;

            Assert.That(inst, Is.Not.Null);
            Assert.That(inst.Arg1, Is.EqualTo(default(string)));
            Assert.That(inst.Arg2, Is.EqualTo(default(bool)));
            Assert.That(inst.Arg3, Is.EqualTo(default(DateTime)));
        }
        public void CreateInstance_Class_Without_Arguments_Returning_Object()
        {
            object obj = FastActivator.CreateInstance(typeof(TestClass <int>));

            Assert.IsType <TestClass <int> >(obj);
            TestClass <int> testClass = (TestClass <int>)obj;

            Assert.Null(testClass.Values);
        }
        public void Type_CanBeActivated_UsingParameterizedConstructor()
        {
            var dateTime = DateTime.Now;
            var instance = FastActivator.CreateInstance(typeof(TestClass), new object[] { "test2", true, dateTime }) as TestClass;

            Assert.That(instance, Is.Not.Null);
            Assert.That(instance.Arg1, Is.EqualTo("test2"));
            Assert.That(instance.Arg2, Is.EqualTo(true));
            Assert.That(instance.Arg3, Is.EqualTo(dateTime));
        }
        public void Benchmark()
        {
            var activatorDuration     = Benchmark("Activator", () => (TestClass)Activator.CreateInstance(typeof(TestClass), "test", true, DateTime.Now));
            var fastActivatorDuration = Benchmark("FastActivator", () => FastActivator.CreateInstance <TestClass>(new object[] { "test", true, DateTime.Now }));

            Assert.That(fastActivatorDuration, Is.LessThan(activatorDuration));

            Benchmark("Activator (parameterless)", () => (TestClass)Activator.CreateInstance(typeof(TestClass)));
            Benchmark("FastActivator (parameterless)", FastActivator.CreateInstance <TestClass>);
        }
        public void MultipleTypes_CanBeActivated_UsingParameterizedConstructor()
        {
            var instance1 = FastActivator.CreateInstance(typeof(TestClass), new object[] { "instance1" }) as TestClass;
            var instance2 = FastActivator.CreateInstance(typeof(TestClass2), new object[] { "instance2" }) as TestClass2;

            Assert.That(instance1, Is.Not.Null);
            Assert.That(instance1.Arg1, Is.EqualTo("instance1"));

            Assert.That(instance2, Is.Not.Null);
            Assert.That(instance2.Arg1, Is.EqualTo("instance2"));
        }
Пример #25
0
        public Task <T> RestoreFromHistoryAsync <T>() where T : IProjectionDefinition
        {
            if (Commits.Count <= 0 && ReferenceEquals(null, GetSnapshot().State))
            {
                return(Task.FromResult(default(T)));
            }

            T projection = (T)FastActivator.CreateInstance(typeof(T), true);

            return(RestoreFromHistoryMamamiaAsync <T>(projection));
        }
Пример #26
0
        public Task <IProjectionDefinition> RestoreFromHistoryAsync(Type projectionType)
        {
            if (Commits.Count <= 0 && ReferenceEquals(null, GetSnapshot().State))
            {
                return(Task.FromResult(default(IProjectionDefinition)));
            }

            IProjectionDefinition projection = (IProjectionDefinition)FastActivator.CreateInstance(projectionType, true);

            return(RestoreFromHistoryMamamiaAsync(projection));
        }
        public void MultipleTypes_CanBeActivated_UsingParameterlessConstructor()
        {
            var instance1 = FastActivator.CreateInstance(typeof(TestClass));
            var instance2 = FastActivator.CreateInstance(typeof(TestClass2));

            Assert.That(instance1, Is.Not.Null);
            Assert.That(instance1.GetType(), Is.EqualTo(typeof(TestClass)));

            Assert.That(instance2, Is.Not.Null);
            Assert.That(instance2.GetType(), Is.EqualTo(typeof(TestClass2)));
        }
Пример #28
0
        public IProjectionDefinition RestoreFromHistory(Type projectionType)
        {
            if (Commits.Count <= 0 && ReferenceEquals(null, GetSnapshot().State))
            {
                return(null);
            }

            IProjectionDefinition projection = (IProjectionDefinition)FastActivator.CreateInstance(projectionType, true);

            return(RestoreFromHistoryMamamia(projection));
        }
Пример #29
0
        public IProjectionGetResult <IProjectionDefinition> RestoreFromHistory(Type projectionType)
        {
            if (commits.Count <= 0 && ReferenceEquals(null, snapshot.State))
            {
                return(ProjectionGetResult <IProjectionDefinition> .NoResult);
            }

            IProjectionDefinition projection = (IProjectionDefinition)FastActivator.CreateInstance(projectionType, true);

            return(RestoreFromHistoryMamamia(projection));
        }
Пример #30
0
        /// <summary>
        /// Try to gets an instance of a named pseudoclass filter.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the pseudoselector.
        /// </param>
        /// <param name="instance">
        /// [out] The new instance.
        /// </param>
        ///
        /// <returns>
        /// true if succesful, false if a pseudoselector of that name doesn't exist.
        /// </returns>

        public bool TryGetInstance(string name, out IPseudoSelector instance)
        {
            Type type;

            if (InnerSelectors.TryGetValue(name, out type))
            {
                instance = (IPseudoSelector)FastActivator.CreateInstance(type);
                return(true);
            }
            instance = null;
            return(false);
        }