Esempio n. 1
0
        internal SqlPreCommand Schema_Synchronizing(Replacements replacements)
        {
            SqlPreCommand views = SyncViews(replacements);
            SqlPreCommand procedures = SyncProcedures(replacements);

            return SqlPreCommand.Combine(Spacing.Triple, views, procedures);
        }
        static SqlPreCommand SyncronizeProperties(Replacements rep)
        {
            var current = Administrator.TryRetrieveAll<PropertyRouteEntity>(rep).AgGroupToDictionary(a => a.RootType.FullClassName, g => g.ToDictionary(f => f.Path, "PropertyEntity in the database with path"));

            var should = TypeLogic.TryEntityToType(rep).SelectDictionary(dn => dn.FullClassName, (dn, t) => GenerateProperties(t, dn).ToDictionary(f => f.Path, "PropertyEntity in the database with path"));

            Table table = Schema.Current.Table<PropertyRouteEntity>();

            using (rep.WithReplacedDatabaseName())
                return Synchronizer.SynchronizeScript(should, current,
                    null,
                    null,
                    (fullName, dicShould, dicCurr) =>
                        Synchronizer.SynchronizeScriptReplacing(rep, PropertiesFor.FormatWith(fullName),
                        dicShould,
                        dicCurr,
                        null,
                        (path, c) => table.DeleteSqlSync(c),
                        (path, s, c) =>
                        {
                            c.Path = s.Path;
                            return table.UpdateSqlSync(c);
                        }, Spacing.Simple),
                    Spacing.Double);
        }
Esempio n. 3
0
        public static string ReplaceTokens(Replacements replacements, string input)
        {
            string output = input;

            if (replacements != null)
            {
                var tokenRegex = new Regex(@"{(\w+)}");
                var tokenMatches = tokenRegex.Matches(input);

                foreach (Match tokenMatch in tokenMatches)
                {
                    var wholeToken = tokenMatch.Groups[0].Value;
                    var token = tokenMatch.Groups[1].Value;
                    string tokenReplacement = null;

                    const string RESPONSE = "RESPONSE_";
                    const string REQUEST = "REQUEST_";

                    if (replacements.ResponseHeaders != null && token.StartsWith(RESPONSE))
                    {
                        var tokenKey = token.Remove(0, RESPONSE.Length);
                        tokenKey = tokenKey.Replace("_", "-");

                        tokenReplacement = replacements.ResponseHeaders[tokenKey];
                    }
                    else if (replacements.RequestHeaders != null && token.StartsWith(REQUEST))
                    {
                        var tokenKey = token.Remove(0, REQUEST.Length);
                        tokenKey = tokenKey.Replace("_", "-");

                        tokenReplacement = replacements.RequestHeaders[tokenKey];
                    }
                    else if (replacements.RequestServerVariables != null)
                    {
                        tokenReplacement = replacements.RequestServerVariables[token];
                    }

                    if (!string.IsNullOrEmpty(tokenReplacement))
                    {
                        output = output.Replace(wholeToken, tokenReplacement);
                    }
                } 
            }

            return output;
        }
        static void Remember(Replacements replacements, string tokenString, QueryToken token)
        {
            List<QueryToken> tokenList = token.Follow(a => a.Parent).Reverse().ToList();

            string[] oldParts = tokenString.Split('.');
            string[] newParts = token.FullKey().Split('.');

            List<string> oldPartsList = oldParts.ToList();
            List<string> newPartsList = newParts.ToList();

            Func<string, string> rep = str =>
            {
                if (Replacements.AutoReplacement == null)
                    return null;

                Replacements.Selection? sel = Replacements.AutoReplacement(str, null);

                if (sel == null || sel.Value.NewValue == null)
                    return null;

                return sel.Value.NewValue;
            };

            int pos = -1;
            while (oldPartsList.Count > 0 && newPartsList.Count > 0 &&
                (oldPartsList[0] == newPartsList[0] ||
                 rep(oldPartsList[0]) == newPartsList[0]))
            {
                oldPartsList.RemoveAt(0);
                newPartsList.RemoveAt(0);
                pos++;
            }

            while (oldPartsList.Count > 0 && newPartsList.Count > 0 &&
                (oldPartsList[oldPartsList.Count - 1] == newPartsList[newPartsList.Count - 1] ||
                 rep(oldPartsList[oldPartsList.Count - 1]) == newPartsList[newPartsList.Count - 1]))
            {
                oldPartsList.RemoveAt(oldPartsList.Count - 1);
                newPartsList.RemoveAt(newPartsList.Count - 1);
            }

            string key = pos == -1 ? QueryKey(tokenList[0].QueryName) : TypeKey(tokenList[pos].Type);

            replacements.GetOrCreate(key)[oldPartsList.ToString(".")] = newPartsList.ToString(".");
        }
Esempio n. 5
0
        public static SqlPreCommand SynchronizeSchemasScript(Replacements replacements)
        {
            HashSet<SchemaName> model = Schema.Current.GetDatabaseTables().Select(a => a.Name.Schema).ToHashSet();
            HashSet<SchemaName> database = new HashSet<SchemaName>();
            foreach (var db in model.Select(a => a.Database).Distinct())
	        {
                using (Administrator.OverrideDatabaseInViews(db))
                {
                    database.AddRange(
                     from s in Database.View<SysSchemas>()
                     select new SchemaName(db, s.name));
                }
	        }

            return Synchronizer.SynchronizeScript(
                model.ToDictionary(a => a),
                database.ToDictionary(a => a),
                (_, newSN) => SqlBuilder.CreateSchema(newSN),
                null,
                null, Spacing.Simple);
        }
Esempio n. 6
0
    public static FixTokenResult FixToken(Replacements replacements, ref QueryTokenEmbedded token, QueryDescription qd, SubTokensOptions options, string?remainingText, bool allowRemoveToken, bool allowReCreate)
    {
        var t = token;

        using (DelayedConsole.Delay(() => { SafeConsole.WriteColor(t.ParseException == null ? ConsoleColor.Gray : ConsoleColor.Red, "  " + t.TokenString); Console.WriteLine(" " + remainingText); }))
        {
            if (token.ParseException == null)
            {
                return(FixTokenResult.Nothing);
            }

            DelayedConsole.Flush();
            FixTokenResult result = FixToken(replacements, token.TokenString, out QueryToken? resultToken, qd, options, remainingText, allowRemoveToken, allowReCreate);

            if (result == FixTokenResult.Fix)
            {
                token = new QueryTokenEmbedded(resultToken !);
            }

            return(result);
        }
    }
        /// <summary>Get a list of Phase Names for life Cycle</summary>
        /// <param name="crop">The crop.</param>
        /// <returns>A list of Phase Names.</returns>
        private string[] GetPhaseNames(LifeCycle lifeCycle)
        {
            if (lifeCycle.LifeCyclePhaseNames.Length == 0)
            {
                Simulations  simulations  = Apsim.Parent(lifeCycle as IModel, typeof(Simulations)) as Simulations;
                Replacements replacements = Apsim.Child(simulations, typeof(Replacements)) as Replacements;
                if (replacements != null)
                {
                    LifeCycle replacementLifeCycle = Apsim.Child(replacements, (lifeCycle as IModel).Name) as LifeCycle;
                    if (replacementLifeCycle != null)
                    {
                        return(replacementLifeCycle.LifeCyclePhaseNames);
                    }
                }
            }
            else
            {
                return(lifeCycle.LifeCyclePhaseNames);
            }

            return(new string[0]);
        }
Esempio n. 8
0
        SqlPreCommand?SyncViews(Replacements replacements)
        {
            var oldView = Schema.Current.DatabaseNames().SelectMany(db =>
            {
                using (Administrator.OverrideDatabaseInSysViews(db))
                {
                    return((from v in Database.View <SysViews>()
                            join s in Database.View <SysSchemas>() on v.schema_id equals s.schema_id
                            join m in Database.View <SysSqlModules>() on v.object_id equals m.object_id
                            select KVP.Create(new ObjectName(new SchemaName(db, s.name), v.name), m.definition)).ToList());
                }
            }).ToDictionary();

            using (replacements.WithReplacedDatabaseName())
                return(Synchronizer.SynchronizeScript(Spacing.Double,
                                                      Views,
                                                      oldView,
                                                      createNew: (name, newView) => newView.CreateView(),
                                                      removeOld: null,
                                                      mergeBoth: (name, newDef, oldDef) => Clean(newDef.CreateView().Sql) == Clean(oldDef) ? null : newDef.AlterView()
                                                      ));
        }
Esempio n. 9
0
        static SqlPreCommand SynchronizeQueries(Replacements replacements)
        {
            var should = GenerateQueries();

            var current = Administrator.TryRetrieveAll <QueryEntity>(replacements);

            Table table = Schema.Current.Table <QueryEntity>();

            using (replacements.WithReplacedDatabaseName())
                return(Synchronizer.SynchronizeScriptReplacing(
                           replacements,
                           QueriesKey,
                           should.ToDictionaryEx(a => a.Key, "query in memory"),
                           current.ToDictionaryEx(a => a.Key, "query in database"),
                           (n, s) => table.InsertSqlSync(s),
                           (n, c) => table.DeleteSqlSync(c),
                           (fn, s, c) =>
                {
                    c.Key = s.Key;
                    return table.UpdateSqlSync(c);
                }, Spacing.Double));
        }
        /// <summary>Get a list of phases for lifecycle.</summary>
        /// <param name="lifeCycle">The lifecycle.</param>
        /// <returns>A list of phases.</returns>
        public static string[] GetPhaseNames(LifeCycle lifeCycle)
        {
            if (lifeCycle.LifeCyclePhaseNames.Length == 0)
            {
                Simulations  simulations  = (lifeCycle as IModel).FindAncestor <Simulations>();
                Replacements replacements = simulations.FindChild <Replacements>();
                if (replacements != null)
                {
                    LifeCycle replacementLifeCycle = replacements.FindChild((lifeCycle as IModel).Name) as LifeCycle;
                    if (replacementLifeCycle != null)
                    {
                        return(replacementLifeCycle.LifeCyclePhaseNames);
                    }
                }
            }
            else
            {
                return(lifeCycle.LifeCyclePhaseNames);
            }

            return(new string[0]);
        }
Esempio n. 11
0
        /// <summary>Get a list of cultivars for crop.</summary>
        /// <param name="crop">The crop.</param>
        /// <returns>A list of cultivars.</returns>
        private string[] GetCultivarNames(IPlant crop)
        {
            if (crop.CultivarNames.Length == 0)
            {
                Simulations  simulations  = Apsim.Parent(crop as IModel, typeof(Simulations)) as Simulations;
                Replacements replacements = Apsim.Child(simulations, typeof(Replacements)) as Replacements;
                if (replacements != null)
                {
                    IPlant replacementCrop = Apsim.Child(replacements, (crop as IModel).Name) as IPlant;
                    if (replacementCrop != null)
                    {
                        return(replacementCrop.CultivarNames);
                    }
                }
            }
            else
            {
                return(crop.CultivarNames);
            }

            return(new string[0]);
        }
Esempio n. 12
0
        static SqlPreCommand SynchronizeOperations(Replacements replacements, SyncData data)
        {
            var dic = Database.Query <OperationHelpEntity>().ToList();

            if (dic.IsEmpty())
            {
                return(null);
            }

            var queryKeys = DynamicQueryManager.Current.GetQueryNames().ToDictionary(a => QueryUtils.GetKey(a));

            var table = Schema.Current.Table <OperationHelpEntity>();

            var replace = replacements.TryGetC(QueryLogic.QueriesKey);

            using (replacements.WithReplacedDatabaseName())
                return(dic.Select(qh =>
                {
                    qh.Description = SynchronizeContent(qh.Description, replacements, data);

                    return table.UpdateSqlSync(qh);
                }).Combine(Spacing.Simple));
        }
Esempio n. 13
0
        SqlPreCommand SyncProcedures(Replacements replacements)
        {
            var oldProcedures = Schema.Current.DatabaseNames().SelectMany(db =>
            {
                using (Administrator.OverrideDatabaseInSysViews(db))
                {
                    return((from p in Database.View <SysObjects>()
                            join s in Database.View <SysSchemas>() on p.schema_id equals s.schema_id
                            where p.type == "P" || p.type == "IF" || p.type == "FN"
                            join m in Database.View <SysSqlModules>() on p.object_id equals m.object_id
                            select KVP.Create(new ObjectName(new SchemaName(db, s.name), p.name), m.definition)).ToList());
                }
            }).ToDictionary();

            return(Synchronizer.SynchronizeScript(
                       StoreProcedures,
                       oldProcedures,
                       (name, newProc) => newProc.CreateSql(),
                       null,
                       (name, newProc, oldProc) =>
                       Clean(newProc.CreateSql().Sql) == Clean(oldProc) ? null : newProc.AlterSql(),
                       Spacing.Double));
        }
Esempio n. 14
0
        SqlPreCommand SyncViews(Replacements replacements)
        {
            var oldView = Schema.Current.DatabaseNames().SelectMany(db =>
            {
                using (Administrator.OverrideDatabaseInSysViews(db))
                {
                    return (from v in Database.View<SysViews>()
                            join s in Database.View<SysSchemas>() on v.schema_id equals s.schema_id
                            join m in Database.View<SysSqlModules>() on v.object_id equals m.object_id
                            select KVP.Create(new ObjectName(new SchemaName(db, s.name), v.name), m.definition)).ToList();
                }
            }).ToDictionary();

            using (replacements.WithReplacedDatabaseName())
                return Synchronizer.SynchronizeScript(
                    Views,
                    oldView,
                    (name, newView) => newView.CreateView(),
                    null,
                    (name, newDef, oldDef) =>
                        Clean(newDef.CreateView().Sql) == Clean(oldDef) ? null : newDef.AlterView(),
                    Spacing.Double);
        }
Esempio n. 15
0
        static SqlPreCommand SynchronizeTypes(Replacements replacements, SyncData data)
        {
            var dic = Database.Query <EntityHelpEntity>().ToList();

            if (dic.IsEmpty())
            {
                return(null);
            }

            var typesByTableName = Schema.Current.Tables.ToDictionary(kvp => kvp.Value.Name.Name, kvp => kvp.Key);

            var replace = replacements.TryGetC(Replacements.KeyTables);

            var table = Schema.Current.Table <EntityHelpEntity>();

            using (replacements.WithReplacedDatabaseName())
                return(dic.Select(eh =>
                {
                    Type type = typesByTableName.TryGetC(replace.TryGetC(eh.Type.TableName) ?? eh.Type.TableName);

                    if (type == null)
                    {
                        return null; //PreDeleteSqlSync
                    }
                    var repProperties = replacements.TryGetC(PropertyRouteLogic.PropertiesFor.FormatWith(type.FullName));
                    var routes = PropertyRoute.GenerateRoutes(type).ToDictionary(pr => { var ps = pr.PropertyString(); return repProperties.TryGetC(ps) ?? ps; });
                    eh.Properties.RemoveAll(p => !routes.ContainsKey(p.Property.Path));
                    foreach (var prop in eh.Properties)
                    {
                        prop.Description = SynchronizeContent(prop.Description, replacements, data);
                    }

                    eh.Description = SynchronizeContent(eh.Description, replacements, data);

                    return table.UpdateSqlSync(eh);
                }).Combine(Spacing.Simple));
        }
