Exemple #1
0
        protected List <NewConceptApplication> CreateNewApplications(List <ConceptApplication> oldApplications)
        {
            var stopwatch = Stopwatch.StartNew();

            var conceptApplications = new List <NewConceptApplication>();

            foreach (var conceptInfo in _dslModel.Concepts)
            {
                IConceptDatabaseDefinition[] implementations = _plugins.GetImplementations(conceptInfo.GetType()).ToArray();

                if (implementations.Count() == 0)
                {
                    implementations = new[] { new NullImplementation() }
                }
                ;

                conceptApplications.AddRange(implementations.Select(impl => new NewConceptApplication(conceptInfo, impl))); // DependsOn, CreateQuery and RemoveQuery will be set later.
            }
            MatchAndComputeNewApplicationIds(oldApplications, conceptApplications);
            _performanceLogger.Write(stopwatch, "DatabaseGenerator.CreateNewApplications: Created concept applications from plugins.");

            ComputeDependsOn(conceptApplications);
            _performanceLogger.Write(stopwatch, "DatabaseGenerator.CreateNewApplications: Computed dependencies.");

            ComputeCreateAndRemoveQuery(conceptApplications, _dslModel.Concepts);
            _performanceLogger.Write(stopwatch, "DatabaseGenerator.CreateNewApplications: Generated SQL queries for new concept applications.");

            _logger.Trace(() => ReportDependencies(conceptApplications));

            return(conceptApplications);
        }
        private GeneratedDataMigrationScripts ExecutePlugins()
        {
            var stopwatch = Stopwatch.StartNew();

            var codeBuilder = new DataMigrationScriptBuilder();

            foreach (var conceptInfo in _dslModel.Concepts)
            {
                foreach (var plugin in _plugins.GetImplementations(conceptInfo.GetType()))
                {
                    try
                    {
                        plugin.GenerateCode(conceptInfo, codeBuilder);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Part of the source code that was generated before the exception was thrown is written in the trace log.");
                        _logger.Trace(codeBuilder.GeneratedCode);
                        throw new FrameworkException($"Error while generating data-migration script for '{conceptInfo.GetUserDescription()}'.", ex);
                    }
                }
            }

            _logger.Trace(codeBuilder.GeneratedCode);

            _performanceLogger.Write(stopwatch, "DataMigrationScriptGenerator: Scripts generated.");

            return(codeBuilder.GetDataMigrationScripts());
        }
