Exemplo n.º 1
0
        private static void TestComplexLinqQuery()
        {
            using (ClientTransaction.CreateRootTransaction().EnterDiscardingScope())
            {
                using (StopwatchScope.CreateScope("Complex query took {elapsed:ms} ms"))
                {
                    var result = from acl in QueryFactory.CreateLinqQuery <StatefulAccessControlList>()
                                 from sc in acl.GetStateCombinationsForQuery()
                                 from usage in sc.GetStateUsagesForQuery().DefaultIfEmpty()
                                 from propertyReference in acl.GetClassForQuery().GetStatePropertyReferencesForQuery().DefaultIfEmpty()
                                 select new
                    {
                        Class                = acl.GetClassForQuery().ID,
                        Acl                  = acl.ID.GetHandle <StatefulAccessControlList>(),
                        HasState             = propertyReference != null,
                        StatePropertyID      = propertyReference.StateProperty.ID.Value,
                        StatePropertyClassID = propertyReference.StateProperty.ID.ClassID,
                        StatePropertyName    = propertyReference.StateProperty.Name,
                        StateValue           = usage.StateDefinition.Name
                    };

                    result.Count();
                }
            }
        }
Exemplo n.º 2
0
        public static BaseTypeCache Create(IEnumerable <Type> types)
        {
            ArgumentUtility.CheckNotNull("types", types);

            s_log.Value.DebugFormat("Beginning to build BaseTypeCache...");
            using (StopwatchScope.CreateScope(s_log.Value, LogLevel.Debug, string.Format("Built BaseTypeCache. Time taken: {{elapsed}}")))
            {
                // Note: there is no meassurable impact when switching this code to parallel execution.
                var classes    = new List <KeyValuePair <Type, Type> >();
                var interfaces = new List <KeyValuePair <Type, Type> >();

                foreach (var type in types)
                {
                    classes.AddRange(
                        type.CreateSequence(t => t.BaseType)
                        .Where(t => !t.IsInterface)
                        .Select(baseType => new KeyValuePair <Type, Type> (baseType, type)));

                    interfaces.AddRange(
                        type.GetInterfaces()
                        .Select(interfaceType => new KeyValuePair <Type, Type> (interfaceType, type)));

                    if (type.IsInterface)
                    {
                        interfaces.Add(new KeyValuePair <Type, Type> (type, type));
                    }
                }

                var classCache     = classes.ToLookup(kvp => kvp.Key, kvp => kvp.Value, MemberInfoEqualityComparer <Type> .Instance);
                var interfaceCache = interfaces.ToLookup(kvp => kvp.Key, kvp => kvp.Value, MemberInfoEqualityComparer <Type> .Instance);

                return(new BaseTypeCache(classCache, interfaceCache));
            }
        }
Exemplo n.º 3
0
        public AccessType[] GetAccessTypes(IDomainObjectHandle <AccessControlList> aclHandle, SecurityToken token)
        {
            ArgumentUtility.CheckNotNull("aclHandle", aclHandle);
            ArgumentUtility.CheckNotNull("token", token);

            using (SecurityFreeSection.Activate())
            {
                using (ClientTransaction.CreateRootTransaction().EnterDiscardingScope())
                {
                    using (StopwatchScope.CreateScope(
                               s_log,
                               LogLevel.Info,
                               string.Format(
                                   "Evaluated access types of ACL '{0}' for principal '{1}'. Time taken: {{elapsed:ms}}ms",
                                   aclHandle.ObjectID,
                                   token.Principal.User != null ? token.Principal.User.ObjectID.ToString() : "<unknown>")))
                    {
                        LoadAccessTypeDefinitions();
                        var acl = LoadAccessControlList(aclHandle);

                        var accessInformation = acl.GetAccessTypes(token);
                        return(Array.ConvertAll(accessInformation.AllowedAccessTypes, ConvertToAccessType));
                    }
                }
            }
        }