Esempio n. 16
0
        public void AddResourceModelToReplacements()
        {
            ExplorerPresenter explorerPresenter = UITestUtilities.OpenBasicFileInGui();

            GtkUtilities.WaitForGtkEvents();

            // Add a replacements node.
            Replacements replacements = new Replacements();

            Structure.Add(replacements, explorerPresenter.ApsimXFile);
            explorerPresenter.Refresh();

            // Select the replacements node, then activate the 'add model' context menu item.
            explorerPresenter.SelectNode(replacements);
            explorerPresenter.ContextMenu.AddModel(explorerPresenter, EventArgs.Empty);
            GtkUtilities.WaitForGtkEvents();

            TreeView addModelsTree = (TreeView)ReflectionUtilities.GetValueOfFieldOrProperty("tree", explorerPresenter.CurrentPresenter);

            // Now, we double click on the fertiliser node. This should add a fertiliser model.
            // For some reason, sending a double click event doesn't trigger the ActivateRow signal.
            // Therefore, we need to manually activate the row.
            //GtkUtilities.ClickOnTreeView(treeView, path, 0, EventType.TwoButtonPress, ModifierType.None, GtkUtilities.ButtonPressType.LeftClick);
            ActivateNode(addModelsTree, ".Models.PMF.Wheat");
            Assert.AreEqual(1, replacements.Children.Count, "Replacements should now have 1 child after adding wheat, but it doesn't");
            Assert.AreEqual(typeof(Models.PMF.Plant), replacements.Children[0].GetType());

            // Wheat should have some children (read in from the resource file).
            IModel wheat = replacements.Children[0];

            Assert.NotZero(wheat.Children.Count);
            // The children should all be visible.
            foreach (IModel child in wheat.Children)
            {
                Assert.False(child.IsHidden);
            }
        }
Esempio n. 17
0
            public bool Consume(FileInfo info, out string key, out uint number)
            {
                key    = string.Empty;
                number = 0;
                var m = r.Match(info.Name);

                if (!m.Success)
                {
                    return(false);
                }
                var val = m.Groups[2].Value;

                if (!uint.TryParse(val, out number))
                {
                    return(false);
                }
                key = Replacements.CombinePath(info.DirectoryName, info.Name.Replace(m.Groups[1].Value, String.Format(
                                                                                         CultureInfo.InvariantCulture,
                                                                                         "part{0}",
                                                                                         1.ToString(new string('0', val.Length), CultureInfo.InvariantCulture)
                                                                                         ))).ToUpperInvariant();

                return(true);
            }
Esempio n. 18
0
            public bool Consume(FileInfo info, out string key, out uint number)
            {
                key    = string.Empty;
                number = 0;
                var m = r.Match(info.Name);

                if (!m.Success)
                {
                    return(false);
                }
                var val = m.Groups[1].Value;

                if (!uint.TryParse(val, out number))
                {
                    return(false);
                }
                key = Replacements.CombinePath(info.DirectoryName, String.Format(
                                                   CultureInfo.InvariantCulture,
                                                   "{0}.{1}1", Path.GetFileNameWithoutExtension(info.Name),
                                                   new string('0', m.Groups[1].Length - 1)
                                                   )).ToUpperInvariant();

                return(true);
            }
        static SqlPreCommand Schema_Synchronizing(Replacements rep)
        {
            var conds = (from rt in Database.Query <RuleTypeEntity>()
                         from c in rt.Conditions
                         select new { rt.Resource, c.Condition, rt.Role }).ToList();

            var errors = conds.GroupBy(a => new { a.Resource, a.Condition }, a => a.Role)
                         .Where(gr =>
            {
                if (gr.Key.Condition.FieldInfo == null)
                {
                    return(rep.TryGetC(typeof(TypeConditionSymbol).Name)?.TryGetC(gr.Key.Condition.Key) == null);
                }

                return(!TypeConditionLogic.IsDefined(gr.Key.Resource.ToType(), gr.Key.Condition));
            })
                         .ToList();

            using (rep.WithReplacedDatabaseName())
                return(errors.Select(a => Administrator.UnsafeDeletePreCommand((RuleTypeEntity rt) => rt.Conditions, Database.MListQuery((RuleTypeEntity rt) => rt.Conditions)
                                                                               .Where(mle => mle.Element.Condition.Is(a.Key.Condition) && mle.Parent.Resource.Is(a.Key.Resource)))
                                     .AddComment("TypeCondition {0} not defined for {1} (roles {2})".FormatWith(a.Key.Condition, a.Key.Resource, a.ToString(", "))))
                       .Combine(Spacing.Double));
        }
        public static SqlPreCommand SynchronizeSchemasScript(Replacements replacements)
        {
            HashSet<SchemaName> model = Schema.Current.GetDatabaseTables().Select(a => a.Name.Schema).Where(a => !SqlBuilder.SystemSchemas.Contains(a.Name)).ToHashSet();
            HashSet<SchemaName> database = new HashSet<SchemaName>();
            foreach (var db in Schema.Current.DatabaseNames())
            {
                using (Administrator.OverrideDatabaseInSysViews(db))
                {
                    var schemaNames = Database.View<SysSchemas>().Select(s => s.name).ToList().Except(SqlBuilder.SystemSchemas);

                    database.AddRange(schemaNames.Select(sn => new SchemaName(db, sn)));
                }
            }

            using (replacements.WithReplacedDatabaseName())
                return Synchronizer.SynchronizeScriptReplacing(replacements, "Schemas",
                    model.ToDictionary(a => a.ToString()),
                    database.ToDictionary(a => a.ToString()),
                    (_, newSN) => SqlBuilder.CreateSchema(newSN),
                    (_, oldSN) => DropSchema(oldSN) ? SqlBuilder.DropSchema(oldSN) :  null,
                    (_, newSN, oldSN) => newSN.Equals(oldSN) ? null :
                        SqlPreCommand.Combine(Spacing.Simple, SqlBuilder.DropSchema(oldSN), SqlBuilder.CreateSchema(newSN)),
                    Spacing.Double);
        }
Esempio n. 21
0
        public virtual void EnterCompoundStatement([NotNull] ParserRuleContext context)
        {
            var lhs      = GetText(context.children[0]);
            var opAssign = GetText(context.children[1]);
            var rhs      = GetText(context.children[2]);

            string op = opAssign.Substring(0, opAssign.Length - 1);

            var node = context.children[2];

            while (node.ChildCount == 1)
            {
                node = node.GetChild(0);
            }
            var isLeaf = node.ChildCount == 0;

            Replacements.Push(
                new Replacement(
                    context.start.StartIndex,
                    context.stop.StopIndex,
                    string.Format(isLeaf ? "{0} = {0} {1} {2}" : "{0} = {0} {1} ({2})", lhs, op, rhs)
                    )
                );
        }
        public static FixTokenResult FixToken(Replacements replacements, ref QueryTokenEntity token, QueryDescription qd, SubTokensOptions options, string remainingText, bool allowRemoveToken, bool allowReCreate)
        {
            SafeConsole.WriteColor(token.ParseException == null ? ConsoleColor.Gray : ConsoleColor.Red, "  " + token.TokenString);
            Console.WriteLine(" " + remainingText);

            if (token.ParseException == null)
                return FixTokenResult.Nothing;

            QueryToken resultToken;
            FixTokenResult result = FixToken(replacements, token.TokenString, out resultToken, qd, options, remainingText, allowRemoveToken, allowReCreate);

            if (result == FixTokenResult.Fix)
                token = new QueryTokenEntity(resultToken);

            return result;
        }
