protected override Expression VisitMemberInit(MemberInitExpression init)
        {
            if (this.mapping.IsEntity(init.Type))
            {
                var save = this.includeScope;
                this.includeScope = new ScopedDictionary<MemberInfo,bool>(this.includeScope);

                Dictionary<MemberInfo, MemberBinding> existing = init.Bindings.ToDictionary(b => b.Member);
                List<MemberBinding> newBindings = null;
                foreach (var mi in this.mapping.GetMappedMembers(init.Type))
                {
                    if (!existing.ContainsKey(mi) && this.mapping.IsRelationship(mi) && this.policy.IsIncluded(mi))
                    {
                        if (this.includeScope.ContainsKey(mi))
                        {
                            throw new NotSupportedException(string.Format("Cannot include '{0}.{1}' recursively.", mi.DeclaringType.Name, mi.Name));
                        }
                        Expression me = this.mapping.GetMemberExpression(init, mi);
                        if (newBindings == null)
                        {
                            newBindings = new List<MemberBinding>(init.Bindings);
                        }
                        newBindings.Add(Expression.Bind(mi, me));
                    }
                }
                if (newBindings != null)
                {
                    init = Expression.MemberInit(init.NewExpression, newBindings);
                }

                this.includeScope = save;
            }
            return base.VisitMemberInit(init);
        }
示例#2
0
 protected override Expression VisitEntity(EntityExpression entity)
 {
     var save = this.includeScope;
     this.includeScope = new ScopedDictionary<MemberInfo, bool>(this.includeScope);
     try
     {
         if (this.mapper.HasIncludedMembers(entity))
         {
             entity = this.mapper.IncludeMembers(
                 entity,
                 m =>
                 {
                     if (this.includeScope.ContainsKey(m))
                     {
                         return false;
                     }
                     if (this.policy.IsIncluded(m))
                     {
                         this.includeScope.Add(m, true);
                         return true;
                     }
                     return false;
                 });
         }
         return base.VisitEntity(entity);
     }
     finally
     {
         this.includeScope = save;
     }
 }
		private Expression FindSimilarRight(JoinExpression join, JoinExpression compareTo)
		{
			if (join == null)
			{
				return null;
			}
			if (join.Join == compareTo.Join)
			{
				if (join.Right.NodeType == compareTo.Right.NodeType && DbExpressionComparer.AreEqual(join.Right, compareTo.Right))
				{
					if (join.Condition == compareTo.Condition)
					{
						return join.Right;
					}
					var scope = new ScopedDictionary<TableAlias, TableAlias>(null);
					scope.Add(((AliasedExpression)join.Right).Alias, ((AliasedExpression)compareTo.Right).Alias);
					if (DbExpressionComparer.AreEqual(null, scope, join.Condition, compareTo.Condition))
					{
						return join.Right;
					}
				}
			}
			Expression result = FindSimilarRight(join.Left as JoinExpression, compareTo);
			if (result == null)
			{
				result = FindSimilarRight(join.Right as JoinExpression, compareTo);
			}
			return result;
		}
 public override string ToString()
 {
     StringBuilder sb = new StringBuilder();
     ScopedDictionary<string, ValueProviderBase> variables = new ScopedDictionary<string, ValueProviderBase>(null);
     ToString(sb, variables);
     return sb.ToString();
 }
 protected DbExpressionComparer(ScopedDictionary<ParameterExpression,
     ParameterExpression> parameterScope,
     ScopedDictionary<DbTableAlias, DbTableAlias> aliasScope)
     : base(parameterScope)
 {
     _aliasScope = aliasScope;
 }
		public static bool AreEqual(
			ScopedDictionary<ParameterExpression, ParameterExpression> parameterScope,
			Expression a,
			Expression b,
			Func<object, object, bool> fnCompare)
		{
			return new ExpressionComparer(parameterScope, fnCompare).Compare(a, b);
		}
		public static bool AreEqual(
			ScopedDictionary<ParameterExpression, ParameterExpression> parameterScope,
			ScopedDictionary<TableAlias, TableAlias> aliasScope,
			Expression a,
			Expression b)
		{
			return new DbExpressionComparer(parameterScope, null, aliasScope).Compare(a, b);
		}
 protected ExpressionComparer(
     ScopedDictionary<ParameterExpression, ParameterExpression> parameterScope,
     Func<object, object, bool> fnCompare
     )
 {
     this.parameterScope = parameterScope;
     this.fnCompare = fnCompare;
 }
 protected DbExpressionComparer(
     ScopedDictionary<ParameterExpression, ParameterExpression> parameterScope, 
     Func<object, object, bool> fnCompare,
     ScopedDictionary<TableAlias, TableAlias> aliasScope)
     : base(parameterScope, fnCompare)
 {
     this.aliasScope = aliasScope;
 }