Exemple #3
0
        public IAssemblySource ExecutePlugins <TPlugin>(IPluginsContainer <TPlugin> plugins, string tagOpen, string tagClose, IConceptCodeGenerator initialCodeGenerator)
            where TPlugin : IConceptCodeGenerator
        {
            var stopwatch = Stopwatch.StartNew();

            var codeBuilder = new CodeBuilder(tagOpen, tagClose);

            if (initialCodeGenerator != null)
            {
                initialCodeGenerator.GenerateCode(null, codeBuilder);
            }

            foreach (var conceptInfo in _dslModel.Concepts)
            {
                foreach (var plugin in plugins.GetImplementations(conceptInfo.GetType()))
                {
                    try
                    {
                        plugin.GenerateCode(conceptInfo, codeBuilder);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex.ToString());
                        _logger.Error("Part of the source code that was generated before the exception was thrown is written in the trace log.");
                        _logger.Trace(codeBuilder.GeneratedCode);
                        throw;
                    }
                }
            }

            _performanceLogger.Write(stopwatch, "CodeGenerator: Code generated.");

            return(codeBuilder);
        }
        private IList <Claim> GetRequiredClaims(IEnumerable <ICommandInfo> commandInfos)
        {
            List <Claim> requiredClaims = new List <Claim>();

            foreach (ICommandInfo commandInfo in commandInfos)
            {
                var providers = _claimProviders.GetImplementations(commandInfo.GetType());
                foreach (var provider in providers)
                {
                    requiredClaims.AddRange(provider.GetRequiredClaims(commandInfo));
                }
            }
            return(requiredClaims);
        }
        public ProcessingResult ExecuteInner(IList <ICommandInfo> commands)
        {
            var authorizationMessage = _authorizationManager.Authorize(commands);

            if (!String.IsNullOrEmpty(authorizationMessage))
            {
                return new ProcessingResult
                       {
                           UserMessage   = authorizationMessage,
                           SystemMessage = authorizationMessage,
                           Success       = false
                       }
            }
            ;

            var commandResults = new List <CommandResult>();

            try
            {
                foreach (var commandInfo in commands)
                {
                    _logger.Trace("Executing command {0}: {1}.", commandInfo.GetType().Name, commandInfo);

                    var implementations = _commandRepository.GetImplementations(commandInfo.GetType());

                    if (implementations.Count() == 0)
                    {
                        throw new FrameworkException(string.Format(CultureInfo.InvariantCulture,
                                                                   "Cannot execute command \"{0}\". There are no command implementations loaded that implement the command.", commandInfo));
                    }

                    if (implementations.Count() > 1)
                    {
                        throw new FrameworkException(string.Format(CultureInfo.InvariantCulture,
                                                                   "Cannot execute command \"{0}\". It has more than one implementation registered: {1}.", commandInfo, String.Join(", ", implementations.Select(i => i.GetType().Name))));
                    }

                    var commandImplementation = implementations.Single();
                    _logger.Trace("Executing implementation {0}.", commandImplementation.GetType().Name);

                    var commandObserversForThisCommand = _commandObservers.GetImplementations(commandInfo.GetType());
                    var stopwatch = Stopwatch.StartNew();

                    foreach (var commandObeserver in commandObserversForThisCommand)
                    {
                        commandObeserver.BeforeExecute(commandInfo);
                        _performanceLogger.Write(stopwatch, () => "ProcessingEngine: CommandObeserver.BeforeExecute " + commandObeserver.GetType().FullName);
                    }

                    var commandResult = commandImplementation.Execute(commandInfo);

                    _performanceLogger.Write(stopwatch, () => "ProcessingEngine: Command executed (" + commandInfo.GetType().FullName + ").");
                    _logger.Trace("Execution result message: {0}", commandResult.Message);

                    if (commandResult.Success)
                    {
                        foreach (var commandObeserver in commandObserversForThisCommand)
                        {
                            commandObeserver.AfterExecute(commandInfo, commandResult);
                            _performanceLogger.Write(stopwatch, () => "ProcessingEngine: CommandObeserver.AfterExecute " + commandObeserver.GetType().FullName);
                        }
                    }

                    commandResults.Add(commandResult);

                    if (!commandResult.Success)
                    {
                        _persistenceTransaction.DiscardChanges();

                        var systemMessage = String.Format(CultureInfo.InvariantCulture, "Command failed. {0} {1} {2}", commandInfo.GetType().Name, commandInfo, commandImplementation.GetType().Name);
                        return(LogAndReturnError(commandResults, systemMessage + " " + commandResult.Message, systemMessage, commandResult.Message));
                    }
                }

                return(new ProcessingResult
                {
                    CommandResults = commandResults.ToArray(),
                    Success = true,
                    SystemMessage = null
                });
            }
            catch (Exception ex)
            {
                _persistenceTransaction.DiscardChanges();

                if (ex is TargetInvocationException && ex.InnerException is RhetosException)
                {
                    _logger.Trace(() => "Unwrapping exception: " + ex.ToString());
                    ex = ex.InnerException;
                }

                string userMessage   = null;
                string systemMessage = null;

                var sqlException = SqlUtility.InterpretSqlException(ex);
                if (sqlException != null)
                {
                    ex = sqlException;
                }

                if (ex is UserException)
                {
                    userMessage   = ex.Message;
                    systemMessage = (ex as UserException).SystemMessage;
                }
                else if (ex is ClientException)
                {
                    userMessage   = _clientExceptionUserMessage;
                    systemMessage = ex.Message;
                }
                else
                {
                    userMessage   = null;
                    systemMessage = "Internal server error occurred (" + ex.GetType().Name + "). See RhetosServer.log for more information.";
                }

                return(LogAndReturnError(
                           commandResults,
                           "Command execution error: ",
                           systemMessage,
                           userMessage,
                           ex));
            }
        }
        private CodeBuilder BuildCode <TPlugin>(IPluginsContainer <TPlugin> plugins, string tagOpen, string tagClose, IConceptCodeGenerator initialCodeGenerator) where TPlugin : IConceptCodeGenerator
        {
            var stopwatch = Stopwatch.StartNew();

            var codeBuilder = new CodeBuilder(tagOpen, tagClose);

            if (initialCodeGenerator != null)
            {
                initialCodeGenerator.GenerateCode(null, codeBuilder);
            }

            var conceptImplementations = _dslModel.GetTypes()
                                         .ToDictionary(conceptType => conceptType, conceptType => plugins.GetImplementations(conceptType).ToList());

            _performanceLogger.Write(stopwatch, $"Get implementations for {typeof(TPlugin).FullName}.");

            var implementationStopwatches = conceptImplementations.SelectMany(ci => ci.Value)
                                            .Select(plugin => plugin.GetType())
                                            .Distinct()
                                            .ToDictionary(pluginType => pluginType, pluginType => new Stopwatch());

            foreach (var conceptInfo in _dslModel.Concepts)
            {
                foreach (var plugin in conceptImplementations[conceptInfo.GetType()])
                {
                    try
                    {
                        var implementationStopwatch = implementationStopwatches[plugin.GetType()];
                        implementationStopwatch.Start();
                        plugin.GenerateCode(conceptInfo, codeBuilder);
                        implementationStopwatch.Stop();
                    }
                    catch (Exception e)
                    {
                        _logger.Info("Part of the source code that was generated before the exception was thrown is written in the trace log.");
                        _logger.Trace(() => codeBuilder.GenerateCode());
                        ExceptionsUtility.Rethrow(e);
                    }
                }
            }

            foreach (var imp in implementationStopwatches.OrderByDescending(i => i.Value.Elapsed.TotalSeconds).Take(3))
            {
                _performanceLogger.Write(imp.Value, () => $"{typeof(TPlugin).Name} total time for {imp.Key}.");
            }

            _performanceLogger.Write(stopwatch, $"Code generated for {typeof(TPlugin).FullName}.");
            return(codeBuilder);
        }
        private List <CodeGenerator> CreateCodeGenerators()
        {
            var codeGenerators         = new List <CodeGenerator>();
            var conceptImplementations = _dslModel.GetTypes()
                                         .ToDictionary(conceptType => conceptType, conceptType => _plugins.GetImplementations(conceptType).ToArray());

            foreach (var conceptInfo in _dslModel.Concepts)
            {
                var implementations = conceptImplementations[conceptInfo.GetType()];

                if (!implementations.Any())
                {
                    implementations = _nullImplementations;
                }

                codeGenerators.AddRange(implementations.Select(
                                            conceptImplementation => new CodeGenerator(conceptInfo, conceptImplementation)));
            }

            return(codeGenerators);
        }