Esempio n. 23
0
        static SqlPreCommand?ProcessUserChart(Replacements replacements, Table table, UserChartEntity uc)
        {
            Console.Write(".");
            using (DelayedConsole.Delay(() => SafeConsole.WriteLineColor(ConsoleColor.White, "UserChart: " + uc.DisplayName)))
                using (DelayedConsole.Delay(() => Console.WriteLine(" ChartScript: " + uc.ChartScript.ToString())))
                    using (DelayedConsole.Delay(() => Console.WriteLine(" Query: " + uc.Query.Key)))
                    {
                        try
                        {
                            if (uc.Filters.Any(a => a.Token?.ParseException != null) ||
                                uc.Columns.Any(a => a.Token?.ParseException != null))
                            {
                                QueryDescription qd = QueryLogic.Queries.QueryDescription(uc.Query.ToQueryName());

                                if (uc.Filters.Any())
                                {
                                    using (DelayedConsole.Delay(() => Console.WriteLine(" Filters:")))
                                    {
                                        foreach (var item in uc.Filters.ToList())
                                        {
                                            if (item.Token != null)
                                            {
                                                QueryTokenEmbedded token = item.Token;
                                                switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | SubTokensOptions.CanAggregate, "{0} {1}".FormatWith(item.Operation, item.ValueString), allowRemoveToken: true, allowReCreate: false))
                                                {
                                                case FixTokenResult.Nothing: break;

                                                case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(uc, u => u.Guid == uc.Guid));

                                                case FixTokenResult.RemoveToken: uc.Filters.Remove(item); break;

                                                case FixTokenResult.SkipEntity: return(null);

                                                case FixTokenResult.Fix: item.Token = token; break;

                                                default: break;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (uc.Columns.Any())
                                {
                                    using (DelayedConsole.Delay(() => Console.WriteLine(" Columns:")))
                                    {
                                        foreach (var item in uc.Columns.ToList())
                                        {
                                            if (item.Token == null)
                                            {
                                                continue;
                                            }

                                            QueryTokenEmbedded token = item.Token;
                                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement | SubTokensOptions.CanAggregate, item.ScriptColumn.DisplayName, allowRemoveToken: item.ScriptColumn.IsOptional, allowReCreate: false))
                                            {
                                            case FixTokenResult.Nothing: break;

                                            case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(uc, u => u.Guid == uc.Guid));

                                            case FixTokenResult.RemoveToken: item.Token = null; break;

                                            case FixTokenResult.SkipEntity: return(null);

                                            case FixTokenResult.Fix: item.Token = token; break;

                                            default: break;
                                            }
                                        }
                                    }
                                }
                            }

                            foreach (var item in uc.Filters.Where(f => !f.IsGroup).ToList())
                            {
retry:
                                string?val = item.ValueString;
                                switch (QueryTokenSynchronizer.FixValue(replacements, item.Token !.Token.Type, ref val, allowRemoveToken: true, isList: item.Operation.Value.IsList()))
                                {
                                case FixTokenResult.Nothing: break;
        static string AskTypeReplacement(Replacements replacements, string type)
        {
            return replacements.GetOrCreate("cleanNames").GetOrCreate(type, () =>
            {
                if (Replacements.AutoReplacement != null)
                {
                    Replacements.Selection? sel = Replacements.AutoReplacement(type, null);

                    if (sel != null && sel.Value.NewValue != null)
                        return sel.Value.NewValue;
                }

                Console.WriteLine("Type {0} has been renamed?".FormatWith(type));

                int startingIndex = 0;
                StringDistance sd = new StringDistance();
                var list = TypeLogic.NameToType.Keys.OrderBy(t => sd.LevenshteinDistance(t, type)).ToList();
            retry:
                int maxElements = Console.LargestWindowHeight - 11;

                list.Skip(startingIndex).Take(maxElements)
                           .Select((s, i) => "- {1,2}: {2} ".FormatWith(i + startingIndex == 0 ? ">" : " ", i + startingIndex, s)).ToConsole();
                Console.WriteLine();
                SafeConsole.WriteLineColor(ConsoleColor.White, "- n: None");

                int remaining = list.Count - startingIndex - maxElements;
                if (remaining > 0)
                    SafeConsole.WriteLineColor(ConsoleColor.White, "- +: Show more values ({0} remaining)", remaining);

                while (true)
                {
                    string answer = Console.ReadLine();

                    if (answer == null)
                        throw new InvalidOperationException("Impossible to synchronize interactively without Console");

                    answer = answer.ToLower();

                    if (answer == "+" && remaining > 0)
                    {
                        startingIndex += maxElements;
                        goto retry;
                    }

                    if (answer == "n")
                        return null;

                    int option = 0;
                    if (int.TryParse(answer, out option))
                    {
                        return list[option];
                    }

                    Console.WriteLine("Error");
                }
            });
        }
Esempio n. 25
0
        static SqlPreCommand ProcessUserChart(Replacements replacements, Table table, UserChartEntity uc)
        {
            try
            {
                Console.Clear();

                SafeConsole.WriteLineColor(ConsoleColor.White, "UserChart: " + uc.DisplayName);
                Console.WriteLine(" ChartScript: " + uc.ChartScript.ToString());
                Console.WriteLine(" Query: " + uc.Query.Key);

                if (uc.Filters.Any(a => a.Token.ParseException != null) ||
                    uc.Columns.Any(a => a.Token != null && a.Token.ParseException != null) ||
                    uc.Orders.Any(a => a.Token.ParseException != null))
                {
                    QueryDescription qd = DynamicQueryManager.Current.QueryDescription(uc.Query.ToQueryName());

                    SubTokensOptions canAggregate = uc.GroupResults ? SubTokensOptions.CanAggregate : 0;

                    if (uc.Filters.Any())
                    {
                        Console.WriteLine(" Filters:");
                        foreach (var item in uc.Filters.ToList())
                        {
                            QueryTokenEmbedded token = item.Token;
                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | canAggregate, "{0} {1}".FormatWith(item.Operation, item.ValueString), allowRemoveToken: true, allowReCreate: false))
                            {
                            case FixTokenResult.Nothing: break;

                            case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(uc));

                            case FixTokenResult.RemoveToken: uc.Filters.Remove(item); break;

                            case FixTokenResult.SkipEntity: return(null);

                            case FixTokenResult.Fix: item.Token = token; break;

                            default: break;
                            }
                        }
                    }

                    if (uc.Columns.Any())
                    {
                        Console.WriteLine(" Columns:");
                        foreach (var item in uc.Columns.ToList())
                        {
                            QueryTokenEmbedded token = item.Token;
                            if (item.Token == null)
                            {
                                continue;
                            }

                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement | canAggregate, item.ScriptColumn.DisplayName, allowRemoveToken: item.ScriptColumn.IsOptional, allowReCreate: false))
                            {
                            case FixTokenResult.Nothing: break;

                            case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(uc));

                            case FixTokenResult.RemoveToken: item.Token = null; break;

                            case FixTokenResult.SkipEntity: return(null);

                            case FixTokenResult.Fix: item.Token = token; break;

                            default: break;
                            }
                        }
                    }

                    if (uc.Orders.Any())
                    {
                        Console.WriteLine(" Orders:");
                        foreach (var item in uc.Orders.ToList())
                        {
                            QueryTokenEmbedded token = item.Token;
                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement | canAggregate, item.OrderType.ToString(), allowRemoveToken: true, allowReCreate: false))
                            {
                            case FixTokenResult.Nothing: break;

                            case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(uc));

                            case FixTokenResult.RemoveToken: uc.Orders.Remove(item); break;

                            case FixTokenResult.SkipEntity: return(null);

                            case FixTokenResult.Fix: item.Token = token; break;

                            default: break;
                            }
                        }
                    }
                }

                foreach (var item in uc.Filters.ToList())
                {
                    string val = item.ValueString;
                    switch (QueryTokenSynchronizer.FixValue(replacements, item.Token.Token.Type, ref val, allowRemoveToken: true, isList: item.Operation.IsList()))
                    {
                    case FixTokenResult.Nothing: break;

                    case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(uc));

                    case FixTokenResult.RemoveToken: uc.Filters.Remove(item); break;

                    case FixTokenResult.SkipEntity: return(null);

                    case FixTokenResult.Fix: item.ValueString = val; break;
                    }
                }

                foreach (var item in uc.Columns)
                {
                    uc.FixParameters(item);
                }

                foreach (var item in uc.Parameters)
                {
                    string val = item.Value;
retry:
                    switch (FixParameter(item, ref val))
                    {
                    case FixTokenResult.Nothing: break;

                    case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(uc));

                    case FixTokenResult.RemoveToken: uc.Parameters.Remove(item); break;

                    case FixTokenResult.SkipEntity: return(null);

                    case FixTokenResult.Fix: { item.Value = val; goto retry; }
                    }
                }


                try
                {
                    return(table.UpdateSqlSync(uc, includeCollections: true));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Integrity Error:");
                    SafeConsole.WriteLineColor(ConsoleColor.DarkRed, e.Message);
                    while (true)
                    {
                        SafeConsole.WriteLineColor(ConsoleColor.Yellow, "- s: Skip entity");
                        SafeConsole.WriteLineColor(ConsoleColor.Red, "- d: Delete entity");

                        string answer = Console.ReadLine();

                        if (answer == null)
                        {
                            throw new InvalidOperationException("Impossible to synchronize interactively without Console");
                        }

                        answer = answer.ToLower();

                        if (answer == "s")
                        {
                            return(null);
                        }

                        if (answer == "d")
                        {
                            return(table.DeleteSqlSync(uc));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return(new SqlPreCommandSimple("-- Exception in {0}: {1}".FormatWith(uc.BaseToString(), e.Message)));
            }
            finally
            {
                Console.Clear();
            }
        }
Esempio n. 26
0
        static SqlPreCommand ProcessUserChart(Replacements replacements, Table table, UserChartEntity uc)
        {
            try
            {
                Console.Clear();

                SafeConsole.WriteLineColor(ConsoleColor.White, "UserChart: " + uc.DisplayName);
                Console.WriteLine(" ChartScript: " + uc.ChartScript.ToString());
                Console.WriteLine(" Query: " + uc.Query.Key);

                if (uc.Filters.Any(a => a.Token.ParseException != null) ||
                   uc.Columns.Any(a => a.Token != null && a.Token.ParseException != null) ||
                   uc.Orders.Any(a => a.Token.ParseException != null))
                {
                    QueryDescription qd = DynamicQueryManager.Current.QueryDescription(uc.Query.ToQueryName());

                    SubTokensOptions canAggregate = uc.GroupResults ? SubTokensOptions.CanAggregate : 0;

                    if (uc.Filters.Any())
                    {
                        Console.WriteLine(" Filters:");
                        foreach (var item in uc.Filters.ToList())
                        {
                            QueryTokenEntity token = item.Token;
                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | canAggregate, "{0} {1}".FormatWith(item.Operation, item.ValueString), allowRemoveToken: true, allowReCreate: false))
                            {
                                case FixTokenResult.Nothing: break;
                                case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uc);
                                case FixTokenResult.RemoveToken: uc.Filters.Remove(item); break;
                                case FixTokenResult.SkipEntity: return null;
                                case FixTokenResult.Fix: item.Token = token; break;
                                default: break;
                            }
                        }
                    }

                    if (uc.Columns.Any())
                    {
                        Console.WriteLine(" Columns:");
                        foreach (var item in uc.Columns.ToList())
                        {
                            QueryTokenEntity token = item.Token;
                            if (item.Token == null)
                                break;

                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement | canAggregate, item.ScriptColumn.DisplayName, allowRemoveToken: item.ScriptColumn.IsOptional, allowReCreate: false))
                            {
                                case FixTokenResult.Nothing: break;
                                case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uc);
                                case FixTokenResult.RemoveToken: item.Token = null; break;
                                case FixTokenResult.SkipEntity: return null;
                                case FixTokenResult.Fix: item.Token = token; break;
                                default: break;
                            }
                        }
                    }

                    if (uc.Orders.Any())
                    {
                        Console.WriteLine(" Orders:");
                        foreach (var item in uc.Orders.ToList())
                        {
                            QueryTokenEntity token = item.Token;
                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement | canAggregate, item.OrderType.ToString(), allowRemoveToken: true, allowReCreate: false))
                            {
                                case FixTokenResult.Nothing: break;
                                case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uc);
                                case FixTokenResult.RemoveToken: uc.Orders.Remove(item); break;
                                case FixTokenResult.SkipEntity: return null;
                                case FixTokenResult.Fix: item.Token = token; break;
                                default: break;
                            }
                        }
                    }
                }

                foreach (var item in uc.Filters.ToList())
                {
                    string val = item.ValueString;
                    switch (QueryTokenSynchronizer.FixValue(replacements, item.Token.Token.Type, ref val, allowRemoveToken: true, isList: item.Operation == FilterOperation.IsIn))
                    {
                        case FixTokenResult.Nothing: break;
                        case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uc);
                        case FixTokenResult.RemoveToken: uc.Filters.Remove(item); break;
                        case FixTokenResult.SkipEntity: return null;
                        case FixTokenResult.Fix: item.ValueString = val; break;
                    }
                }

                foreach (var item in uc.Columns)
                {
                    uc.FixParameters(item);
                }


                try
                {
                    return table.UpdateSqlSync(uc, includeCollections: true);
                }
                catch(Exception e)
                {
                    Console.WriteLine("Integrity Error:");
                    SafeConsole.WriteLineColor(ConsoleColor.DarkRed, e.Message);
                    while (true)
                    {
                        SafeConsole.WriteLineColor(ConsoleColor.Yellow, "- s: Skip entity");
                        SafeConsole.WriteLineColor(ConsoleColor.Red, "- d: Delete entity");

                        string answer = Console.ReadLine();

                        if (answer == null)
                            throw new InvalidOperationException("Impossible to synchronize interactively without Console");

                        answer = answer.ToLower();

                        if (answer == "s")
                            return null;

                        if (answer == "d")
                            return table.DeleteSqlSync(uc);
                    }
                }

               
            }
            catch (Exception e)
            {
                return new SqlPreCommandSimple("-- Exception in {0}: {1}".FormatWith(uc.BaseToString(), e.Message));
            }
            finally
            {
                Console.Clear();
            }
        }
Esempio n. 27
0
        static string AskTypeReplacement(Replacements replacements, string type)
        {
            return(replacements.GetOrCreate("cleanNames").GetOrCreate(type, () =>
            {
                if (Replacements.AutoReplacement != null)
                {
                    Replacements.Selection?sel = Replacements.AutoReplacement(new Replacements.AutoReplacementContext {
                        ReplacementKey = "FixValue.Type", OldValue = type, NewValues = null
                    });

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

                Console.WriteLine("Type {0} has been renamed?".FormatWith(type));

                int startingIndex = 0;
                StringDistance sd = new StringDistance();
                var list = TypeLogic.NameToType.Keys.OrderBy(t => sd.LevenshteinDistance(t, type)).ToList();
                retry:
                int maxElements = Console.LargestWindowHeight - 11;

                list.Skip(startingIndex).Take(maxElements)
                .Select((s, i) => "- {1,2}: {2} ".FormatWith(i + startingIndex == 0 ? ">" : " ", i + startingIndex, s)).ToConsole();
                Console.WriteLine();
                SafeConsole.WriteLineColor(ConsoleColor.White, "- n: None");

                int remaining = list.Count - startingIndex - maxElements;
                if (remaining > 0)
                {
                    SafeConsole.WriteLineColor(ConsoleColor.White, "- +: Show more values ({0} remaining)", remaining);
                }

                while (true)
                {
                    string answer = Console.ReadLine();

                    if (answer == null)
                    {
                        throw new InvalidOperationException("Impossible to synchronize interactively without Console");
                    }

                    answer = answer.ToLower();

                    if (answer == "+" && remaining > 0)
                    {
                        startingIndex += maxElements;
                        goto retry;
                    }

                    if (answer == "n")
                    {
                        return null;
                    }

                    if (int.TryParse(answer, out int option))
                    {
                        return list[option];
                    }

                    Console.WriteLine("Error");
                }
            }));
        }
        private static Dictionary<string, string> AskForReplacementsWithMemory(HashSet<string> newNames, HashSet<string> oldNames, Dictionary<string, string> memory, string replacementKey)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            foreach (var kvp in memory)
            {
                if (oldNames.Contains(kvp.Key) && kvp.Value == null)
                {
                    oldNames.Remove(kvp.Key);
                }
                else if (oldNames.Contains(kvp.Key) && newNames.Contains(kvp.Value))
                {
                    oldNames.Remove(kvp.Key);
                    newNames.Remove(kvp.Value);
                    result.Add(kvp.Key, kvp.Value);
                }
            }

            Replacements rep = new Replacements();

            rep.AskForReplacements(oldNames, newNames, replacementKey);

            var answers = rep.TryGetC(replacementKey);
            if (answers != null)
            {
                result.AddRange(answers);
                memory.SetRange(answers);
            }

            var toDelete = oldNames.Except(newNames);
            if(answers != null)
                toDelete = toDelete.Except(answers.Keys);

            memory.SetRange(toDelete.Select(n => KVP.Create(n, (string)null)));

            return result;
        }
Esempio n. 29
0
        public static ConditionMatch TestConditionMatch(Replacements replacements, Condition condition, Match previousConditionMatch = null)
        {
            var conditionRegex = new Regex(condition.Pattern, condition.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);

            var conditionInput = ReplaceTokens(replacements, condition.InputString);
            if (previousConditionMatch != null)
            {
                conditionInput = ReplaceConditionBackReferences(previousConditionMatch, conditionInput);
            }

            var returnMatch = conditionRegex.Match(conditionInput);

            return new ConditionMatch { Match = returnMatch, ConditionInput = conditionInput };
        }
Esempio n. 30
0
        internal static SqlPreCommand?ProcessEmailTemplate(Replacements replacements, Table table, EmailTemplateEntity et, StringDistance sd)
        {
            Console.Write(".");
            try
            {
                var queryName = QueryLogic.ToQueryName(et.Query.Key);

                QueryDescription qd = QueryLogic.Queries.QueryDescription(queryName);

                using (DelayedConsole.Delay(() => SafeConsole.WriteLineColor(ConsoleColor.White, "EmailTemplate: " + et.Name)))
                    using (DelayedConsole.Delay(() => Console.WriteLine(" Query: " + et.Query.Key)))
                    {
                        if (et.From != null && et.From.Token != null)
                        {
                            QueryTokenEmbedded token = et.From.Token;
                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement, " From", allowRemoveToken: false, allowReCreate: et.Model != null))
                            {
                            case FixTokenResult.Nothing: break;

                            case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(et, e => e.Name == et.Name));

                            case FixTokenResult.SkipEntity: return(null);

                            case FixTokenResult.Fix: et.From.Token = token; break;

                            case FixTokenResult.ReGenerateEntity: return(Regenerate(et, replacements, table));

                            default: break;
                            }
                        }

                        if (et.Recipients.Any(a => a.Token != null))
                        {
                            using (DelayedConsole.Delay(() => Console.WriteLine(" Recipients:")))
                            {
                                foreach (var item in et.Recipients.Where(a => a.Token != null).ToList())
                                {
                                    QueryTokenEmbedded token = item.Token !;
                                    switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement, " Recipient", allowRemoveToken: false, allowReCreate: et.Model != null))
                                    {
                                    case FixTokenResult.Nothing: break;

                                    case FixTokenResult.DeleteEntity: return(table.DeleteSqlSync(et, e => e.Name == et.Name));

                                    case FixTokenResult.RemoveToken: et.Recipients.Remove(item); break;

                                    case FixTokenResult.SkipEntity: return(null);

                                    case FixTokenResult.Fix: item.Token = token; break;

                                    case FixTokenResult.ReGenerateEntity: return(Regenerate(et, replacements, table));

                                    default: break;
                                    }
                                }
                            }
                        }

                        try
                        {
                            foreach (var item in et.Messages)
                            {
                                SynchronizationContext sc = new SynchronizationContext(replacements, sd, qd, et.Model?.ToType());

                                item.Subject = TextTemplateParser.Synchronize(item.Subject, sc);
                                item.Text    = TextTemplateParser.Synchronize(item.Text, sc);
                            }

                            using (replacements.WithReplacedDatabaseName())
                                return(table.UpdateSqlSync(et, e => e.Name == et.Name, includeCollections: true, comment: "EmailTemplate: " + et.Name));
                        }
                        catch (TemplateSyncException ex)
                        {
                            if (ex.Result == FixTokenResult.SkipEntity)
                            {
                                return(null);
                            }

                            if (ex.Result == FixTokenResult.DeleteEntity)
                            {
                                return(table.DeleteSqlSync(et, e => e.Name == et.Name));
                            }

                            if (ex.Result == FixTokenResult.ReGenerateEntity)
                            {
                                return(Regenerate(et, replacements, table));
                            }

                            throw new UnexpectedValueException(ex.Result);
                        }
                    }
            }
            catch (Exception e)
            {
                return(new SqlPreCommandSimple("-- Exception on {0}. {1}\r\n{2}".FormatWith(et.BaseToString(), e.GetType().Name, e.Message.Indent(2, '-'))));
            }
        }
        /// <summary>
        /// Returns an IDisposable LocalWrapper that will render the open tag upon opening, and a close tag upon closing
        /// </summary>
        /// <returns>returns a LocalWrapper containing the rendered tag</returns>
        public LocalWrapper Open()
        {
            if (!(IsDisplayed || DebugMode))
            {
                return(new LocalWrapper(null, _context));
            }

            var builder = new TagBuilder(TagName);

            foreach (var attribute in LocalizedAttributes)
            {
                var value = Repository.GetQualified(attribute.Value.Key, attribute.Value.Default);
                builder.MergeAttribute(attribute.Key, Processors.Aggregate(
                                           value.Value.DecodeWithReplacements(Replacements),
                                           (val, processor) => processor(val)
                                           ));

                if (!DebugMode)
                {
                    continue;
                }
                builder.MergeAttribute("data-loc-debug", "true");
                var key = "data-loc-attribute-" + attribute.Key + "-";
                builder.MergeAttribute(key + "part", value.Qualifier.Part.ToString());
                builder.MergeAttribute(key + "content", value.Value.Content);
            }

            if (DebugMode)
            {
                if (LocalizedAttributes.Any())
                {
                    var localizations = String.Join(((char)31).ToString(CultureInfo.InvariantCulture), LocalizedAttributes.Select(localization => localization.Key + (char)30 + localization.Value));
                    builder.MergeAttribute("data-loc-localizations", localizations);
                }

                if (Replacements.Any())
                {
                    var replacements = String.Join(((char)31).ToString(CultureInfo.InvariantCulture), Replacements.Select(replacement => replacement.Key + (char)30 + replacement.Value));
                    builder.MergeAttribute("data-loc-replacements", replacements);
                }
            }

            foreach (var attribute in OtherAttributes)
            {
                builder.MergeAttribute(attribute.Key, attribute.Value);
            }

            return(new LocalWrapper(builder, _context));
        }