示例#10
0
        /// <summary>
        /// 获取上下文实体审计数据
        /// </summary>
        public static IList <AuditEntityEntry> GetAuditEntities(this DbContext context)
        {
            List <AuditEntityEntry> result = new List <AuditEntityEntry>();
            //当前操作的功能是否允许数据审计
            ScopedDictionary scopedDict = ServiceLocator.Instance.GetService <ScopedDictionary>();
            IFunction        function   = scopedDict?.Function;

            if (function == null || !function.AuditEntityEnabled)
            {
                return(result);
            }
            IEntityInfoHandler entityInfoHandler = ServiceLocator.Instance.GetService <IEntityInfoHandler>();

            if (entityInfoHandler == null)
            {
                return(result);
            }
            EntityState[]      states  = { EntityState.Added, EntityState.Modified, EntityState.Deleted };
            List <EntityEntry> entries = context.ChangeTracker.Entries().Where(m => m.Entity != null && states.Contains(m.State)).ToList();

            if (entries.Count == 0)
            {
                return(result);
            }
            foreach (EntityEntry entry in entries)
            {
                //当前操作的实体是否允许数据审计
                IEntityInfo entityInfo = entityInfoHandler.GetEntityInfo(entry.Entity.GetType());
                if (entityInfo == null || !entityInfo.AuditEnabled)
                {
                    continue;
                }
                result.AddIfNotNull(GetAuditEntity(entry, entityInfo));
            }
            return(result);
        }
            private bool CompareLambda(LambdaExpression a, LambdaExpression b)
            {
                var n = a.Parameters.Count;

                if (b.Parameters.Count != n)
                {
                    return(false);
                }

                // all must have same type
                for (var i = 0; i < n; i++)
                {
                    if (a.Parameters[i].Type != b.Parameters[i].Type)
                    {
                        return(false);
                    }
                }

                var save = _parameterScope;

                _parameterScope = new ScopedDictionary <ParameterExpression, ParameterExpression>(_parameterScope);

                try
                {
                    for (var i = 0; i < n; i++)
                    {
                        _parameterScope.Add(a.Parameters[i], b.Parameters[i]);
                    }

                    return(Compare(a.Body, b.Body));
                }
                finally
                {
                    _parameterScope = save;
                }
            }
示例#12
0
 public static bool AreEqual(ScopedDictionary<ParameterExpression, ParameterExpression> parameterScope, Expression a, Expression b)
 {
     return new ExpressionComparer(parameterScope).Compare(a, b);
 }
示例#13
0
 protected virtual bool CompareLambda(LambdaExpression a, LambdaExpression b)
 {
     int n = a.Parameters.Count;
     if (b.Parameters.Count != n)
         return false;
     // all must have same type
     for (int i = 0; i < n; i++)
     {
         if (a.Parameters[i].Type != b.Parameters[i].Type)
             return false;
     }
     var save = this.parameterScope;
     this.parameterScope = new ScopedDictionary<ParameterExpression, ParameterExpression>(this.parameterScope);
     try
     {
         for (int i = 0; i < n; i++)
         {
             this.parameterScope.Add(a.Parameters[i], b.Parameters[i]);
         }
         return this.Compare(a.Body, b.Body);
     }
     finally
     {
         this.parameterScope = save;
     }
 }
        protected virtual bool CompareJoin(JoinExpression a, JoinExpression b)
        {
            if (a.Join != b.Join || !this.Compare(a.Left, b.Left))
                return false;

            if (a.Join == JoinType.CrossApply || a.Join == JoinType.OuterApply)
            {
                var save = this.aliasScope;
                try
                {
                    this.aliasScope = new ScopedDictionary<TableAlias, TableAlias>(this.aliasScope);
                    this.MapAliases(a.Left, b.Left);

                    return this.Compare(a.Right, b.Right)
                        && this.Compare(a.Condition, b.Condition);
                }
                finally
                {
                    this.aliasScope = save;
                }
            }
            else
            {
                return this.Compare(a.Right, b.Right)
                    && this.Compare(a.Condition, b.Condition);
            }
        }
 /// <summary>
 /// 初始化一个<see cref="AuditEntityProvider"/>类型的新实例
 /// </summary>
 public AuditEntityProvider(ScopedDictionary scopedDict, IEntityInfoHandler entityInfoHandler)
 {
     _scopedDict        = scopedDict;
     _entityInfoHandler = entityInfoHandler;
 }