Exemplo n.º 4
0
 private StopwatchScope CreateStopwatchScopeForQueryParsing(string queryName)
 {
     return(StopwatchScope.CreateScope(
                s_log,
                LogLevel.Debug,
                "Parsed query for " + GetType().Name + "." + queryName + "(). Time taken: {elapsed:ms}ms"));
 }
Exemplo n.º 5
0
        // The MixinConfiguration is passed to Execute in order to be able to call PrepareOutputDirectory before analyzing the configuration (and potentially
        // locking old generated files).
        public void Execute(MixinConfiguration configuration)
        {
            ArgumentUtility.CheckNotNull("configuration", configuration);

            using (StopwatchScope.CreateScope(s_log, LogLevel.Info, "Time needed to mix and save all types: {elapsed}."))
            {
                _errors.Clear();
                _processedTypes.Clear();
                _finishedTypes.Clear();
                _generatedFiles = new string[0].AsReadOnly();

                s_log.InfoFormat("The base directory is '{0}'.", AppDomain.CurrentDomain.BaseDirectory);

                var pipeline = MixerPipelineFactory.CreatePipeline(AssemblyOutputDirectory);

                var mixedTypes = MixedTypeFinder.FindMixedTypes(configuration).ToArray();

                s_log.Info("Generating types...");
                using (configuration.EnterScope())
                {
                    foreach (var mixedType in mixedTypes)
                    {
                        Generate(mixedType, pipeline);
                    }
                }

                s_log.Info("Saving assemblies...");
                Save(pipeline);
            }

            s_log.InfoFormat("Successfully generated concrete types for {0} target classes.", _finishedTypes.Count);
        }
Exemplo n.º 6
0
        public void Checkpoint_AfterDispose()
        {
            var scope = StopwatchScope.CreateScope((context, s) => { });

            scope.Dispose();
            scope.Checkpoint("");
        }
Exemplo n.º 7
0
 protected StopwatchScope CreateStopwatchScopeForQueryExecution(string queryName)
 {
     return(StopwatchScope.CreateScope(
                s_log,
                LogLevel.Debug,
                "Fetched " + queryName + " into " + GetType().Name + ". Time taken: {elapsed:ms}ms"));
 }
Exemplo n.º 8
0
        public void New()
        {
            var args = new object[]
            {
                new TestConstructorInjectionWithOneParameter(null),
                new TestConstructorInjectionWithOneParameter(null),
                new TestConcreteImplementationAttributeType()
            };

            Func <object> factory = () => new TestConstructorInjectionWithThreeParameters(
                (ITestConstructorInjectionWithOneParameter)args[0],
                (ITestConstructorInjectionWithOneParameter)args[1],
                (ITestSingletonConcreteImplementationAttributeType)args[2]);

            int acc = 0;

            using (StopwatchScope.CreateScope("New: elapsed: {elapsed}"))
            {
                for (int i = 0; i < 1000000; ++i)
                {
                    var instance = factory();
                    acc ^= instance.GetHashCode();
                }
            }
            Console.WriteLine(acc);
        }