Esempio n. 32
0
        internal SqlPreCommand?ImportXml(XElement element, Dictionary <string, Lite <RoleEntity> > roles, Replacements replacements)
        {
            var current = Database.RetrieveAll <RuleTypeEntity>().GroupToDictionary(a => a.Role);
            var xRoles  = (element.Element("Types")?.Elements("Role")).EmptyIfNull();
            var should  = xRoles.ToDictionary(x => roles.GetOrThrow(x.Attribute("Name").Value));

            Table table = Schema.Current.Table(typeof(RuleTypeEntity));

            replacements.AskForReplacements(
                xRoles.SelectMany(x => x.Elements("Type")).Select(x => x.Attribute("Resource").Value).ToHashSet(),
                TypeLogic.NameToType.Where(a => !a.Value.IsEnumEntity()).Select(a => a.Key).ToHashSet(), typeReplacementKey);

            replacements.AskForReplacements(
                xRoles.SelectMany(x => x.Elements("Type")).SelectMany(t => t.Elements("Condition")).Select(x => x.Attribute("Name").Value).ToHashSet(),
                SymbolLogic <TypeConditionSymbol> .AllUniqueKeys(),
                typeConditionReplacementKey);

            Func <string, TypeEntity?> getResource = s =>
            {
                Type?type = TypeLogic.NameToType.TryGetC(replacements.Apply(typeReplacementKey, s));

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

                return(TypeLogic.TypeToEntity.GetOrThrow(type));
            };


            return(Synchronizer.SynchronizeScript(Spacing.Double, should, current,
                                                  createNew: (role, x) =>
            {
                var dic = (from xr in x.Elements("Type")
                           let t = getResource(xr.Attribute("Resource").Value)
                                   where t != null
                                   select KVP.Create(t, new
                {
                    Allowed = xr.Attribute("Allowed").Value.ToEnum <TypeAllowed>(),
                    Condition = Conditions(xr, replacements)
                })).ToDictionaryEx("Type rules for {0}".FormatWith(role));

                SqlPreCommand?restSql = dic.Select(kvp => table.InsertSqlSync(new RuleTypeEntity
                {
                    Resource = kvp.Key,
                    Role = role,
                    Allowed = kvp.Value.Allowed,
                    Conditions = kvp.Value.Condition !    /*CSBUG*/
                }, comment: Comment(role, kvp.Key, kvp.Value.Allowed))).Combine(Spacing.Simple)?.Do(p => p.GoBefore = true);
 public string ReplaceManyDictionaryAggregate() =>
 Replacements.Aggregate(Text, (current, kvp) => current.Replace(kvp.Key, kvp.Value));
Esempio n. 34
0
        static SqlPreCommand SynchronizeQueries(Replacements replacements)
        {
            var should = GenerateQueries();

            var current = Administrator.TryRetrieveAll<QueryEntity>(replacements);

            Table table = Schema.Current.Table<QueryEntity>();

            using (replacements.WithReplacedDatabaseName())
                return Synchronizer.SynchronizeScriptReplacing(
                    replacements,
                    QueriesKey,
                    should.ToDictionary(a => a.Key, "query in memory"),
                    current.ToDictionary(a => a.Key, "query in database"),
                    (n, s) => table.InsertSqlSync(s),
                    (n, c) => table.DeleteSqlSync(c),
                    (fn, s, c) =>
                    {
                        c.Key = s.Key;
                        c.Name = s.Name;
                        return table.UpdateSqlSync(c);
                    }, Spacing.Double);
        }
        static bool TryParseRemember(Replacements replacements, string tokenString, QueryDescription qd, SubTokensOptions options, out QueryToken result)
        {
            string[] parts = tokenString.Split('.');

            result = null;
            for (int i = 0; i < parts.Length; i++)
            {
                string part = parts[i];

                QueryToken newResult = QueryUtils.SubToken(result, qd, options, part);

                if (newResult != null)
                {
                    result = newResult;
                }
                else
                {
                    if (i == 0)
                    {
                        var entity = QueryUtils.SubToken(result, qd, options, "Entity");
                        QueryToken newSubResult = QueryUtils.SubToken(entity, qd, options, part);

                        if (newSubResult != null)
                        {
                            result = newSubResult;
                            continue;
                        }
                    }


                    if (Replacements.AutoReplacement != null)
                    {
                        Replacements.Selection? sel = Replacements.AutoReplacement(part, result.SubTokens(qd, options).Select(a => a.Key).ToList());

                        if (sel != null && sel.Value.NewValue != null)
                        {
                            newResult = QueryUtils.SubToken(result, qd, options, sel.Value.NewValue);

                            if (newResult != null)
                            {
                                result = newResult;
                                continue;
                            }
                        }
                    }

                    string key = result == null ? QueryKey(qd.QueryName) : TypeKey(result.Type);

                    Dictionary<string, string> dic = replacements.TryGetC(key);

                    if (dic == null)
                        return false;

                    string remainging = parts.Skip(i).ToString(".");

                    string old = dic.Keys.OrderByDescending(a => a.Length).FirstOrDefault(s => remainging.StartsWith(s));

                    if (old == null)
                        return false;

                    var subParts = dic[old].Let(s => s.HasText() ? s.Split('.') : new string[0]);

                    for (int j = 0; j < subParts.Length; j++)
                    {
                        string subPart = subParts[j];

                        QueryToken subNewResult = QueryUtils.SubToken(result, qd, options, subPart);

                        if (subNewResult == null)
                            return false;

                        result = subNewResult;
                    }

                    i += (old == "" ? 0 : old.Split('.').Length) - 1;
                }
            }

            return true;
        }
        private static SqlPreCommand AlterTableAddColumnDefault(ITable table, IColumn column, Replacements rep)
        {
            bool temporalDefault = !column.Nullable && !column.Identity && column.Default == null;

            if (!temporalDefault)
                return SqlBuilder.AlterTableAddColumn(table, column);

            string defaultValue = rep.Interactive ? SafeConsole.AskString("Default value for '{0}.{1}'? (or press enter) ".FormatWith(table.Name.Name, column.Name), stringValidator: str => null) : "";
            if (defaultValue == "null")
                return SqlBuilder.AlterTableAddColumn(table, column);

            try
            {
                column.Default = defaultValue;

                if (column.Default.HasText() && SqlBuilder.IsString(column.SqlDbType) && !column.Default.Contains("'"))
                    column.Default = "'" + column.Default + "'";

                if (string.IsNullOrEmpty(column.Default))
                    column.Default = SqlBuilder.IsNumber(column.SqlDbType) ? "0" :
                        SqlBuilder.IsString(column.SqlDbType) ? "''" :
                        SqlBuilder.IsDate(column.SqlDbType) ? "GetDate()" :
                        "?";

                return SqlPreCommand.Combine(Spacing.Simple,
                    SqlBuilder.AlterTableAddColumn(table, column),
                    SqlBuilder.DropDefaultConstraint(table.Name, column.Name));
            }
            finally
            {
                column.Default = null;
            }
        }
        private static SqlPreCommand Regenerate(WordTemplateEntity template, Replacements replacements)
        {
            var newTemplate = SystemWordTemplateLogic.CreateDefaultTemplate(template.SystemWordTemplate);

            var file = template.Template.Retrieve();

            using (file.AllowChanges())
            {
                file.BinaryFile = newTemplate.Template.Entity.BinaryFile;
                file.FileName = newTemplate.Template.Entity.FileName;

                return Schema.Current.Table<FileEntity>().UpdateSqlSync(file, comment: "WordTemplate Regenerated: " + template.Name);
            }
        }
        public static SqlPreCommand SnapshotIsolation(Replacements replacements)
        {
            if (replacements.SchemaOnly)
                return null;

            var list = Schema.Current.DatabaseNames().Select(a => a?.ToString()).ToList();

            if (list.Contains(null))
            {
                list.Remove(null);
                list.Add(Connector.Current.DatabaseName());
            }

            var results = Database.View<SysDatabases>()
                .Where(d => list.Contains(d.name))
                .Select(d => new { d.name, d.snapshot_isolation_state, d.is_read_committed_snapshot_on }).ToList();

            var cmd = replacements.WithReplacedDatabaseName().Using(_ => results.Select((a, i) =>
                SqlPreCommand.Combine(Spacing.Simple,
                !a.snapshot_isolation_state || !a.is_read_committed_snapshot_on ? DisconnectUsers(a.name, "SPID" + i) : null,
                !a.snapshot_isolation_state ? SqlBuilder.SetSnapshotIsolation(a.name, true) : null,
                !a.is_read_committed_snapshot_on ? SqlBuilder.MakeSnapshotIsolationDefault(a.name, true) : null)).Combine(Spacing.Double));

            if (cmd == null)
                return null;

            return SqlPreCommand.Combine(Spacing.Double,
                new SqlPreCommandSimple("use master -- Start Snapshot"),
                cmd,
                new SqlPreCommandSimple("use {0} -- Stop Snapshot".FormatWith(Connector.Current.DatabaseName())));
        }
        public static SqlPreCommand SynchronizeTablesScript(Replacements replacements)
        {
            Schema s = Schema.Current;

            Dictionary<string, ITable> model = s.GetDatabaseTables().Where(t => !s.IsExternalDatabase(t.Name.Schema.Database)).ToDictionaryEx(a => a.Name.ToString(), "schema tables");
            HashSet<SchemaName> modelSchemas = model.Values.Select(a => a.Name.Schema).Where(a => !SqlBuilder.SystemSchemas.Contains(a.Name)).ToHashSet();

            Dictionary<string, DiffTable> database = DefaultGetDatabaseDescription(s.DatabaseNames());
            HashSet<SchemaName> databaseSchemas = DefaultGetSchemas(s.DatabaseNames());

            if (SimplifyDiffTables != null) 
                SimplifyDiffTables(database);

            replacements.AskForReplacements(database.Keys.ToHashSet(), model.Keys.ToHashSet(), Replacements.KeyTables);

            database = replacements.ApplyReplacementsToOld(database, Replacements.KeyTables);

            Dictionary<ITable, Dictionary<string, Index>> modelIndices = model.Values
                .ToDictionary(t => t, t => t.GeneratAllIndexes().ToDictionaryEx(a => a.IndexName, "Indexes for {0}".FormatWith(t.Name)));

            model.JoinDictionaryForeach(database, (tn, tab, diff) =>
            {
                var key = Replacements.KeyColumnsForTable(tn);

                replacements.AskForReplacements(diff.Columns.Keys.ToHashSet(), tab.Columns.Keys.ToHashSet(), key);

                diff.Columns = replacements.ApplyReplacementsToOld(diff.Columns, key);

                diff.Indices = ApplyIndexAutoReplacements(diff, tab, modelIndices[tab]);
            });

            Func<ObjectName, ObjectName> ChangeName = (ObjectName objectName) =>
            {
                string name = replacements.Apply(Replacements.KeyTables, objectName.ToString());

                return model.TryGetC(name)?.Name ?? objectName;
            };


            Func<ObjectName, SqlPreCommand> DeleteAllForeignKey = tableName =>
            {
                var dropFks = (from t in database.Values
                               from c in t.Columns.Values
                               where c.ForeignKey != null && c.ForeignKey.TargetTable.Equals(tableName)
                               select SqlBuilder.AlterTableDropConstraint(t.Name, c.ForeignKey.Name)).Combine(Spacing.Simple);

                if (dropFks == null)
                    return null;

                return SqlPreCommand.Combine(Spacing.Simple, new SqlPreCommandSimple("---In order to remove the PK of " + tableName.Name), dropFks);
            };

            using (replacements.WithReplacedDatabaseName())
            {
                SqlPreCommand createSchemas = Synchronizer.SynchronizeScriptReplacing(replacements, "Schemas",
                    modelSchemas.ToDictionary(a => a.ToString()),
                    databaseSchemas.ToDictionary(a => a.ToString()),
                    (_, newSN) => SqlBuilder.CreateSchema(newSN),
                    null,
                    (_, newSN, oldSN) => newSN.Equals(oldSN) ? null : SqlBuilder.CreateSchema(newSN),
                    Spacing.Double);

                //use database without replacements to just remove indexes
                SqlPreCommand dropStatistics =
                    Synchronizer.SynchronizeScript(model, database,
                     null,
                    (tn, dif) => SqlBuilder.DropStatistics(tn, dif.Stats),
                    (tn, tab, dif) =>
                    {
                        var removedColums = dif.Columns.Keys.Except(tab.Columns.Keys).ToHashSet();

                        return SqlBuilder.DropStatistics(tn, dif.Stats.Where(a => a.Columns.Any(removedColums.Contains)).ToList());
                    },
                     Spacing.Double);
                
                SqlPreCommand dropIndices =
                    Synchronizer.SynchronizeScript(model, database,
                     null,
                    (tn, dif) => dif.Indices.Values.Where(ix => !ix.IsPrimary).Select(ix => SqlBuilder.DropIndex(dif.Name, ix)).Combine(Spacing.Simple),
                    (tn, tab, dif) =>
                    {
                        Dictionary<string, Index> modelIxs = modelIndices[tab];

                        var removedColums = dif.Columns.Keys.Except(tab.Columns.Keys).ToHashSet();

                        var changes = Synchronizer.SynchronizeScript(modelIxs, dif.Indices,
                            null,
                            (i, dix) => dix.Columns.Any(removedColums.Contains) || dix.IsControlledIndex ? SqlBuilder.DropIndex(dif.Name, dix) : null,
                            (i, mix, dix) => !dix.IndexEquals(dif, mix) ? SqlPreCommand.Combine(Spacing.Double, dix.IsPrimary ? DeleteAllForeignKey(dif.Name) : null, SqlBuilder.DropIndex(dif.Name, dix)) : null,
                            Spacing.Simple);

                        return changes;
                    },
                     Spacing.Double);

                SqlPreCommand dropForeignKeys = Synchronizer.SynchronizeScript(
                     model,
                     database,
                     null,
                     (tn, dif) => dif.Columns.Values.Select(c => c.ForeignKey != null ? SqlBuilder.AlterTableDropConstraint(dif.Name, c.ForeignKey.Name) : null)
                         .Concat(dif.MultiForeignKeys.Select(fk => SqlBuilder.AlterTableDropConstraint(dif.Name, fk.Name))).Combine(Spacing.Simple),
                     (tn, tab, dif) => SqlPreCommand.Combine(Spacing.Simple,
                         Synchronizer.SynchronizeScript(
                         tab.Columns,
                         dif.Columns,
                         null,
                         (cn, colDb) => colDb.ForeignKey != null ? SqlBuilder.AlterTableDropConstraint(dif.Name, colDb.ForeignKey.Name) : null,
                         (cn, colModel, colDb) => colDb.ForeignKey == null ? null :
                             colModel.ReferenceTable == null || colModel.AvoidForeignKey || !colModel.ReferenceTable.Name.Equals(ChangeName(colDb.ForeignKey.TargetTable)) ?
                             SqlBuilder.AlterTableDropConstraint(dif.Name, colDb.ForeignKey.Name) :
                             null, Spacing.Simple),
                        dif.MultiForeignKeys.Select(fk => SqlBuilder.AlterTableDropConstraint(dif.Name, fk.Name)).Combine(Spacing.Simple)),
                        Spacing.Double);

                SqlPreCommand tables =
                    Synchronizer.SynchronizeScript(
                    model,
                    database,
                    (tn, tab) => SqlBuilder.CreateTableSql(tab),
                    (tn, dif) => SqlBuilder.DropTable(dif.Name),
                    (tn, tab, dif) =>
                        SqlPreCommand.Combine(Spacing.Simple,
                        !object.Equals(dif.Name, tab.Name) ? SqlBuilder.RenameOrMove(dif, tab) : null,
                        Synchronizer.SynchronizeScript(
                            tab.Columns,
                            dif.Columns,
                            (cn, tabCol) => SqlPreCommandSimple.Combine(Spacing.Simple,
                                tabCol.PrimaryKey && dif.PrimaryKeyName != null ? SqlBuilder.DropPrimaryKeyConstraint(tab.Name) : null,
                                AlterTableAddColumnDefault(tab, tabCol, replacements)),
                            (cn, difCol) => SqlPreCommandSimple.Combine(Spacing.Simple,
                                 difCol.Default != null ? SqlBuilder.DropDefaultConstraint(tab.Name, difCol.Name) : null,
                                SqlBuilder.AlterTableDropColumn(tab, cn)),
                            (cn, tabCol, difCol) => SqlPreCommand.Combine(Spacing.Simple,
                                difCol.Name == tabCol.Name ? null : SqlBuilder.RenameColumn(tab, difCol.Name, tabCol.Name),
                                difCol.ColumnEquals(tabCol, ignorePrimaryKey: true) ? null : SqlPreCommand.Combine(Spacing.Simple,
                                    tabCol.PrimaryKey && !difCol.PrimaryKey && dif.PrimaryKeyName != null ? SqlBuilder.DropPrimaryKeyConstraint(tab.Name) : null,
                                    SqlBuilder.AlterTableAlterColumn(tab, tabCol),
                                    tabCol.SqlDbType == SqlDbType.NVarChar && difCol.SqlDbType == SqlDbType.NChar ? SqlBuilder.UpdateTrim(tab, tabCol) : null),
                                difCol.DefaultEquals(tabCol) ? null : SqlPreCommand.Combine(Spacing.Simple,
                                    difCol.Default != null ? SqlBuilder.DropDefaultConstraint(tab.Name, tabCol.Name) : null,
                                    tabCol.Default != null ? SqlBuilder.AddDefaultConstraint(tab.Name, tabCol.Name, tabCol.Default) : null),
                                UpdateByFkChange(tn, difCol, tabCol, ChangeName)),
                            Spacing.Simple)),
                     Spacing.Double);

                if (tables != null)
                    tables.GoAfter = true;

                var tableReplacements = replacements.TryGetC(Replacements.KeyTables);
                if (tableReplacements != null)
                    replacements[Replacements.KeyTablesInverse] = tableReplacements.Inverse();

                SqlPreCommand syncEnums;

                try
                {
                    syncEnums = SynchronizeEnumsScript(replacements);
                }
                catch(Exception e)
                {
                    syncEnums = new SqlPreCommandSimple("-- Exception synchronizing enums: " + e.Message);
                }

                SqlPreCommand addForeingKeys = Synchronizer.SynchronizeScript(
                     model,
                     database,
                     (tn, tab) => SqlBuilder.AlterTableForeignKeys(tab),
                     null,
                     (tn, tab, dif) => Synchronizer.SynchronizeScript(
                         tab.Columns,
                         dif.Columns,
                         (cn, colModel) => colModel.ReferenceTable == null || colModel.AvoidForeignKey ? null :
                             SqlBuilder.AlterTableAddConstraintForeignKey(tab, colModel.Name, colModel.ReferenceTable),
                         null,
                         (cn, colModel, coldb) =>
                         {
                             if (colModel.ReferenceTable == null || colModel.AvoidForeignKey)
                                 return null;

                             if (coldb.ForeignKey == null || !colModel.ReferenceTable.Name.Equals(ChangeName(coldb.ForeignKey.TargetTable)))
                                 return SqlBuilder.AlterTableAddConstraintForeignKey(tab, colModel.Name, colModel.ReferenceTable);

                             var name = SqlBuilder.ForeignKeyName(tab.Name.Name, colModel.Name);
                             return SqlPreCommand.Combine(Spacing.Simple,
                                name != coldb.ForeignKey.Name.Name ? SqlBuilder.RenameForeignKey(coldb.ForeignKey.Name, name) : null,
                                (coldb.ForeignKey.IsDisabled || coldb.ForeignKey.IsNotTrusted) && !replacements.SchemaOnly ? SqlBuilder.EnableForeignKey(tab.Name, name) : null);
                         },
                         Spacing.Simple),
                     Spacing.Double);

                bool? createMissingFreeIndexes = null;

                SqlPreCommand addIndices =
                    Synchronizer.SynchronizeScript(model, database,
                     (tn, tab) => modelIndices[tab].Values.Where(a => !(a is PrimaryClusteredIndex)).Select(SqlBuilder.CreateIndex).Combine(Spacing.Simple),
                     null,
                    (tn, tab, dif) =>
                    {
                        var columnReplacements = replacements.TryGetC(Replacements.KeyColumnsForTable(tn));

                        Func<IColumn, bool> isNew = c => !dif.Columns.ContainsKey(columnReplacements?.TryGetC(c.Name) ?? c.Name);

                        Dictionary<string, Index> modelIxs = modelIndices[tab];

                        var controlledIndexes = Synchronizer.SynchronizeScript(modelIxs, dif.Indices,
                            (i, mix) => mix is UniqueIndex || mix.Columns.Any(isNew) || SafeConsole.Ask(ref createMissingFreeIndexes, "Create missing non-unique index {0} in {1}?".FormatWith(mix.IndexName, tab.Name)) ? SqlBuilder.CreateIndex(mix) : null,
                            null,
                            (i, mix, dix) => !dix.IndexEquals(dif, mix) ? SqlBuilder.CreateIndex(mix) :
                                mix.IndexName != dix.IndexName ? SqlBuilder.RenameIndex(tab, dix.IndexName, mix.IndexName) : null,
                            Spacing.Simple);

                        return SqlPreCommand.Combine(Spacing.Simple, controlledIndexes);
                    }, Spacing.Double);

                SqlPreCommand dropSchemas = Synchronizer.SynchronizeScriptReplacing(replacements, "Schemas",
                  modelSchemas.ToDictionary(a => a.ToString()),
                  databaseSchemas.ToDictionary(a => a.ToString()),
                  null,
                  (_, oldSN) => DropSchema(oldSN) ? SqlBuilder.DropSchema(oldSN) : null,
                  (_, newSN, oldSN) => newSN.Equals(oldSN) ? null : SqlBuilder.DropSchema(oldSN),
                  Spacing.Double);

                return SqlPreCommand.Combine(Spacing.Triple, createSchemas, dropStatistics, dropIndices, dropForeignKeys, tables, syncEnums, addForeingKeys, addIndices, dropSchemas);
            }
        }
        public string ToHtmlString()
        {
            if (!(IsDisplayed || DebugMode))
            {
                return(String.Empty);
            }

            var builder = new TagBuilder(TagName);

            var            innerHtml      = String.Empty;
            QualifiedValue innerHtmlValue = null;

            if (!String.IsNullOrEmpty(LocalizedHtmlKey.Key))
            {
                innerHtmlValue = Repository.GetQualified(LocalizedHtmlKey.Key, LocalizedHtmlKey.Default);
                var decodedValue = Processors.Aggregate(
                    innerHtmlValue.Value.DecodeWithReplacements(Replacements),
                    (value, processor) => processor(value)
                    );
                builder.InnerHtml = decodedValue;
            }

            foreach (var attribute in LocalizedAttributes)
            {
                var value = Repository.GetQualified(attribute.Value.Key, attribute.Value.Default);
                builder.MergeAttribute(attribute.Key, Processors.Aggregate(
                                           value.Value.DecodeWithReplacements(Replacements),
                                           (val, processor) => processor(val)
                                           ));

                if (!DebugMode)
                {
                    continue;
                }
                var key = "data-loc-attribute-" + attribute.Key + "-";
                builder.MergeAttribute(key + "part", value.Qualifier.Part.ToString());
                builder.MergeAttribute(key + "content", value.Value.Content);
            }

            if (DebugMode)
            {
                builder.MergeAttribute("data-loc-debug", "true");

                if (innerHtmlValue != null)
                {
                    builder.MergeAttribute("data-loc-inner-part", innerHtmlValue.Qualifier.Part.ToString());
                    builder.MergeAttribute("data-loc-inner-key", innerHtmlValue.Qualifier.Key);
                    builder.MergeAttribute("data-loc-inner-value", innerHtmlValue.Value.Content);
                }

                if (LocalizedAttributes.Any())
                {
                    var localizations = String.Join(((char)31).ToString(CultureInfo.InvariantCulture), LocalizedAttributes.Select(localization => localization.Key + (char)30 + localization.Value));
                    builder.MergeAttribute("data-loc-localizations", localizations);
                }

                if (Replacements.Any())
                {
                    var replacements = String.Join(((char)31).ToString(CultureInfo.InvariantCulture), Replacements.Select(replacement => replacement.Key + (char)30 + replacement.Value));
                    builder.MergeAttribute("data-loc-replacements", replacements);
                }
            }

            if (!String.IsNullOrEmpty(OtherHtml))
            {
                innerHtml += OtherHtml;
            }
            if (!String.IsNullOrEmpty(innerHtml))
            {
                builder.InnerHtml = innerHtml;
            }

            foreach (var attribute in OtherAttributes)
            {
                builder.MergeAttribute(attribute.Key, attribute.Value);
            }

            return(builder.ToString());
        }
        static SqlPreCommand SynchronizeEnumsScript(Replacements replacements)
        {
            Schema schema = Schema.Current;

            List<SqlPreCommand> commands = new List<SqlPreCommand>();

            foreach (var table in schema.Tables.Values)
            {
                Type enumType = EnumEntity.Extract(table.Type);
                if (enumType != null)
                {
                    IEnumerable<Entity> should = EnumEntity.GetEntities(enumType);
                    Dictionary<string, Entity> shouldByName = should.ToDictionary(a => a.ToString());

                    List<Entity> current = Administrator.TryRetrieveAll(table.Type, replacements);
                    Dictionary<string, Entity> currentByName = current.ToDictionaryEx(a => a.toStr, table.Name.Name);

                    string key = Replacements.KeyEnumsForTable(table.Name.Name);

                    replacements.AskForReplacements(currentByName.Keys.ToHashSet(), shouldByName.Keys.ToHashSet(), key);

                    currentByName = replacements.ApplyReplacementsToOld(currentByName, key);

                    var mix = shouldByName.JoinDictionary(currentByName, (n, s, c) => new { s, c }).Where(a => a.Value.s.id != a.Value.c.id).ToDictionary();

                    HashSet<PrimaryKey> usedIds = current.Select(a => a.Id).ToHashSet();

                    Dictionary<string, Entity> middleByName = mix.Where(kvp => usedIds.Contains(kvp.Value.s.Id)).ToDictionary(kvp => kvp.Key, kvp => Clone(kvp.Value.c));

                    if (middleByName.Any())
                    {
                        var moveToAux = SyncEnums(schema, table, 
                            currentByName.Where(a => middleByName.ContainsKey(a.Key)).ToDictionary(), 
                            middleByName);
                        if (moveToAux != null)
                            commands.Add(moveToAux);
                    }

                    var com = SyncEnums(schema, table, 
                        currentByName.Where(a=>!middleByName.ContainsKey(a.Key)).ToDictionary(), 
                        shouldByName.Where(a=>!middleByName.ContainsKey(a.Key)).ToDictionary());
                    if (com != null)
                        commands.Add(com);

                    if (middleByName.Any())
                    {
                        var backFromAux = SyncEnums(schema, table, 
                            middleByName,
                            shouldByName.Where(a => middleByName.ContainsKey(a.Key)).ToDictionary());
                        if (backFromAux != null)
                            commands.Add(backFromAux);
                    }
                }
            }

            return SqlPreCommand.Combine(Spacing.Double, commands.ToArray());
        }
Esempio n. 42
0
        static bool TryParseRemember(Replacements replacements, string tokenString, QueryDescription qd, SubTokensOptions options, out QueryToken result)
        {
            string[] parts = tokenString.Split('.');

            result = null;
            for (int i = 0; i < parts.Length; i++)
            {
                string part = parts[i];

                QueryToken newResult = QueryUtils.SubToken(result, qd, options, part);

                if (newResult != null)
                {
                    result = newResult;
                }
                else
                {
                    if (i == 0)
                    {
                        var        entity       = QueryUtils.SubToken(result, qd, options, "Entity");
                        QueryToken newSubResult = QueryUtils.SubToken(entity, qd, options, part);

                        if (newSubResult != null)
                        {
                            result = newSubResult;
                            continue;
                        }
                    }


                    if (Replacements.AutoReplacement != null)
                    {
                        Replacements.Selection?sel = Replacements.AutoReplacement(new Replacements.AutoReplacementContext {
                            ReplacementKey = "QueryToken", OldValue = part, NewValues = result.SubTokens(qd, options).Select(a => a.Key).ToList()
                        });

                        if (sel != null && sel.Value.NewValue != null)
                        {
                            newResult = QueryUtils.SubToken(result, qd, options, sel.Value.NewValue);

                            if (newResult != null)
                            {
                                result = newResult;
                                continue;
                            }
                        }
                    }

                    string key = result == null?QueryKey(qd.QueryName) : TypeKey(result.Type);

                    Dictionary <string, string> dic = replacements.TryGetC(key);

                    if (dic == null)
                    {
                        return(false);
                    }

                    string remainging = parts.Skip(i).ToString(".");

                    string old = dic.Keys.OrderByDescending(a => a.Length).FirstOrDefault(s => remainging.StartsWith(s));

                    if (old == null)
                    {
                        return(false);
                    }

                    var subParts = dic[old].Let(s => s.HasText() ? s.Split('.') : new string[0]);

                    for (int j = 0; j < subParts.Length; j++)
                    {
                        string subPart = subParts[j];

                        QueryToken subNewResult = QueryUtils.SubToken(result, qd, options, subPart);

                        if (subNewResult == null)
                        {
                            return(false);
                        }

                        result = subNewResult;
                    }

                    i += (old == "" ? 0 : old.Split('.').Length) - 1;
                }
            }

            return(true);
        }
Esempio n. 43
0
        public static FixTokenResult FixValue(Replacements replacements, Type type, ref string valueString, bool allowRemoveToken, bool isList)
        {
            string error = FilterValueConverter.TryParse(valueString, type, out object val, isList);

            if (error == null)
            {
                return(FixTokenResult.Nothing);
            }

            if (isList && valueString.Contains('|'))
            {
                List <string> changes = new List <string>();
                foreach (var str in valueString.Split('|'))
                {
                    string s      = str;
                    var    result = FixValue(replacements, type, ref s, allowRemoveToken, false);

                    if (result == FixTokenResult.DeleteEntity || result == FixTokenResult.SkipEntity || result == FixTokenResult.RemoveToken)
                    {
                        return(result);
                    }

                    changes.Add(s);
                }

                valueString = changes.ToString("|");
                return(FixTokenResult.Fix);
            }

            if (type.IsLite())
            {
                var m = Lite.ParseRegex.Match(valueString);
                if (m.Success)
                {
                    var typeString = m.Groups["type"].Value;

                    if (!TypeLogic.NameToType.ContainsKey(typeString))
                    {
                        string newTypeString = AskTypeReplacement(replacements, typeString);

                        if (newTypeString.HasText())
                        {
                            valueString = valueString.Replace(typeString, newTypeString);
                            return(FixTokenResult.Fix);
                        }
                    }
                }
            }

            if (Replacements.AutoReplacement != null)
            {
                Replacements.Selection?sel = Replacements.AutoReplacement(new Replacements.AutoReplacementContext {
                    ReplacementKey = "FixValue", OldValue = valueString, NewValues = null
                });

                if (sel != null && sel.Value.NewValue != null)
                {
                    valueString = sel.Value.NewValue;
                    return(FixTokenResult.Fix);
                }
            }

            SafeConsole.WriteLineColor(ConsoleColor.White, "Value '{0}' not convertible to {1}.".FormatWith(valueString, type.TypeName()));
            SafeConsole.WriteLineColor(ConsoleColor.Yellow, "- s: Skip entity");
            if (allowRemoveToken)
            {
                SafeConsole.WriteLineColor(ConsoleColor.DarkRed, "- r: Remove token");
            }
            SafeConsole.WriteLineColor(ConsoleColor.Red, "- d: Delete entity");
            SafeConsole.WriteLineColor(ConsoleColor.Green, "- freeText: New value");

            string answer = Console.ReadLine();

            if (answer == null)
            {
                throw new InvalidOperationException("Impossible to synchronize interactively without Console");
            }

            string a = answer.ToLower();

            if (a == "s")
            {
                return(FixTokenResult.SkipEntity);
            }

            if (allowRemoveToken && a == "r")
            {
                return(FixTokenResult.RemoveToken);
            }

            if (a == "d")
            {
                return(FixTokenResult.DeleteEntity);
            }

            valueString = answer;
            return(FixTokenResult.Fix);
        }
Esempio n. 44
0
        internal static SqlPreCommand Regenerate(EmailTemplateEntity et, Replacements replacements, Table table)
        {
            var newTemplate = SystemEmailLogic.CreateDefaultTemplate(et.SystemEmail);

            newTemplate.SetId(et.IdOrNull);
            newTemplate.SetNew(false);
            newTemplate.Ticks = et.Ticks; 

            using (replacements == null ? null : replacements.WithReplacedDatabaseName())
                return table.UpdateSqlSync(newTemplate, includeCollections: true, comment: "EmailTemplate Regenerated: " + et.Name);
        }
Esempio n. 45
0
        public static FixTokenResult FixToken(Replacements replacements, string original, out QueryToken token, QueryDescription qd, SubTokensOptions options, string remainingText, bool allowRemoveToken, bool allowReGenerate)
        {
            string[] parts = original.Split('.');

            if (TryParseRemember(replacements, original, qd, options, out QueryToken current))
            {
                if (current.FullKey() != original)
                {
                    SafeConsole.WriteColor(ConsoleColor.DarkRed, "  " + original);
                    Console.Write(" -> ");
                    SafeConsole.WriteColor(ConsoleColor.DarkGreen, current.FullKey());
                }
                Console.WriteLine(remainingText);
                token = current;
                return(FixTokenResult.Fix);
            }

            while (true)
            {
                var result = SelectInteractive(ref current, qd, options, remainingText, allowRemoveToken, allowReGenerate);
                switch (result)
                {
                case UserAssetTokenAction.DeleteEntity:
                    SafeConsole.WriteLineColor(ConsoleColor.Red, "Entity deleted");
                    token = null;
                    return(FixTokenResult.DeleteEntity);

                case UserAssetTokenAction.ReGenerateEntity:
                    if (!allowReGenerate)
                    {
                        throw new InvalidOperationException("Unexpected ReGenerate");
                    }

                    SafeConsole.WriteLineColor(ConsoleColor.Magenta, "Entity Re-Generated");
                    token = null;
                    return(FixTokenResult.ReGenerateEntity);

                case UserAssetTokenAction.RemoveToken:
                    if (!allowRemoveToken)
                    {
                        throw new InvalidOperationException("Unexpected RemoveToken");
                    }

                    Console.SetCursorPosition(0, Console.CursorTop - 1);
                    SafeConsole.WriteColor(ConsoleColor.DarkRed, "  " + original);
                    SafeConsole.WriteColor(ConsoleColor.DarkRed, " (token removed)");
                    Console.WriteLine(remainingText);
                    token = null;
                    return(FixTokenResult.RemoveToken);

                case UserAssetTokenAction.SkipEntity:
                    SafeConsole.WriteLineColor(ConsoleColor.DarkYellow, "Entity skipped");
                    token = null;
                    return(FixTokenResult.SkipEntity);

                case UserAssetTokenAction.Confirm:
                    Remember(replacements, original, current);
                    Console.SetCursorPosition(0, Console.CursorTop - 1);
                    SafeConsole.WriteColor(ConsoleColor.DarkRed, "  " + original);
                    Console.Write(" -> ");
                    SafeConsole.WriteColor(ConsoleColor.DarkGreen, current.FullKey());
                    Console.WriteLine(remainingText);
                    token = current;
                    return(FixTokenResult.Fix);
                }
            }
        }
Esempio n. 46
0
        public static ConditionMatchResult TestConditionMatches(IConditionsProperties rule, Replacements replacements, out Match lastConditionMatch)
        {
            var conditionMatchResult = new ConditionMatchResult();
            bool conditionMatches;
            lastConditionMatch = null;

            var conditionLogicalGrouping = rule.ConditionLogicalGrouping.HasValue
                ? rule.ConditionLogicalGrouping.Value
                : LogicalGrouping.MatchAll;

            conditionMatchResult.LogincalGrouping = conditionLogicalGrouping;

            if (conditionLogicalGrouping == LogicalGrouping.MatchAll)
            {
                foreach (var condition in rule.Conditions)
                {
                    var conditionMatched = TestConditionMatch(replacements, condition, lastConditionMatch);
                    var conditionMatch = conditionMatched.Match;
                    var conditionInput = conditionMatched.ConditionInput;

                    conditionMatches = conditionMatch.Success;

                    if (condition.CheckIfInputString != null && condition.CheckIfInputString.Value == CheckIfInputString.DoesNotMatchThePattern)
                    {
                        conditionMatches = !conditionMatches;
                    }

                    if (conditionMatches)
                    {
                        lastConditionMatch = conditionMatch;
                        conditionMatchResult.MatchedConditions.Add(new MatchedCondition(condition, conditionInput));
                        conditionMatchResult.Matched = true;
                    }
                }
            }
            else
            {
                foreach (var condition in rule.Conditions)
                {
                    var conditionMatched = TestConditionMatch(replacements, condition);
                    var conditionMatch = conditionMatched.Match;
                    var conditionInput = conditionMatched.ConditionInput;

                    conditionMatches = conditionMatch.Success;

                    if (condition.CheckIfInputString != null && condition.CheckIfInputString.Value == CheckIfInputString.DoesNotMatchThePattern)
                    {
                        conditionMatches = !conditionMatches;
                    }

                    if (!conditionMatches) continue;

                    conditionMatchResult.MatchedConditions.Add(new MatchedCondition(condition, conditionInput));
                    lastConditionMatch = conditionMatch;
                    conditionMatchResult.Matched = true;

                    break;
                }
            }

            return conditionMatchResult;
        }
Esempio n. 47
0
        SqlPreCommand SyncProcedures(Replacements replacements)
        {
            var oldProcedures = Schema.Current.DatabaseNames().SelectMany(db =>
            {
                using (Administrator.OverrideDatabaseInSysViews(db))
                {
                    return (from p in Database.View<SysObjects>()
                            join s in Database.View<SysSchemas>() on p.schema_id equals s.schema_id
                            where p.type == "P" || p.type == "IF" || p.type == "FN"
                            join m in Database.View<SysSqlModules>() on p.object_id equals m.object_id
                            select KVP.Create(new ObjectName(new SchemaName(db, s.name), p.name), m.definition)).ToList();
                }
            }).ToDictionary();

            return Synchronizer.SynchronizeScript(
                StoreProcedures,
                oldProcedures,
                (name, newProc) => newProc.CreateSql(),
                null,
                (name, newProc, oldProc) =>
                    Clean(newProc.CreateSql().Sql) == Clean(oldProc) ? null : newProc.AlterSql(),
                Spacing.Double);
        }
Esempio n. 48
0
        public static SqlPreCommand ImportRulesScript(XDocument doc, bool interactive)
        {
            Replacements replacements = new Replacements { Interactive = interactive };

            Dictionary<string, Lite<RoleEntity>> rolesDic = roles.Value.ToDictionary(a => a.ToString());
            Dictionary<string, XElement> rolesXml = doc.Root.Element("Roles").Elements("Role").ToDictionary(x => x.Attribute("Name").Value);

            replacements.AskForReplacements(rolesXml.Keys.ToHashSet(), rolesDic.Keys.ToHashSet(), "Roles");

            rolesDic = replacements.ApplyReplacementsToNew(rolesDic, "Roles");

            try
            {
                var xmlOnly = rolesXml.Keys.Except(rolesDic.Keys).ToList();
                if (xmlOnly.Any())
                    throw new InvalidOperationException("roles {0} not found on the database".FormatWith(xmlOnly.ToString(", ")));

                foreach (var kvp in rolesXml)
                {
                    var r = rolesDic[kvp.Key];

                    var current = GetMergeStrategy(r);
                    var should = kvp.Value.Attribute("MergeStrategy")?.Let(t => t.Value.ToEnum<MergeStrategy>()) ?? MergeStrategy.Union;

                    if (current != should)
                        throw new InvalidOperationException("Merge strategy of {0} is {1} in the database but is {2} in the file".FormatWith(r, current, should));

                    EnumerableExtensions.JoinStrict(
                        roles.Value.RelatedTo(r),
                        kvp.Value.Attribute("Contains").Value.Split(new []{','},  StringSplitOptions.RemoveEmptyEntries),
                        sr => sr.ToString(),
                        s => rolesDic[s].ToString(),
                        (sr, s) => 0,
                        "subRoles of {0}".FormatWith(r));
                }
            }
            catch (InvalidOperationException ex)
            {
                throw new InvalidRoleGraphException("The role graph does not match:\r\n" + ex.Message); 
            }

            var dbOnlyWarnings = rolesDic.Keys.Except(rolesXml.Keys).Select(n =>
                    new SqlPreCommandSimple("-- Alien role {0} not configured!!".FormatWith(n))
                ).Combine(Spacing.Simple);

            SqlPreCommand result = ImportFromXml.GetInvocationListTyped()
                .Select(inv => inv(doc.Root, rolesDic, replacements)).Combine(Spacing.Triple);

            result = SqlPreCommand.Combine(Spacing.Triple, result, UpdateLastAuthRules(doc.Root.Element("Exported")));
            

            if (replacements.Values.Any(a => a.Any()))
                SafeConsole.WriteLineColor(ConsoleColor.Red, "There are renames! Remember to export after executing the script");

            if (result == null && dbOnlyWarnings == null)
                return null;

       
            return SqlPreCommand.Combine(Spacing.Triple,
                new SqlPreCommandSimple("-- BEGIN AUTH SYNC SCRIPT"),
                new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())),
                dbOnlyWarnings,
                result,
                new SqlPreCommandSimple("-- END AUTH SYNC SCRIPT"));
        }
Esempio n. 49
0
        static SqlPreCommand Schema_Synchronizing(Replacements replacements)
        {
            if (!replacements.Interactive)
                return null;

            var list = Database.Query<UserQueryEntity>().ToList();

            var table = Schema.Current.Table(typeof(UserQueryEntity));

            SqlPreCommand cmd = list.Select(uq => ProcessUserQuery(replacements, table, uq)).Combine(Spacing.Double);

            return cmd;
        }
Esempio n. 50
0
        internal static SqlPreCommand ProcessEmailTemplate( Replacements replacements, Table table, EmailTemplateEntity et, StringDistance sd)
        {
            try
            {
                var queryName = QueryLogic.ToQueryName(et.Query.Key);

                QueryDescription qd = DynamicQueryManager.Current.QueryDescription(queryName);

                Console.Clear();

                SafeConsole.WriteLineColor(ConsoleColor.White, "EmailTemplate: " + et.Name);
                Console.WriteLine(" Query: " + et.Query.Key);

                if (et.From != null && et.From.Token != null)
                {
                    QueryTokenEntity token = et.From.Token;
                    switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement, " From", allowRemoveToken: false, allowReCreate: et.SystemEmail != null))
                    {
                        case FixTokenResult.Nothing: break;
                        case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(et);
                        case FixTokenResult.SkipEntity: return null;
                        case FixTokenResult.Fix: et.From.Token = token; break;
                        case FixTokenResult.ReGenerateEntity: return Regenerate(et, replacements, table);
                        default: break;
                    }
                }

                if (et.Recipients.Any(a=>a.Token != null))
                {
                    Console.WriteLine(" Recipients:");
                    foreach (var item in et.Recipients.Where(a => a.Token != null).ToList())
                    {
                        QueryTokenEntity token = item.Token;
                        switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement, " Recipient", allowRemoveToken: false, allowReCreate: et.SystemEmail != null))
                        {
                            case FixTokenResult.Nothing: break;
                            case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(et);
                            case FixTokenResult.RemoveToken: et.Recipients.Remove(item); break;
                            case FixTokenResult.SkipEntity: return null;
                            case FixTokenResult.Fix: item.Token = token; break;
                            case FixTokenResult.ReGenerateEntity: return Regenerate(et, replacements, table);
                            default: break;
                        }
                    }
                }

                try
                {

                    foreach (var item in et.Messages)
                    {
                        SyncronizationContext sc = new SyncronizationContext
                        {
                            ModelType = et.SystemEmail.ToType(),
                            QueryDescription = qd,
                            Replacements = replacements,
                            StringDistance = sd,
                            Variables = new ScopedDictionary<string, ValueProviderBase>(null)
                        };

                        item.Subject = Synchronize(item.Subject, sc);
                        item.Text = Synchronize(item.Text, sc);
                    }

                    using (replacements.WithReplacedDatabaseName())
                        return table.UpdateSqlSync(et, includeCollections: true, comment: "EmailTemplate: " + et.Name);
                }
                catch (TemplateSyncException ex)
                {
                    if (ex.Result == FixTokenResult.SkipEntity)
                        return null;

                    if (ex.Result == FixTokenResult.DeleteEntity)
                        return table.DeleteSqlSync(et);

                    if (ex.Result == FixTokenResult.ReGenerateEntity)
                        return Regenerate(et, replacements, table);

                    throw new InvalidOperationException("Unexcpected {0}".FormatWith(ex.Result));
                }
                finally
                {
                    Console.Clear();
                }
            }
            catch (Exception e)
            {
                return new SqlPreCommandSimple("-- Exception in {0}: {1}".FormatWith(et.BaseToString(), e.Message));
            }
        }