示例#16
0
 internal protected abstract void RenderTemplate(ScopedDictionary <string, ValueProviderBase> variables);
 protected MongoExpressionComparer(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope, ScopedDictionary <Alias, Alias> aliasScope)
     : base(parameterScope)
 {
     _aliasScope = aliasScope;
 }
            public override void ToString(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
            {
                sb.Append("@declare");

                ValueProvider.ToString(sb, variables, null);

                ValueProvider.Declare(variables);
            }
        protected virtual bool CompareLambda(LambdaExpression a, LambdaExpression b)
        {
            int n = a.Parameters.Count;
            if (b.Parameters.Count != n)
                return false;
            
            for (int i = 0; i < n; i++)
            {
                if (a.Parameters[i].Type != b.Parameters[i].Type)
                    return false;
            }
            ScopedDictionary<ParameterExpression, ParameterExpression> save = _scope;
            _scope = new ScopedDictionary<ParameterExpression, ParameterExpression>(_scope);

            try
            {
                for (int i = 0; i < n; i++)
                    _scope.Add(a.Parameters[i], b.Parameters[i]);
                
                return Compare(a.Body, b.Body);
            }
            finally
            {
                _scope = save;
            }
        }
 public override void ToString(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
 {
     sb.Append(Text);               
 }
            public override void ToString(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
            {
                sb.Append("@if");
                ValueProvider.ToString(sb, variables, Operation == null ? null : FilterValueConverter.ToStringOperation(Operation.Value) + Value);
                {
                    var newVars = new ScopedDictionary<string, ValueProviderBase>(variables);
                    ValueProvider.Declare(newVars);
                    IfBlock.ToString(sb, newVars);
                }

                if (ElseBlock != null)
                {
                    sb.Append("@else");
                    var newVars = new ScopedDictionary<string, ValueProviderBase>(variables);
                    ValueProvider.Declare(newVars);
                    ElseBlock.ToString(sb, newVars);
                }

                sb.Append("@endif");
            }
 public abstract void ToString(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables);
 public override void ToString(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
 {
     foreach (var n in Nodes)
     {
         n.ToString(sb, variables);
     }
 }
 public static bool AreEqual(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope, ScopedDictionary <Alias, Alias> aliasScope, Expression a, Expression b)
 {
     return(new MongoExpressionComparer(parameterScope, aliasScope).Compare(a, b));
 }
示例#25
0
 public static bool AreEqual(Expression?a, Expression?b, ScopedDictionary <ParameterExpression, ParameterExpression>?parameterScope = null, ScopedDictionary <Alias, Alias>?aliasScope = null, bool checkParameterNames = false)
 {
     return(new DbExpressionComparer(parameterScope, aliasScope, checkParameterNames).Compare(a, b));
 }
示例#26
0
 /// <summary>
 /// 初始化一个<see cref="UnitOfWorkManager"/>类型的新实例
 /// </summary>
 public UnitOfWorkManager(IServiceProvider provider)
 {
     ServiceProvider   = provider;
     _logger           = provider.GetLogger(this);
     _scopedDictionary = provider.GetService <ScopedDictionary>();
 }
示例#27
0
 public ScopedDictionary(ScopedDictionary <TKey, TValue> previous)
 {
     _previous = previous;
     _map      = new Dictionary <TKey, TValue>();
 }
示例#28
0
 /// <summary>
 /// 初始化一个<see cref="UnitOfWorkManager"/>类型的新实例
 /// </summary>
 public UnitOfWorkManager(IServiceProvider serviceProvider)
 {
     ServiceProvider   = serviceProvider;
     _scopedDictionary = serviceProvider.GetService <ScopedDictionary>();
 }
示例#29
0
 public static bool AreEqual(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope, ScopedDictionary <TableAlias, TableAlias> aliasScope, Expression a, Expression b)
 {
     return(new DbExpressionComparer(parameterScope, null, aliasScope).Compare(a, b));
 }
        protected internal override void RenderTemplate(ScopedDictionary<string, ValueProviderBase> variables)
        {
            var str = "@" + this.ValueProvider.ToString(variables, Format.HasText() ? (":" + Format) : null);

            this.ReplaceBy(new Run(this.RunProperties.TryDo(prop => prop.Remove()), new Text(str)));
        }
示例#31
0
        public static ParsedToken TryParseToken(string tokenString, SubTokensOptions options, QueryDescription qd, ScopedDictionary <string, ValueProviderBase> variables, Action <bool, string> addError)
        {
            ParsedToken result = new ParsedToken {
                String = tokenString
            };

            if (tokenString.StartsWith("$"))
            {
                string v = tokenString.TryBefore('.') ?? tokenString;

                if (!variables.TryGetValue(v, out ValueProviderBase vp))
                {
                    addError(false, "Variable '{0}' is not defined at this scope".FormatWith(v));
                    return(result);
                }

                var tvp = vp as TokenValueProvider;

                if (tvp == null)
                {
                    addError(false, "Variable '{0}' is not a token".FormatWith(v));
                    return(result);
                }

                if (tvp.ParsedToken.QueryToken == null)
                {
                    addError(false, "Variable '{0}' is not a correctly parsed".FormatWith(v));
                    return(result);
                }

                var after = tokenString.TryAfter('.');

                tokenString = tvp.ParsedToken.QueryToken.FullKey() + (after == null ? null : ("." + after));
            }

            try
            {
                result.QueryToken = QueryUtils.Parse(tokenString, qd, options);
            }
            catch (Exception ex)
            {
                addError(false, ex.Message);
            }
            return(result);
        }
 protected internal override void RenderTemplate(ScopedDictionary<string, ValueProviderBase> variables)
 {
     foreach (var item in this.Descendants<BaseNode>().ToList())
     {
         item.RenderTemplate(variables);
     }
 }
        protected virtual bool CompareProjection(ProjectionExpression a, ProjectionExpression b)
        {
            if (!this.Compare(a.Select, b.Select))
                return false;

            var save = this.aliasScope;
            try
            {
                this.aliasScope = new ScopedDictionary<TableAlias, TableAlias>(this.aliasScope);
                this.aliasScope.Add(a.Select.Alias, b.Select.Alias);

                return this.Compare(a.Projector, b.Projector)
                    && this.Compare(a.Aggregator, b.Aggregator)
                    && a.IsSingleton == b.IsSingleton;
            }
            finally
            {
                this.aliasScope = save;
            }
        }
 internal protected abstract void RenderTemplate(ScopedDictionary<string, ValueProviderBase> variables);
        protected virtual bool CompareSelect(SelectExpression a, SelectExpression b)
        {
            var save = this.aliasScope;
            try
            {
                if (!this.Compare(a.From, b.From))
                    return false;

                this.aliasScope = new ScopedDictionary<TableAlias, TableAlias>(save);
                this.MapAliases(a.From, b.From);

                return this.Compare(a.Where, b.Where)
                    && this.CompareOrderList(a.OrderBy, b.OrderBy)
                    && this.CompareExpressionList(a.GroupBy, b.GroupBy)
                    && this.Compare(a.Skip, b.Skip)
                    && this.Compare(a.Take, b.Take)
                    && a.IsDistinct == b.IsDistinct
                    && a.IsReverse == b.IsReverse
                    && this.CompareColumnDeclarations(a.Columns, b.Columns);
            }
            finally
            {
                this.aliasScope = save;
            }
        }
示例#36
0
        /// <summary>
        /// 重写方法,实现事务自动提交功能
        /// </summary>
        /// <param name="context"></param>
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            ScopedDictionary dict    = context.HttpContext.RequestServices.GetService <ScopedDictionary>();
            AjaxResultType   type    = AjaxResultType.Success;
            string           message = null;

            if (context.Result is JsonResult result1)
            {
                if (result1.Value is AjaxResult ajax)
                {
                    type    = ajax.Type;
                    message = ajax.Content;
                    if (ajax.Successed())
                    {
                        _unitOfWorkManager?.Commit();
                    }
                }
            }
            else if (context.Result is ObjectResult result2)
            {
                if (result2.Value is AjaxResult ajax)
                {
                    type    = ajax.Type;
                    message = ajax.Content;
                    if (ajax.Successed())
                    {
                        _unitOfWorkManager?.Commit();
                    }
                }
                _unitOfWorkManager?.Commit();
            }
            //普通请求
            else if (context.HttpContext.Response.StatusCode >= 400)
            {
                switch (context.HttpContext.Response.StatusCode)
                {
                case 401:
                    type = AjaxResultType.UnAuth;
                    break;

                case 403:
                    type = AjaxResultType.UnAuth;
                    break;

                case 404:
                    type = AjaxResultType.UnAuth;
                    break;

                case 423:
                    type = AjaxResultType.UnAuth;
                    break;

                default:
                    type = AjaxResultType.Error;
                    break;
                }
            }
            else
            {
                type = AjaxResultType.Success;
                _unitOfWorkManager?.Commit();
            }
            if (dict.AuditOperation != null)
            {
                dict.AuditOperation.ResultType = type;
                dict.AuditOperation.Message    = message;
            }
        }
示例#37
0
 protected ExpressionComparer(ScopedDictionary<ParameterExpression, ParameterExpression> parameterScope)
 {
     this.parameterScope = parameterScope;
 }
 public override void ToString(StringBuilder sb, ScopedDictionary <string, ValueProviderBase> variables)
 {
     sb.Append(Text);
 }
示例#39
0
 /// <summary>
 /// 初始化一个<see cref="LogContext"/>类型的实例
 /// </summary>
 /// <param name="scopedDictionary">作用域字典</param>
 public LogContext(ScopedDictionary scopedDictionary)
 {
     _orderId          = 0;
     _scopedDictionary = scopedDictionary;
 }
 public override void ToString(StringBuilder sb, ScopedDictionary<string, ValueProviderBase> variables)
 {
     sb.Append("@foreach");
     ValueProvider.ToString(sb, variables, null);
     {
         var newVars = new ScopedDictionary<string, ValueProviderBase>(variables);
         ValueProvider.Declare(newVars);
         Block.ToString(sb, newVars);
     }
     sb.Append("@endforeach");
 }
        protected internal override void RenderTemplate(ScopedDictionary<string, ValueProviderBase> variables)
        {
            string str = "@declare" + ValueProvider.ToString(variables, null);

            this.ReplaceBy(new Run(this.RunProperties.TryDo(prop => prop.Remove()), new Text(str)));

            ValueProvider.Declare(variables);
        }
示例#42
0
 /// <summary>
 /// 初始化一个<see cref="MasterSlaveSplitPolicy"/>类型的新实例
 /// </summary>
 public MasterSlaveSplitPolicy(IServiceProvider provider)
 {
     _unitOfWork = provider.GetUnitOfWork(false);
     _scopedDict = provider.GetRequiredService <ScopedDictionary>();
 }
        protected internal override void RenderTemplate(ScopedDictionary<string, ValueProviderBase> variables)
        {
            var parent = this.Parent;
            int index = parent.ChildElements.IndexOf(this);
            this.Remove();
            parent.InsertAt(this.ForeachToken.ReplaceMatchNode("@foreach" + this.ValueProvider.ToString(variables, null)), index++);
            {
                var newVars = new ScopedDictionary<string, ValueProviderBase>(variables);
                ValueProvider.Declare(newVars);
                this.ForeachBlock.RenderTemplate(newVars);
                parent.MoveChildsAt(ref index, this.ForeachBlock.ChildElements);
            }
            parent.InsertAt(this.EndForeachToken.ReplaceMatchNode("@endforeach"), index++);

        }
 protected ExpressionComparer(ScopedDictionary<ParameterExpression, ParameterExpression> parameterScope, bool exactMatch)
 {
     this.parameterScope = parameterScope;
     this.exactMatch = exactMatch;
 }
        protected internal override void RenderTemplate(ScopedDictionary<string, ValueProviderBase> variables)
        {
            var parent = this.Parent;
            int index = parent.ChildElements.IndexOf(this);
            this.Remove();

            var str = "@if" + this.ValueProvider.ToString(variables, Operation == null ? null : FilterValueConverter.ToStringOperation(Operation.Value) + Value);

            parent.InsertAt(this.IfToken.ReplaceMatchNode(str), index++);
            {
                var newVars = new ScopedDictionary<string, ValueProviderBase>(variables);
                this.ValueProvider.Declare(newVars);
                this.IfBlock.RenderTemplate(newVars);
                parent.MoveChildsAt(ref index, this.IfBlock.ChildElements);
            }

            if (this.ElseToken.MatchNode != null)
            {
                parent.InsertAt(this.ElseToken.ReplaceMatchNode("@else"), index++);

                var newVars = new ScopedDictionary<string, ValueProviderBase>(variables);
                this.ValueProvider.Declare(newVars);
                this.ElseBlock.RenderTemplate(newVars);
                parent.MoveChildsAt(ref index, this.ElseBlock.ChildElements);
            }

            parent.InsertAt(this.EndIfToken.ReplaceMatchNode("@endif"), index++);
        }
示例#46
0
 protected ExpressionComparer(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope)
 {
     _parameterScope = parameterScope;
 }
 public abstract void ToString(StringBuilder sb, ScopedDictionary <string, ValueProviderBase> variables);
示例#48
0
 public static bool AreEqual(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope, Expression a, Expression b)
 {
     return(new ExpressionComparer(parameterScope).Compare(a, b));
 }
示例#49
0
 protected DbExpressionComparer(ScopedDictionary <ParameterExpression, ParameterExpression>?parameterScope, ScopedDictionary <Alias, Alias>?aliasScope, bool checkParameterNames)
     : base(parameterScope, checkParameterNames)
 {
     this.aliasMap = aliasScope;
 }
示例#50
0
 protected DbExpressionComparer(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope, ScopedDictionary <TableAlias, TableAlias> aliasScope)
     : base(parameterScope)
 {
     _aliasScope = aliasScope;
 }
示例#51
0
    public IDisposable NewScope()
    {
        Variables = new ScopedDictionary <string, ValueProviderBase>(Variables);

        return(new Disposable(() => Variables = Variables.Previous !));
    }
 protected ExpressionComparer(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope, bool checkParameterNames)
 {
     this.parameterScope      = parameterScope;
     this.checkParameterNames = checkParameterNames;
 }
示例#53
0
        protected internal override void RenderTemplate(ScopedDictionary <string, ValueProviderBase> variables)
        {
            var str = "@" + this.ValueProvider.ToString(variables, Format.HasText() ? (":" + TemplateUtils.ScapeColon(Format)) : null);

            this.ReplaceBy(this.NodeProvider.NewRun((OpenXmlCompositeElement?)this.RunProperties?.CloneNode(true), str));
        }
 public static bool AreEqual(Expression a, Expression b, ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope = null, bool checkParameterNames = false)
 {
     return(new ExpressionComparer(parameterScope, checkParameterNames).Compare(a, b));
 }
示例#55
0
 /// <summary>
 /// 初始化一个<see cref="AuditEntityProvider"/>类型的新实例
 /// </summary>
 public AuditEntityProvider(IServiceProvider provider)
 {
     _logger            = provider.GetLogger(this);
     _scopedDict        = provider.GetService <ScopedDictionary>();
     _entityInfoHandler = provider.GetService <IEntityInfoHandler>();
 }
        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));
            }
        }