Exemplo n.º 9
0
        public void Checkpoint()
        {
            var times = new List <Tuple <string, TimeSpan, TimeSpan> > ();

            using (var scope = StopwatchScope.CreateScope((context, s) => times.Add(Tuple.Create(context, s.ElapsedTotal, s.ElapsedSinceLastCheckpoint))))
            {
                Wait(TimeSpan.FromMilliseconds(5.0));
                scope.Checkpoint("One");
                Wait(TimeSpan.FromMilliseconds(5.0));
                scope.Checkpoint("Two");
                Wait(TimeSpan.FromMilliseconds(5.0));
            }
            Assert.That(times.Count, Is.EqualTo(3));

            Assert.That(times[0].Item1, Is.EqualTo("One"));
            Assert.That(times[0].Item2, Is.GreaterThan(TimeSpan.FromMilliseconds(5.0))); // total
            Assert.That(times[0].Item3, Is.GreaterThan(TimeSpan.FromMilliseconds(5.0))); // since last checkpoint

            Assert.That(times[1].Item1, Is.EqualTo("Two"));
            Assert.That(times[1].Item2, Is.GreaterThan(times[0].Item2 + TimeSpan.FromMilliseconds(5.0))); // total
            Assert.That(times[1].Item3, Is.GreaterThan(TimeSpan.FromMilliseconds(5.0)));                  // since last checkpoint
            Assert.That(times[1].Item3, Is.LessThan(times[1].Item2));

            Assert.That(times[2].Item1, Is.EqualTo("end"));
            Assert.That(times[2].Item2, Is.GreaterThan(times[1].Item2 + TimeSpan.FromMilliseconds(5.0))); // total
            Assert.That(times[2].Item3, Is.GreaterThan(TimeSpan.FromMilliseconds(5.0)));                  // since last checkpoint
            Assert.That(times[2].Item3, Is.LessThan(times[2].Item2));
        }
Exemplo n.º 10
0
        public void LinqExpression()
        {
            var args = new object[]
            {
                new TestConstructorInjectionWithOneParameter(null),
                new TestConstructorInjectionWithOneParameter(null),
                new TestConcreteImplementationAttributeType()
            };

            var ctorInfo = typeof(TestConstructorInjectionWithThreeParameters).GetConstructors()[0];

            var ctorArgExpressions = ctorInfo.GetParameters().Select(p => (Expression)Expression.Constant(args[p.Position]));
            Expression <Func <object> > factoryExpression = Expression.Lambda <Func <object> > (Expression.New(ctorInfo, ctorArgExpressions));

            Func <object> factory = factoryExpression.Compile();

            int acc = 0;

            using (StopwatchScope.CreateScope("Built factory: elapsed: {elapsed}"))
            {
                for (int i = 0; i < 1000000; ++i)
                {
                    var instance = factory();
                    acc ^= instance.GetHashCode();
                }
            }
            Console.WriteLine(acc);
        }
        /// <summary>
        /// Retrieves the list of types available in the assemblies found by the <see cref="AssemblyFinder"/> specified in the constructor.
        /// </summary>
        /// <param name="baseType">The base type to match. Can be null.</param>
        /// <param name="excludeGlobalTypes">Indicates whether types from all referenced assemblies should be checked.</param>
        /// <returns>
        /// A collection of types that match the criteria specified by baseType and excludeGlobalTypes.
        /// </returns>
        public ICollection GetTypes(Type baseType, bool excludeGlobalTypes)
        {
            var nonNullBaseType = baseType ?? typeof(object);

            if (nonNullBaseType.IsSealed) // ValueTypes are also sealed
            {
                return new[] { nonNullBaseType }
            }
            ;

            if (!excludeGlobalTypes && AssemblyTypeCache.IsGacAssembly(nonNullBaseType.Assembly))
            {
                return(_globalTypesCache.GetOrAdd(
                           nonNullBaseType,
                           key =>
                {
                    s_log.Value.DebugFormat("Discovering types derived from '{0}', including GAC...", key);
                    using (StopwatchScope.CreateScope(
                               s_log.Value,
                               LogLevel.Info,
                               string.Format("Discovered types derived from '{0}', including GAC. Time taken: {{elapsed}}", key)))
                    {
                        return GetTypesFromAllAssemblies(key, false).ToList().AsReadOnly();
                    }
                }));
            }

            var baseTypeCache = _baseTypeCache.Value;

            Assertion.IsTrue(_baseTypeCache.IsValueCreated);

            return(baseTypeCache.GetTypes(nonNullBaseType));
        }
Exemplo n.º 12
0
        public void Resume_AfterDispose()
        {
            var scope = StopwatchScope.CreateScope((context, s) => { });

            scope.Dispose();
            scope.Resume();
        }