Esempio n. 51
0
        public static void SynchronizeRoles(XDocument doc)
        {
            Table table = Schema.Current.Table(typeof(RoleEntity));
            TableMList relationalTable = table.TablesMList().Single();

            Dictionary<string, XElement> rolesXml = doc.Root.Element("Roles").Elements("Role").ToDictionary(x => x.Attribute("Name").Value);

            {
                Dictionary<string, RoleEntity> rolesDic = Database.Query<RoleEntity>().ToDictionary(a => a.ToString());
                Replacements replacements = new Replacements();
                replacements.AskForReplacements(rolesDic.Keys.ToHashSet(), rolesXml.Keys.ToHashSet(), "Roles");
                rolesDic = replacements.ApplyReplacementsToOld(rolesDic, "Roles");

                Console.WriteLine("Part 1: Syncronize roles without relationships");

                var roleInsertsDeletes = Synchronizer.SynchronizeScript(rolesXml, rolesDic,
                    (name, xelement) => table.InsertSqlSync(new RoleEntity { Name = name }, includeCollections: false),
                    (name, role) => SqlPreCommand.Combine(Spacing.Simple,
                            new SqlPreCommandSimple("DELETE {0} WHERE {1} = {2} --{3}"
                                .FormatWith(relationalTable.Name, ((IColumn)relationalTable.Field).Name.SqlEscape(), role.Id, role.Name)),
                            table.DeleteSqlSync(role)),
                    (name, xElement, role) =>
                    {
                        var oldName = role.Name;
                        role.Name = name;
                        role.MergeStrategy = xElement.Attribute("MergeStrategy")?.Let(t => t.Value.ToEnum<MergeStrategy>()) ?? MergeStrategy.Union;
                        return table.UpdateSqlSync(role, includeCollections: false, comment: oldName);
                    }, Spacing.Double);

                if (roleInsertsDeletes != null)
                {
                    SqlPreCommand.Combine(Spacing.Triple,
                       new SqlPreCommandSimple("-- BEGIN ROLE SYNC SCRIPT"),
                       new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())),
                       roleInsertsDeletes,
                       new SqlPreCommandSimple("-- END ROLE  SYNC SCRIPT")).OpenSqlFileRetry();

                    Console.WriteLine("Press [Enter] when executed...");
                    Console.ReadLine();
                }
                else
                {
                    SafeConsole.WriteLineColor(ConsoleColor.Green, "Already syncronized");
                }
            }

            {
                Console.WriteLine("Part 2: Syncronize roles relationships");
                Dictionary<string, RoleEntity> rolesDic = Database.Query<RoleEntity>().ToDictionary(a => a.ToString());

                var roleRelationships = Synchronizer.SynchronizeScript(rolesXml, rolesDic,
                 (name, xelement) => { throw new InvalidOperationException("No new roles should be at this stage. Did you execute the script?"); },
                 (name, role) => { throw new InvalidOperationException("No old roles should be at this stage. Did you execute the script?"); },
                 (name, xElement, role) =>
                 {
                     var should = xElement.Attribute("Contains").Value.Split(new []{','},  StringSplitOptions.RemoveEmptyEntries);
                     var current = role.Roles.Select(a=>a.ToString());

                     if(should.OrderBy().SequenceEqual(current.OrderBy()))
                         return null;

                     role.Roles = should.Select(rs => rolesDic.GetOrThrow(rs).ToLite()).ToMList();

                     return table.UpdateSqlSync(role);
                 }, Spacing.Double);

                if (roleRelationships != null)
                {
                    SqlPreCommand.Combine(Spacing.Triple,
                       new SqlPreCommandSimple("-- BEGIN ROLE SYNC SCRIPT"),
                       new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())),
                       roleRelationships,
                       new SqlPreCommandSimple("-- END ROLE  SYNC SCRIPT")).OpenSqlFileRetry();

                    Console.WriteLine("Press [Enter] when executed...");
                    Console.ReadLine();
                }
                else
                {
                    SafeConsole.WriteLineColor(ConsoleColor.Green, "Already syncronized");
                }
            }
        }