示例#57
0
 protected DbExpressionComparer(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope, Func <object, object, bool> fnCompare,
                                ScopedDictionary <TableAlias, TableAlias> aliasScope) : base(parameterScope, fnCompare)
 {
     this.aliasScope = aliasScope;
 }
示例#58
0
        /// <summary>
        /// Called after the action executes, before the action result.
        /// </summary>
        /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext" />.</param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            ScopedDictionary dict    = context.HttpContext.RequestServices.GetService <ScopedDictionary>();
            AjaxResultType   type    = AjaxResultType.Success;
            string           message = null;

            if (context.Exception != null && !context.ExceptionHandled)
            {
                Exception ex = context.Exception;
                _logger.LogError(new EventId(), ex, ex.Message);
                message = ex.Message;
                if (context.HttpContext.Request.IsAjaxRequest() || context.HttpContext.Request.IsJsonContextType())
                {
                    if (!context.HttpContext.Response.HasStarted)
                    {
                        context.Result = new JsonResult(new AjaxResult(ex.Message, AjaxResultType.Error));
                    }
                    context.ExceptionHandled = true;
                }
            }
            if (context.Result is JsonResult result1)
            {
                if (result1.Value is AjaxResult ajax)
                {
                    type    = ajax.Type;
                    message = ajax.Content;
                    if (ajax.Succeeded())
                    {
                        _unitOfWork?.Commit();
                    }
                }
            }
            else if (context.Result is ObjectResult result2)
            {
                if (result2.Value is AjaxResult ajax)
                {
                    type    = ajax.Type;
                    message = ajax.Content;
                    if (ajax.Succeeded())
                    {
                        _unitOfWork?.Commit();
                    }
                }
                else
                {
                    _unitOfWork?.Commit();
                }
            }
            //普通请求
            else if (context.HttpContext.Response.StatusCode >= 400)
            {
                switch (context.HttpContext.Response.StatusCode)
                {
                case 401:
                    type = AjaxResultType.UnAuth;
                    break;

                case 403:
                    type = AjaxResultType.UnAuth;
                    break;

                case 404:
                    type = AjaxResultType.UnAuth;
                    break;

                case 423:
                    type = AjaxResultType.UnAuth;
                    break;

                default:
                    type = AjaxResultType.Error;
                    break;
                }
            }
            else
            {
                type = AjaxResultType.Success;
                _unitOfWork?.Commit();
            }

            if (dict.AuditOperation != null)
            {
                dict.AuditOperation.ResultType = type;
                dict.AuditOperation.Message    = message;
            }
        }