Exemplo n.º 13
0
 private static void InitializeLinq()
 {
     using (ClientTransaction.CreateRootTransaction().EnterDiscardingScope())
     {
         using (StopwatchScope.CreateScope("Initializing Linq took {elapsed:ms} ms."))
             QueryFactory.CreateLinqQuery <Tenant>();
     }
 }
Exemplo n.º 14
0
 private static void ExecuteFirstLinqQuery()
 {
     using (ClientTransaction.CreateRootTransaction().EnterDiscardingScope())
     {
         using (StopwatchScope.CreateScope("Executing first Linq query took {elapsed:ms} ms."))
             QueryFactory.CreateLinqQuery <Position>().ToList();
     }
 }
 private static MixinConfiguration BuildMasterConfiguration()
 {
     s_log.Info("Building mixin master configuration...");
     using (StopwatchScope.CreateScope(s_log, LogLevel.Info, "Time needed to build mixin master configuration: {elapsed}."))
     {
         return(DeclarativeConfigurationBuilder.BuildDefaultConfiguration());
     }
 }
Exemplo n.º 16
0
        public void CreateScope_Log()
        {
            var logMock = MockRepository.GenerateMock <ILog> ();

            var scope = StopwatchScope.CreateScope(logMock, LogLevel.Error, "{context}#{elapsed}#{elapsed:ms}#{elapsedCP}#{elapsedCP:ms}");

            Wait(TimeSpan.FromMilliseconds(1.0));

            scope.Pause();

            var firstElapsed   = scope.ElapsedTotal;
            var firstElapsedCP = scope.ElapsedSinceLastCheckpoint;

            scope.Checkpoint("one");

            scope.Resume();

            Wait(TimeSpan.FromMilliseconds(1.0));

            scope.Pause();
            var secondElapsed   = scope.ElapsedTotal;
            var secondElapsedCP = scope.ElapsedSinceLastCheckpoint;

            scope.Dispose();

            var expectedFirstArgs = new[] {
                "one",
                firstElapsed.ToString(),
                firstElapsed.TotalMilliseconds.ToString(),
                firstElapsedCP.ToString(),
                firstElapsedCP.TotalMilliseconds.ToString()
            };

            logMock.AssertWasCalled(
                mock =>
                mock.LogFormat(
                    Arg.Is(LogLevel.Error),
                    Arg <int> .Is.Null,
                    Arg <Exception> .Is.Null,
                    Arg.Is("{0}#{1}#{2}#{3}#{4}"),
                    Arg <object[]> .List.Equal(expectedFirstArgs)));

            var expectedSecondArgs = new[] {
                "end",
                secondElapsed.ToString(),
                secondElapsed.TotalMilliseconds.ToString(),
                secondElapsedCP.ToString(),
                secondElapsedCP.TotalMilliseconds.ToString()
            };

            logMock.AssertWasCalled(
                mock => mock.LogFormat(
                    Arg.Is(LogLevel.Error),
                    Arg <int> .Is.Null,
                    Arg <Exception> .Is.Null,
                    Arg.Is("{0}#{1}#{2}#{3}#{4}"),
                    Arg <object[]> .List.Equal(expectedSecondArgs)));
        }
Exemplo n.º 17
0
 private ICollection <RootAssembly> FindRootAssemblies()
 {
     s_log.Value.Debug("Finding root assemblies...");
     using (StopwatchScope.CreateScope(s_log.Value, LogLevel.Debug, "Time spent for finding and loading root assemblies: {elapsed}."))
     {
         return(_rootAssemblyFinder.FindRootAssemblies()
                .LogAndReturnItems(s_log.Value, LogLevel.Debug, count => string.Format("Found {0} root assemblies.", count))
                .ToList());
     }
 }