Esempio n. 52
0
        static string SynchronizeContent(string content, Replacements r, SyncData data)
        {
            if (content == null)
            {
                return(null);
            }

            return(WikiMarkup.WikiParserExtensions.TokenRegex.Replace(content, m =>
            {
                var m2 = HelpLinkRegex.Match(m.Groups["content"].Value);

                if (!m2.Success)
                {
                    return m.Value;
                }

                string letter = m2.Groups["letter"].Value;
                string link = m2.Groups["link"].Value;
                string text = m2.Groups["text"].Value;

                switch (letter)
                {
                case WikiFormat.EntityLink:
                    {
                        string type = r.SelectInteractive(link, TypeLogic.NameToType.Keys, "Type", data.StringDistance);

                        if (type == null)
                        {
                            return Link(letter + "-error", link, text);
                        }

                        return Link(letter, type, text);
                    }

                case WikiFormat.PropertyLink:
                    {
                        string type = r.SelectInteractive(link.Before("."), TypeLogic.NameToType.Keys, "Type", data.StringDistance);

                        if (type == null)
                        {
                            return Link(letter + "-error", link, text);
                        }

                        var routes = PropertyRoute.GenerateRoutes(TypeLogic.GetType(type)).Select(a => a.PropertyString()).ToList();

                        string pr = r.SelectInteractive(link.After('.'), routes, "PropertyRoutes-" + type, data.StringDistance);

                        if (pr == null)
                        {
                            return Link(letter + "-error", link, text);
                        }

                        return Link(letter, type + "." + pr, text);
                    }

                case WikiFormat.QueryLink:
                    {
                        string query = r.SelectInteractive(link, QueryLogic.QueryNames.Keys, "Query", data.StringDistance);

                        if (query == null)
                        {
                            return Link(letter + "-error", link, text);
                        }

                        return Link(letter, query, text);
                    }

                case WikiFormat.OperationLink:
                    {
                        string operation = r.SelectInteractive(link, SymbolLogic <OperationSymbol> .AllUniqueKeys(), "Operation", data.StringDistance);

                        if (operation == null)
                        {
                            return Link(letter + "-error", link, text);
                        }

                        return Link(letter, operation, text);
                    }

                case WikiFormat.Hyperlink: return m.Value;

                case WikiFormat.NamespaceLink:
                    {
                        string @namespace = r.SelectInteractive(link, data.Namespaces, "Namespace", data.StringDistance);

                        if (@namespace == null)
                        {
                            return Link(letter + "-error", link, text);
                        }

                        return Link(letter, @namespace, text);
                    }

                case WikiFormat.AppendixLink:
                    {
                        string appendix = r.SelectInteractive(link, data.Appendices, "Appendices", data.StringDistance);

                        if (appendix == null)
                        {
                            return Link(letter + "-error", link, text);
                        }

                        return Link(letter, appendix, text);
                    }

                default:
                    break;
                }

                return m.Value;
            }));
        }