示例#59
0
 public static bool AreEqual(ScopedDictionary <ParameterExpression, ParameterExpression> parameterScope, ScopedDictionary <TableAlias, TableAlias> aliasScope, Expression a, Expression b,
                             Func <object, object, bool> fnCompare)
 {
     return(new DbExpressionComparer(parameterScope, fnCompare, aliasScope).Compare(a, b));
 }
示例#60
0
        public static ValueProviderBase TryParse(string type, string token, string variable, Type modelType, PropertyInfo modelProperty, QueryDescription qd, ScopedDictionary <string, ValueProviderBase> variables, Action <bool, string> addError)
        {
            switch (type)
            {
            case "":
            {
                if (token.StartsWith("$"))
                {
                    string v = token.TryBefore('.') ?? token;

                    if (!variables.TryGetValue(v, out ValueProviderBase vp))
                    {
                        addError(false, "Variable '{0}' is not defined at this scope".FormatWith(v));
                        return(null);
                    }

                    if (!(vp is TokenValueProvider))
                    {
                        return(new ContinueValueProvider(token.TryAfter('.'), vp, addError));
                    }
                }

                ParsedToken result = ParsedToken.TryParseToken(token, SubTokensOptions.CanElement, qd, variables, addError);

                if (result.QueryToken != null && TranslateInstanceValueProvider.IsTranslateInstanceCanditate(result.QueryToken))
                {
                    return new TranslateInstanceValueProvider(result, false, addError)
                           {
                               Variable = variable
                           }
                }
                ;
                else
                {
                    return new TokenValueProvider(result, false)
                           {
                               Variable = variable
                           }
                };
            }

            case "q":
            {
                ParsedToken result = ParsedToken.TryParseToken(token, SubTokensOptions.CanElement, qd, variables, addError);

                return(new TokenValueProvider(result, true)
                    {
                        Variable = variable
                    });
            }

            case "t":
            {
                ParsedToken result = ParsedToken.TryParseToken(token, SubTokensOptions.CanElement, qd, variables, addError);

                return(new TranslateInstanceValueProvider(result, true, addError)
                    {
                        Variable = variable
                    });
            }

            case "m":
                return(new ModelValueProvider(token, modelType, modelProperty, addError)
                {
                    Variable = variable
                });

            case "g":
                return(new GlobalValueProvider(token, addError)
                {
                    Variable = variable
                });

            case "d":
                return(new DateValueProvider(token, addError)
                {
                    Variable = variable
                });

            default:
                addError(false, "{0} is not a recognized value provider (q:Query, t:Translate, m:Model, g:Global or just blank)");
                return(null);
            }
        }