Exemplo n.º 18
0
 private void LoadAccessTypeDefinitions()
 {
     using (StopwatchScope.CreateScope(s_log, LogLevel.Debug, "Fetched access types for AccessResolver. Time taken: {elapsed:ms}ms"))
     {
         s_queryCache.ExecuteCollectionQuery <AccessTypeDefinition> (
             ClientTransaction.Current,
             MethodInfo.GetCurrentMethod().Name,
             accessTypes => accessTypes);
     }
 }
Exemplo n.º 19
0
 private static void TestSimpleLinqQueryWithCustomProjection()
 {
     using (ClientTransaction.CreateRootTransaction().EnterDiscardingScope())
     {
         using (StopwatchScope.CreateScope("Simple Linq query with custom projection took {elapsed:ms} ms"))
         {
             QueryFactory.CreateLinqQuery <Tenant>().Select(p => new { Value = p.ID, Key = p.UniqueIdentifier }).ToList();
         }
     }
 }
Exemplo n.º 20
0
 private static void TestSimpleLinqQuery()
 {
     using (ClientTransaction.CreateRootTransaction().EnterDiscardingScope())
     {
         using (StopwatchScope.CreateScope("Simple Linq query took {elapsed:ms} ms"))
         {
             QueryFactory.CreateLinqQuery <Position>().ToList();
         }
     }
 }
Exemplo n.º 21
0
        public void Pause()
        {
            var scope = StopwatchScope.CreateScope((context, s) => { });

            scope.Pause();
            var elapsedBefore = scope.ElapsedTotal;

            Wait(TimeSpan.FromMilliseconds(5.0));
            Assert.That(scope.ElapsedTotal, Is.EqualTo(elapsedBefore));
        }
Exemplo n.º 22
0
        public void Dispose_AfterDispose()
        {
            int counter = 0;
            var scope   = StopwatchScope.CreateScope((context, s) => ++ counter);

            scope.Dispose();
            Assert.That(counter, Is.EqualTo(1));

            scope.Dispose();
            Assert.That(counter, Is.EqualTo(1));
        }
 private BaseTypeCache CreateBaseTypeCache()
 {
     s_log.Value.DebugFormat("Creating cache for all types in application directory...");
     using (StopwatchScope.CreateScope(
                s_log.Value,
                LogLevel.Info,
                "Created cache for all types in application directory. Time taken: {elapsed}"))
     {
         return(BaseTypeCache.Create(GetTypesFromAllAssemblies(null, true)));
     }
 }
Exemplo n.º 24
0
 private User GetUser(string userName)
 {
     using (StopwatchScope.CreateScope(
                s_log,
                LogLevel.Info,
                "Refreshed data in CachedUser for user '" + userName + "'. Time taken: {elapsed:ms}ms"))
     {
         var clientTransaction = ClientTransaction.CreateRootTransaction();
         return(LoadUser(clientTransaction, userName));
     }
 }
        public static TargetClassDefinition CreateWithoutValidation(ClassContext context)
        {
            ArgumentUtility.CheckNotNull("context", context);

            s_log.DebugFormat("Creating an unvalidated class definition for: {0}.", context);

            using (StopwatchScope.CreateScope(s_log, LogLevel.Debug, "Time needed to create class definition: {elapsed}."))
            {
                return(CreateInternal(context));
            }
        }
Exemplo n.º 26
0
        public RelationDefinition[] GetRelationDefinitions(IDictionary <Type, ClassDefinition> classDefinitions)
        {
            ArgumentUtility.CheckNotNull("classDefinitions", classDefinitions);
            s_log.InfoFormat("Reflecting relation definitions of {0} class definitions...", classDefinitions.Count);

            using (StopwatchScope.CreateScope(s_log, LogLevel.Info, "Time needed to reflect relation definitions: {elapsed}."))
            {
                var relationDefinitions = MappingObjectFactory.CreateRelationDefinitionCollection(classDefinitions);
                return(relationDefinitions
                       .LogAndReturnValue(s_log, LogLevel.Info, result => string.Format("Generated {0} relation definitions.", result.Length)));
            }
        }