Esempio n. 53
0
        static SqlPreCommand ProcessUserQuery(Replacements replacements, Table table, UserQueryEntity uq)
        {
            try
            {
                Console.Clear();

                SafeConsole.WriteLineColor(ConsoleColor.White, "UserQuery: " + uq.DisplayName);
                Console.WriteLine(" Query: " + uq.Query.Key);

                if (uq.Filters.Any(a => a.Token.ParseException != null) ||
                   uq.Columns.Any(a => a.Token != null && a.Token.ParseException != null) ||
                   uq.Orders.Any(a => a.Token.ParseException != null))
                {

                    QueryDescription qd = DynamicQueryManager.Current.QueryDescription(uq.Query.ToQueryName());

                    if (uq.Filters.Any())
                    {
                        Console.WriteLine(" Filters:");
                        foreach (var item in uq.Filters.ToList())
                        {
                            QueryTokenEntity token = item.Token;
                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement, "{0} {1}".FormatWith(item.Operation, item.ValueString), allowRemoveToken: true, allowReCreate: false))
                            {
                                case FixTokenResult.Nothing: break;
                                case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uq);
                                case FixTokenResult.RemoveToken: uq.Filters.Remove(item); break;
                                case FixTokenResult.SkipEntity: return null;
                                case FixTokenResult.Fix: item.Token = token; break;
                                default: break;
                            }
                        }
                    }

                    if (uq.Columns.Any())
                    {
                        Console.WriteLine(" Columns:");
                        foreach (var item in uq.Columns.ToList())
                        {
                            QueryTokenEntity token = item.Token;
                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement, item.DisplayName.HasText() ? "'{0}'".FormatWith(item.DisplayName) : null, allowRemoveToken: true, allowReCreate: false))
                            {
                                case FixTokenResult.Nothing: break;
                                case FixTokenResult.DeleteEntity: ; return table.DeleteSqlSync(uq);
                                case FixTokenResult.RemoveToken: uq.Columns.Remove(item); break;
                                case FixTokenResult.SkipEntity: return null;
                                case FixTokenResult.Fix: item.Token = token; break;
                                default: break;
                            }
                        }
                    }

                    if (uq.Orders.Any())
                    {
                        Console.WriteLine(" Orders:");
                        foreach (var item in uq.Orders.ToList())
                        {
                            QueryTokenEntity token = item.Token;
                            switch (QueryTokenSynchronizer.FixToken(replacements, ref token, qd, SubTokensOptions.CanElement, item.OrderType.ToString(), allowRemoveToken: true, allowReCreate: false))
                            {
                                case FixTokenResult.Nothing: break;
                                case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uq);
                                case FixTokenResult.RemoveToken: uq.Orders.Remove(item); break;
                                case FixTokenResult.SkipEntity: return null;
                                case FixTokenResult.Fix: item.Token = token; break;
                                default: break;
                            }
                        }
                    }
                }

                foreach (var item in uq.Filters.ToList())
                {
                retry:
                    string val = item.ValueString;
                    switch (QueryTokenSynchronizer.FixValue(replacements, item.Token.Token.Type, ref val, allowRemoveToken: true, isList: item.Operation.IsList()))
                    {
                        case FixTokenResult.Nothing: break;
                        case FixTokenResult.DeleteEntity: return table.DeleteSqlSync(uq);
                        case FixTokenResult.RemoveToken: uq.Filters.Remove(item); break;
                        case FixTokenResult.SkipEntity: return null;
                        case FixTokenResult.Fix: item.ValueString = val; goto retry;
                    }
                }

                if (uq.WithoutFilters)
                    uq.Filters.Clear();

                if (!uq.ShouldHaveElements && uq.ElementsPerPage.HasValue)
                    uq.ElementsPerPage = null;

                if (uq.ShouldHaveElements && !uq.ElementsPerPage.HasValue)
                    uq.ElementsPerPage = 20;

                Console.Clear();

                using (replacements.WithReplacedDatabaseName())
                    return table.UpdateSqlSync(uq, includeCollections: true);
            }
            catch (Exception e)
            {
                return new SqlPreCommandSimple("-- Exception in {0}: {1}".FormatWith(uq.BaseToString(), e.Message));
            }
        }
Esempio n. 54
0
 public static Dictionary <TypeEntity, Type> TryEntityToType(Replacements replacements)
 {
     return((from dn in Administrator.TryRetrieveAll <TypeEntity>(replacements)
             join t in Schema.Current.Tables.Keys on dn.FullClassName equals(EnumEntity.Extract(t) ?? t).FullName
             select(dn, t)).ToDictionary(a => a.dn, a => a.t));
 }