Exemple #8
0
        public ProcessingResult ExecuteInner(IList <ICommandInfo> commands, Guid executionId)
        {
            var authorizationMessage = _authorizationManager.Authorize(commands);

            if (!string.IsNullOrEmpty(authorizationMessage))
            {
                return new ProcessingResult
                       {
                           UserMessage   = authorizationMessage,
                           SystemMessage = authorizationMessage,
                           Success       = false
                       }
            }
            ;

            var commandResults = new List <CommandResult>();
            var stopwatch      = Stopwatch.StartNew();

            foreach (var commandInfo in commands)
            {
                try
                {
                    _logger.Trace("Executing command {0}.", commandInfo);

                    var implementations = _commandRepository.GetImplementations(commandInfo.GetType());

                    if (implementations.Count() == 0)
                    {
                        throw new FrameworkException(string.Format(CultureInfo.InvariantCulture,
                                                                   "Cannot execute command \"{0}\". There are no command implementations loaded that implement the command.", commandInfo));
                    }

                    if (implementations.Count() > 1)
                    {
                        throw new FrameworkException(string.Format(CultureInfo.InvariantCulture,
                                                                   "Cannot execute command \"{0}\". It has more than one implementation registered: {1}.", commandInfo, String.Join(", ", implementations.Select(i => i.GetType().Name))));
                    }

                    var commandImplementation = implementations.Single();
                    _logger.Trace("Executing implementation {0}.", commandImplementation.GetType().Name);

                    var commandObserversForThisCommand = _commandObservers.GetImplementations(commandInfo.GetType());
                    stopwatch.Restart();

                    foreach (var commandObeserver in commandObserversForThisCommand)
                    {
                        commandObeserver.BeforeExecute(commandInfo);
                        _performanceLogger.Write(stopwatch, () => "ProcessingEngine: CommandObeserver.BeforeExecute " + commandObeserver.GetType().FullName);
                    }

                    CommandResult commandResult;
                    try
                    {
                        commandResult = commandImplementation.Execute(commandInfo);
                    }
                    finally
                    {
                        _performanceLogger.Write(stopwatch, () => "ProcessingEngine: Command executed (" + commandImplementation + ": " + commandInfo + ").");
                    }
                    _logger.Trace("Execution result message: {0}", commandResult.Message);

                    if (commandResult.Success)
                    {
                        foreach (var commandObeserver in commandObserversForThisCommand)
                        {
                            commandObeserver.AfterExecute(commandInfo, commandResult);
                            _performanceLogger.Write(stopwatch, () => "ProcessingEngine: CommandObeserver.AfterExecute " + commandObeserver.GetType().FullName);
                        }
                    }

                    commandResults.Add(commandResult);

                    if (!commandResult.Success)
                    {
                        _persistenceTransaction.DiscardChanges();

                        var systemMessage = "Command failed: " + commandImplementation + ", " + commandInfo + ".";
                        return(LogAndReturnError(commandResults, systemMessage + " " + commandResult.Message, systemMessage, commandResult.Message, null, commands, executionId));
                    }
                }
                catch (Exception ex)
                {
                    _persistenceTransaction.DiscardChanges();

                    if (ex is TargetInvocationException && ex.InnerException is RhetosException)
                    {
                        _logger.Trace(() => "Unwrapping exception: " + ex.ToString());
                        ex = ex.InnerException;
                    }

                    string userMessage   = null;
                    string systemMessage = null;

                    ex = _sqlUtility.InterpretSqlException(ex) ?? ex;

                    if (ex is UserException)
                    {
                        var userException = (UserException)ex;
                        userMessage   = _localizer[userException.Message, userException.MessageParameters]; // TODO: Remove this code after cleaning the double layer of exceptions in the server response call stack.
                        systemMessage = userException.SystemMessage;
                    }
                    else if (ex is ClientException)
                    {
                        userMessage   = _clientExceptionUserMessage;
                        systemMessage = ex.Message;
                    }
                    else
                    {
                        userMessage   = null;
                        systemMessage = FrameworkException.GetInternalServerErrorMessage(_localizer, ex);
                    }

                    return(LogAndReturnError(commandResults, "Command failed: " + commandInfo + ".", systemMessage, userMessage, ex, commands, executionId));
                }
            }

            return(new ProcessingResult
            {
                CommandResults = commandResults.ToArray(),
                Success = true,
                SystemMessage = null
            });
        }