Exemplo n.º 27
0
        public void CreateScope_Console()
        {
            var oldOut     = Console.Out;
            var writerMock = MockRepository.GenerateMock <TextWriter> ();

            Console.SetOut(writerMock);

            try
            {
                var scope = StopwatchScope.CreateScope("{context}#{elapsed}#{elapsed:ms}#{elapsedCP}#{elapsedCP:ms}");

                Wait(TimeSpan.FromMilliseconds(1.0));

                scope.Pause();

                var firstElapsed   = scope.ElapsedTotal;
                var firstElapsedCP = scope.ElapsedSinceLastCheckpoint;
                scope.Checkpoint("one");

                scope.Resume();

                Wait(TimeSpan.FromMilliseconds(1.0));

                scope.Pause();
                var secondElapsed   = scope.ElapsedTotal;
                var secondElapsedCP = scope.ElapsedSinceLastCheckpoint;
                scope.Dispose();

                var expectedFirstArgs = new[]
                {
                    "one",
                    firstElapsed.ToString(),
                    firstElapsed.TotalMilliseconds.ToString(),
                    firstElapsedCP.ToString(),
                    firstElapsedCP.TotalMilliseconds.ToString()
                };
                writerMock.AssertWasCalled(mock => mock.WriteLine(Arg.Is("{0}#{1}#{2}#{3}#{4}"), Arg <object[]> .List.Equal(expectedFirstArgs)));

                var expectedSecondArgs = new[]
                {
                    "end",
                    secondElapsed.ToString(),
                    secondElapsed.TotalMilliseconds.ToString(),
                    secondElapsedCP.ToString(),
                    secondElapsedCP.TotalMilliseconds.ToString()
                };
                writerMock.AssertWasCalled(mock => mock.WriteLine(Arg.Is("{0}#{1}#{2}#{3}#{4}"), Arg <object[]> .List.Equal(expectedSecondArgs)));
            }
            finally
            {
                Console.SetOut(oldOut);
            }
        }
Exemplo n.º 28
0
        public void ElapsedSinceLastCheckpoint_AfterScopeDisposed()
        {
            var scope = StopwatchScope.CreateScope((context, s) => { });

            scope.Checkpoint("test");
            Wait(TimeSpan.FromMilliseconds(1.0));
            Assert.That(scope.ElapsedSinceLastCheckpoint, Is.GreaterThan(TimeSpan.Zero));

            scope.Dispose();

            Assert.That(scope.ElapsedSinceLastCheckpoint, Is.EqualTo(TimeSpan.Zero));
        }
Exemplo n.º 29
0
        public ClassDefinition[] GetClassDefinitions()
        {
            s_log.Info("Reflecting class definitions...");

            using (StopwatchScope.CreateScope(s_log, LogLevel.Info, "Time needed to reflect class definitions: {elapsed}."))
            {
                var types            = GetDomainObjectTypesSorted();
                var classDefinitions = MappingObjectFactory.CreateClassDefinitionCollection(types);

                return(classDefinitions
                       .LogAndReturnValue(s_log, LogLevel.Info, result => string.Format("Generated {0} class definitions.", result.Length)));
            }
        }
Exemplo n.º 30
0
        protected override Data LoadData(GuidRevisionValue revision)
        {
            using (ClientTransaction.CreateRootTransaction().EnterDiscardingScope())
            {
                s_log.Info("Reset SecurityContextUserRevisionBasedCache cache.");
                using (StopwatchScope.CreateScope(s_log, LogLevel.Info, "Refreshed data in SecurityContextUserRevisionBasedCache. Time taken: {elapsed:ms}ms"))
                {
                    var users = LoadUsers();

                    return(new Data(revision, users));
                }
            }
        }