Esempio n. 55
0
        public static SqlPreCommand?ImportRulesScript(XDocument doc, bool interactive)
        {
            Replacements replacements = new Replacements {
                Interactive = interactive
            };

            Dictionary <string, Lite <RoleEntity> > rolesDic = roles.Value.ToDictionary(a => a.ToString());
            Dictionary <string, XElement>           rolesXml = doc.Root.Element("Roles").Elements("Role").ToDictionary(x => x.Attribute("Name").Value);

            replacements.AskForReplacements(rolesXml.Keys.ToHashSet(), rolesDic.Keys.ToHashSet(), "Roles");

            rolesDic = replacements.ApplyReplacementsToNew(rolesDic, "Roles");

            try
            {
                var xmlOnly = rolesXml.Keys.Except(rolesDic.Keys).ToList();
                if (xmlOnly.Any())
                {
                    throw new InvalidOperationException("roles {0} not found on the database".FormatWith(xmlOnly.ToString(", ")));
                }

                foreach (var kvp in rolesXml)
                {
                    var r = rolesDic[kvp.Key];

                    var current = GetMergeStrategy(r);
                    var should  = kvp.Value.Attribute("MergeStrategy")?.Let(t => t.Value.ToEnum <MergeStrategy>()) ?? MergeStrategy.Union;

                    if (current != should)
                    {
                        throw new InvalidOperationException("Merge strategy of {0} is {1} in the database but is {2} in the file".FormatWith(r, current, should));
                    }

                    EnumerableExtensions.JoinStrict(
                        roles.Value.RelatedTo(r),
                        kvp.Value.Attribute("Contains").Value.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries),
                        sr => sr.ToString(),
                        s => rolesDic[s].ToString(),
                        (sr, s) => 0,
                        "subRoles of {0}".FormatWith(r));
                }
            }
            catch (InvalidOperationException ex)
            {
                throw new InvalidRoleGraphException("The role graph does not match:\r\n" + ex.Message);
            }

            var dbOnlyWarnings = rolesDic.Keys.Except(rolesXml.Keys).Select(n =>
                                                                            new SqlPreCommandSimple("-- Alien role {0} not configured!!".FormatWith(n))
                                                                            ).Combine(Spacing.Simple);

            SqlPreCommand?result = ImportFromXml.GetInvocationListTyped()
                                   .Select(inv => inv(doc.Root, rolesDic, replacements)).Combine(Spacing.Triple);

            if (replacements.Values.Any(a => a.Any()))
            {
                SafeConsole.WriteLineColor(ConsoleColor.Red, "There are renames! Remember to export after executing the script");
            }

            if (result == null && dbOnlyWarnings == null)
            {
                return(null);
            }


            return(SqlPreCommand.Combine(Spacing.Triple,
                                         new SqlPreCommandSimple("-- BEGIN AUTH SYNC SCRIPT"),
                                         new SqlPreCommandSimple("use {0}".FormatWith(Connector.Current.DatabaseName())),
                                         dbOnlyWarnings,
                                         result,
                                         new SqlPreCommandSimple("-- END AUTH SYNC SCRIPT")));
        }
Esempio n. 56
0
        public static SqlPreCommand?Schema_Synchronizing(Replacements replacements)
        {
            var schema     = Schema.Current;
            var isPostgres = schema.Settings.IsPostgres;

            Dictionary <string, TypeEntity> should = GenerateSchemaTypes().ToDictionaryEx(s => s.TableName, "tableName in memory");

            var currentList = Administrator.TryRetrieveAll <TypeEntity>(replacements);

            { //External entities are nt asked in SchemaSynchronizer
                replacements.AskForReplacements(
                    currentList.Where(t => schema.IsExternalDatabase(ObjectName.Parse(t.TableName, isPostgres).Schema.Database)).Select(a => a.TableName).ToHashSet(),
                    should.Values.Where(t => schema.IsExternalDatabase(ObjectName.Parse(t.TableName, isPostgres).Schema.Database)).Select(a => a.TableName).ToHashSet(),
                    Replacements.KeyTables);
            }

            Dictionary <string, TypeEntity> current = ApplyReplacementsToOld(replacements,
                                                                             currentList.ToDictionaryEx(c => c.TableName, "tableName in database"), Replacements.KeyTables);

            { //Temporal solution until applications are updated
                var repeated =
                    should.Keys.Select(k => ObjectName.Parse(k, isPostgres)).GroupBy(a => a.Name).Where(a => a.Count() > 1).Select(a => a.Key).Concat(
                        current.Keys.Select(k => ObjectName.Parse(k, isPostgres)).GroupBy(a => a.Name).Where(a => a.Count() > 1).Select(a => a.Key)).ToList();

                string simplify(string tn)
                {
                    ObjectName name = ObjectName.Parse(tn, isPostgres);

                    return(repeated.Contains(name.Name) ? name.ToString() : name.Name);
                }

                should  = should.SelectDictionary(simplify, v => v);
                current = current.SelectDictionary(simplify, v => v);
            }

            Table table = schema.Table <TypeEntity>();

            using (replacements.WithReplacedDatabaseName())
                return(Synchronizer.SynchronizeScript(
                           Spacing.Double,
                           should,
                           current,
                           createNew: (tn, s) => table.InsertSqlSync(s),
                           removeOld: (tn, c) => table.DeleteSqlSync(c, t => t.CleanName == c.CleanName),
                           mergeBoth: (tn, s, c) =>
                {
                    var originalCleanName = c.CleanName;
                    var originalFullName = c.FullClassName;

                    if (c.TableName != s.TableName)
                    {
                        var pc = ObjectName.Parse(c.TableName, isPostgres);
                        var ps = ObjectName.Parse(s.TableName, isPostgres);

                        if (!EqualsIgnoringDatabasePrefix(pc, ps))
                        {
                            c.TableName = ps.ToString();
                        }
                    }

                    c.CleanName = s.CleanName;
                    c.Namespace = s.Namespace;
                    c.ClassName = s.ClassName;
                    return table.UpdateSqlSync(c, t => t.CleanName == originalCleanName, comment: originalFullName);
                }));
        }
Esempio n. 57
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <DynamicRenameEntity>()
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.CreationDate,
                    e.ReplacementKey,
                    e.OldName,
                    e.NewName,
                    IsApplied = e.IsApplied(),
                });

                sb.Include <DynamicSqlMigrationEntity>()
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.CreationDate,
                    e.CreatedBy,
                    e.ExecutionDate,
                    e.ExecutedBy,
                    e.Comment,
                });

                new Graph <DynamicSqlMigrationEntity> .Construct(DynamicSqlMigrationOperation.Create)
                {
                    Construct = args =>
                    {
                        if (DynamicLogic.CodeGenError != null)
                        {
                            throw new InvalidOperationException(DynamicSqlMigrationMessage.PreventingGenerationNewScriptBecauseOfErrorsInDynamicCodeFixErrorsAndRestartServer.NiceToString());
                        }

                        var old = Replacements.AutoReplacement;

                        var lastRenames = Database.Query <DynamicRenameEntity>()
                                          .Where(a => !a.IsApplied())
                                          .OrderBy(a => a.CreationDate)
                                          .ToList();

                        try
                        {
                            if (Replacements.AutoReplacement == null)
                            {
                                Replacements.AutoReplacement = ctx =>
                                {
                                    var currentName =
                                        ctx.ReplacementKey.StartsWith(Replacements.KeyEnumsForTable("")) ? AutoReplacementEnums(ctx):
                                        ctx.ReplacementKey.StartsWith(PropertyRouteLogic.PropertiesFor.FormatWith("")) ? DynamicAutoReplacementsProperties(ctx, lastRenames) :
                                        ctx.ReplacementKey.StartsWith(Replacements.KeyColumnsForTable("")) ? DynamicAutoReplacementsColumns(ctx, lastRenames) :
                                        ctx.ReplacementKey == Replacements.KeyTables ? DynamicAutoReplacementsSimple(ctx, lastRenames, Replacements.KeyTables) :
                                        ctx.ReplacementKey == typeof(OperationSymbol).Name ? DynamicAutoReplacementsOperations(ctx, lastRenames) :
                                        ctx.ReplacementKey == QueryLogic.QueriesKey ? DynamicAutoReplacementsSimple(ctx, lastRenames, DynamicTypeLogic.TypeNameKey) :
                                        DynamicAutoReplacementsSimple(ctx, lastRenames, ctx.ReplacementKey);

                                    if (currentName != null)
                                    {
                                        return(new Replacements.Selection(ctx.OldValue, currentName));
                                    }

                                    return(new Replacements.Selection(ctx.OldValue, null));
                                }
                            }
                            ;

                            var script = Schema.Current.SynchronizationScript(interactive: false, replaceDatabaseName: SqlMigrationRunner.DatabaseNameReplacement);

                            return(new DynamicSqlMigrationEntity
                            {
                                CreationDate = TimeZoneManager.Now,
                                CreatedBy = UserEntity.Current.ToLite(),
                                Script = script?.ToString() ?? "",
                            });
                        }
                        finally
                        {
                            Replacements.AutoReplacement = old;
                        }
                    }
                }
        static SqlPreCommand Schema_Synchronize_Tokens(Replacements replacements)
        {
            if (AvoidSynchronize)
                return null;

            StringDistance sd = new StringDistance();

            var emailTemplates = Database.Query<WordTemplateEntity>().ToList();

            SqlPreCommand cmd = emailTemplates.Select(uq => SynchronizeWordTemplate(replacements, uq, sd)).Combine(Spacing.Double);

            return cmd;
        }
        internal static SqlPreCommand SynchronizeWordTemplate(Replacements replacements, WordTemplateEntity template, StringDistance sd)
        {
            try
            {
                if (template.Template == null)
                    return null;

                var queryName = QueryLogic.ToQueryName(template.Query.Key);

                QueryDescription qd = DynamicQueryManager.Current.QueryDescription(queryName);

                Console.Clear();

                SafeConsole.WriteLineColor(ConsoleColor.White, "WordTemplate: " + template.Name);
                Console.WriteLine(" Query: " + template.Query.Key);

                var file = template.Template.Retrieve();

                try
                {
                    using (var memory = new MemoryStream())
                    {
                        memory.WriteAllBytes(file.BinaryFile);

                        using (WordprocessingDocument document = WordprocessingDocument.Open(memory, true))
                        {
                            Dump(document, "0.Original.txt");

                            var parser = new WordTemplateParser(document, qd, template.SystemWordTemplate.ToType());
                            parser.ParseDocument(); Dump(document, "1.Match.txt");
                            parser.CreateNodes(); Dump(document, "2.BaseNode.txt");
                            parser.AssertClean();

                            SyncronizationContext sc = new SyncronizationContext
                            {
                                ModelType = template.SystemWordTemplate.ToType(),
                                QueryDescription = qd,
                                Replacements = replacements,
                                StringDistance = sd,
                                HasChanges = false,
                                Variables = new ScopedDictionary<string, ValueProviderBase>(null),
                            };


                            foreach (var root in document.RecursivePartsRootElements())
                            {
                                foreach (var node in root.Descendants<BaseNode>().ToList())
                                {
                                    node.Synchronize(sc);
                                }
                            }

                            if (!sc.HasChanges)
                                return null;

                            Dump(document, "3.Synchronized.txt");
                            var variables = new ScopedDictionary<string, ValueProviderBase>(null);
                            foreach (var root in document.RecursivePartsRootElements())
                            {
                                foreach (var node in root.Descendants<BaseNode>().ToList())
                                {
                                    node.RenderTemplate(variables);
                                }
                            }

                            Dump(document, "4.Rendered.txt");
                        }

                        file.AllowChange = true;
                        file.BinaryFile = memory.ToArray();

                        using (replacements.WithReplacedDatabaseName())
                            return Schema.Current.Table<FileEntity>().UpdateSqlSync(file, comment: "WordTemplate: " + template.Name);
                    }                 
                }
                catch (TemplateSyncException ex)
                {
                    if (ex.Result == FixTokenResult.SkipEntity)
                        return null;

                    if (ex.Result == FixTokenResult.DeleteEntity)
                        return SqlPreCommandConcat.Combine(Spacing.Simple,
                            Schema.Current.Table<WordTemplateEntity>().DeleteSqlSync(template),
                            Schema.Current.Table<FileEntity>().DeleteSqlSync(file));

                    if (ex.Result == FixTokenResult.ReGenerateEntity)
                        return Regenerate(template, replacements);

                    throw new InvalidOperationException("Unexcpected {0}".FormatWith(ex.Result));
                }
                finally
                {
                    Console.Clear();
                }
            }
            catch (Exception e)
            {
                return new SqlPreCommandSimple("-- Exception in {0}: {1}".FormatWith(template.BaseToString(), e.Message));
            }
        }
        public static FixTokenResult FixToken(Replacements replacements, string original, out QueryToken token, QueryDescription qd, SubTokensOptions options, string remainingText, bool allowRemoveToken, bool allowReGenerate)
        {
            string[] parts = original.Split('.');

            QueryToken current;
            if (TryParseRemember(replacements, original, qd, options, out current))
            {
                if (current.FullKey() != original)
                {
                    SafeConsole.WriteColor(ConsoleColor.DarkRed, "  " + original);
                    Console.Write(" -> ");
                    SafeConsole.WriteColor(ConsoleColor.DarkGreen, current.FullKey());
                }
                Console.WriteLine(remainingText);
                token = current;
                return FixTokenResult.Fix;
            }

            while (true)
            {
                var result = SelectInteractive(ref current, qd, options, allowRemoveToken, allowReGenerate);
                switch (result)
                {
                    case UserAssetTokenAction.DeleteEntity:
                        SafeConsole.WriteLineColor(ConsoleColor.Red, "Entity deleted");
                        token = null;
                        return FixTokenResult.DeleteEntity;
                    case UserAssetTokenAction.ReGenerateEntity:
                        if (!allowReGenerate)
                            throw new InvalidOperationException("Unexpected ReGenerate");

                        SafeConsole.WriteLineColor(ConsoleColor.Magenta, "Entity Re-Generated");
                        token = null;
                        return FixTokenResult.ReGenerateEntity;
                    case UserAssetTokenAction.RemoveToken:
                        if (!allowRemoveToken)
                            throw new InvalidOperationException("Unexpected RemoveToken");

                        Console.SetCursorPosition(0, Console.CursorTop - 1);
                        SafeConsole.WriteColor(ConsoleColor.DarkRed, "  " + original);
                        SafeConsole.WriteColor(ConsoleColor.DarkRed, " (token removed)");
                        Console.WriteLine(remainingText);
                        token = null;
                        return FixTokenResult.RemoveToken;
                    case UserAssetTokenAction.SkipEntity:
                        SafeConsole.WriteLineColor(ConsoleColor.DarkYellow, "Entity skipped");
                        token = null;
                        return FixTokenResult.SkipEntity;
                    case UserAssetTokenAction.Confirm:
                        Remember(replacements, original, current);
                        Console.SetCursorPosition(0, Console.CursorTop - 1);
                        SafeConsole.WriteColor(ConsoleColor.DarkRed, "  " + original);
                        Console.Write(" -> ");
                        SafeConsole.WriteColor(ConsoleColor.DarkGreen, current.FullKey());
                        Console.WriteLine(remainingText);
                        token = current;
                        return FixTokenResult.Fix;
                }
            }
        }