Exemple #9
0
        public void Generate()
        {
            var stopwatch = Stopwatch.StartNew();

            var codeBuilder = new DataMigrationScriptBuilder();

            var conceptImplementations = _dslModel.GetTypes()
                                         .ToDictionary(conceptType => conceptType, conceptType => _plugins.GetImplementations(conceptType).ToList());

            foreach (var conceptInfo in _dslModel.Concepts)
            {
                foreach (var plugin in conceptImplementations[conceptInfo.GetType()])
                {
                    try
                    {
                        plugin.GenerateCode(conceptInfo, codeBuilder);
                    }
                    catch (Exception ex)
                    {
                        _logger.Info("Part of the source code that was generated before the exception was thrown is written in the trace log.");
                        _logger.Trace(() => codeBuilder.GenerateCode());
                        throw new FrameworkException($"Error while generating data-migration script for '{conceptInfo.GetUserDescription()}'.", ex);
                    }
                }
            }

            _performanceLogger.Write(stopwatch, "Scripts generated.");

            string serializedConcepts = JsonConvert.SerializeObject(codeBuilder.GetDataMigrationScripts(), Formatting.Indented);

            File.WriteAllText(Path.Combine(_rhetosBuildEnvironment.GeneratedAssetsFolder, ConceptDataMigrationScriptsFileName), serializedConcepts, Encoding.UTF8);
        }