コード例 #1
0
		public override object Build(BuilderContext context)
		{
			return new IgnoreRouteInternal(context.Builtin.Properties.GetRawValue("url"))
			{
				Constraints = this.ResolveValues(context.Builtin.Properties.GetValue<string>("constraints"), context.Builtin)
			};
		}
コード例 #2
0
		public override object Build(BuilderContext context)
		{
			Builtin builtin = context.Builtin;

			var node = new Zongsoft.Web.Controls.TreeViewNode(builtin.Name, builtin.Properties.GetValue<string>("text"))
			{
				Icon = builtin.Properties.GetValue<string>("icon"),
				Text = builtin.Properties.GetValue<string>("text"),
				ToolTip = builtin.Properties.GetValue<string>("tooltip"),
				Description = builtin.Properties.GetValue<string>("description"),
				NavigateUrl = builtin.Properties.GetValue<string>("url") ?? string.Empty,
				NavigateCssClass = builtin.Properties.GetValue<string>("navigateCssClass"),
				CssClass = builtin.Properties.GetValue<string>("cssClass"),
				ListCssClass = builtin.Properties.GetValue<string>("listCssClass"),
				Selected = builtin.Properties.GetValue<bool>("selected", false),
				Visible = builtin.Properties.GetValue<bool>("visible", true),
			};

			node.Image.CssClass = builtin.Properties.GetValue<string>("image-cssClass");
			node.Image.Dimension = builtin.Properties.GetValue<Zongsoft.Web.Controls.Dimension>("image-dimension", Controls.Dimension.None);
			node.Image.ImageUrl = builtin.Properties.GetValue<string>("image-url");
			node.Image.NavigateUrl = builtin.Properties.GetValue<string>("image-navigateUrl");
			node.Image.Placeholder = builtin.Properties.GetValue<string>("image-placeholder");

			//返回构建的目标对象
			return node;
		}
コード例 #3
0
		protected override void OnBuilt(BuilderContext context)
		{
			Control itemControl = context.Result as Control;

			if(itemControl == null)
				return;

			itemControl.ID = context.Builtin.Name;
			Control ownerControl = context.Owner as Control ?? context.Parameter as Control;

			if(ownerControl == null)
				return;

			string index = context.Builtin.Properties.GetValue<string>("index");

			if(!string.IsNullOrWhiteSpace(index))
			{
				for(int i = 0; i < ownerControl.Controls.Count; i++)
				{
					if(string.Equals(ownerControl.Controls[i].ID, index, StringComparison.OrdinalIgnoreCase))
					{
						ownerControl.Controls.AddAt(i, itemControl);
						return;
					}
				}
			}

			ownerControl.Controls.Add(itemControl);
		}
コード例 #4
0
		public void TestNoPoliciesReturnsNull()
		{
			PolicyList policies = new PolicyList();
			BuilderContext context = new BuilderContext(null, null, policies);

			Assert.IsNull(context.Policies.Get<IBuilderPolicy>(typeof (object), null));
		}
コード例 #5
0
            public void SetUp( BuilderContext obj )
            {
//                var routes = this._junctionEdge.EdgeBuilder.Routes;
//                var convertedRoutes = this.ConvertRoutes( routes, obj, this._junctionEdge ).ToArray();
                // TODO Remove Routes from this element
                this._junctionEdge.Routes = new StandardRoutes( Enumerable.Empty<BuildRoute>());
            }
コード例 #6
0
 /// <summary>
 /// Builds the ExpressionQuery:
 /// - parses Expressions and builds row creator
 /// - checks names unicity
 /// </summary>
 /// <param name="expressions"></param>
 /// <param name="queryContext"></param>
 /// <returns></returns>
 protected virtual ExpressionQuery BuildExpressionQuery(ExpressionChain expressions, QueryContext queryContext)
 {
     var builderContext = new BuilderContext(queryContext);
     BuildExpressionQuery(expressions, builderContext);
     CheckTablesAlias(builderContext);
     CheckParametersAlias(builderContext);
     return builderContext.ExpressionQuery;
 }
コード例 #7
0
            public void SetUp(BuilderContext obj)
            {
//                this._lane.LaneCornerBuild.Routes.CalculateProbabilities();
//                var routes = this._lane.LaneCornerBuild.Routes;
//                var convertedRoutes = this.ConvertRoutes( routes, obj, this._lane ).ToArray();
                // TODO Remove Routes from this element
                this._lane.Routes = new StandardRoutes( Enumerable.Empty<BuildRoute>() );
            }
コード例 #8
0
 public void Connect( BuilderContext builderContext )
 {
     this._junctionEdge.Junction = builderContext.GetObject<LaneJunction>( this._junctionEdge.EdgeBuilder.Connector.JunctionEdge.Parent );
     if ( this._junctionEdge.EdgeBuilder.Connector.Edge != null )
     {
         this._junctionEdge.Next = builderContext.GetObject<IRoadElement>( this._junctionEdge.EdgeBuilder.Connector.Edge.Parent );
     }
 }
コード例 #9
0
		public override object Build(BuilderContext context)
		{
			return new HtmlForm()
			{
				Action = context.Builtin.Properties.GetValue<string>("action"),
				Method = context.Builtin.Properties.GetValue<string>("method"),
			};
		}
 private BuildRoute ConvertRoute( BuildMode.Controls.Route route, BuilderContext context, IRoadElement routeOwner )
 {
     return new BuildRoute( this.GetRouteElements( route, context, routeOwner ) )
                {
                    Probability = route.Probability,
                    Name = route.Name,
                    Owner = routeOwner,
                };
 }
コード例 #11
0
 public void Connect( BuilderContext builderContext )
 {
     var connectedLane = this._carsRemover.CarsRemoverBuilder.Connector.OpositeEdge;
     if ( connectedLane == null )
     {
         return;
     }
     this._carsRemover.Lane = builderContext.GetObject<Lane>( connectedLane.Parent );
 }
コード例 #12
0
		public void CanSetPoliciesUsingTheContext()
		{
			BuilderContext context = new BuilderContext(null, null, null);
			MockCreationPolicy policy = new MockCreationPolicy();

			context.Policies.Set<IBuilderPolicy>(policy, typeof (object), "foo");

			Assert.AreSame(policy, context.Policies.Get<IBuilderPolicy>(typeof (object), "foo"));
		}
コード例 #13
0
ファイル: EntitySetExpression.cs プロジェクト: nlhepler/mono
 internal EntitySetExpression(TableExpression sourceTable, MemberInfo memberInfo, Type entitySetType, BuilderContext builderContext, ExpressionDispatcher dispatcher)
     : base(ExpressionType, entitySetType)
 {
     this.builderContext = builderContext;
     this.EntitySetType = entitySetType;
     this.dispatcher = dispatcher;
     this.sourceTable = sourceTable;
     this.memberInfo = memberInfo;
     ParseExpression(sourceTable);
 }
コード例 #14
0
        public IEnumerable<IRoadElement> ConvertToSimulationMode( IEnumerable<IControl> controls )
        {
            Contract.Requires( controls != null );
            var context = new BuilderContext( this._roadInformationFactory );
            controls.Where( c => c != null )
                .SelectMany( this.GetAction )
                .OrderBy( a => a.Order )
                .ForEach( a => a.Action( context ) );

            return context.Elements;
        }
コード例 #15
0
		public void TestSettingAndRetrievePolicy()
		{
			PolicyList policies = new PolicyList();
			MockCreationPolicy policy = new MockCreationPolicy();

			policies.Set<IBuilderPolicy>(policy, typeof (object), null);
			BuilderContext context = new BuilderContext(null, null, policies);

			IBuilderPolicy outPolicy = context.Policies.Get<IBuilderPolicy>(typeof (object), null);

			Assert.IsNotNull(outPolicy);
			Assert.AreSame(policy, outPolicy);
		}
コード例 #16
0
		public override object Build(BuilderContext context)
		{
			string url = context.Builtin.Properties.GetRawValue("url");

			if(string.IsNullOrWhiteSpace(url))
				return base.Build(context);

			TemplateControl template = context.Owner as TemplateControl;
			if(template != null)
				return template.LoadControl(url);

			return null;
		}
コード例 #17
0
		public void SettingPolicyViaContextDoesNotAffectPoliciesPassedToContextConstructor()
		{
			PolicyList policies = new PolicyList();
			MockCreationPolicy policy1 = new MockCreationPolicy();

			policies.Set<IBuilderPolicy>(policy1, typeof (object), null);
			BuilderContext context = new BuilderContext(null, null, policies);

			MockCreationPolicy policy2 = new MockCreationPolicy();
			context.Policies.Set<IBuilderPolicy>(policy2, typeof (string), null);

			Assert.AreEqual(1, policies.Count);
		}
コード例 #18
0
		public override object Build(BuilderContext context)
		{
			string path = context.Builtin.Properties.GetRawValue("path");
			PluginTreeNode node = null;

			if(PluginPath.IsPath(path))
				node = context.PluginTree.Find(path);
			else
				node = context.PluginTree.Find(context.Builtin.FullPath);

			return new Sitemap(node)
			{
				ID = context.Builtin.Name,
				CssClass = context.Builtin.Properties.GetValue<string>("cssClass"),
			};
		}
コード例 #19
0
		public override object Build(BuilderContext context)
		{
			var treeView = new Zongsoft.Web.Controls.TreeView()
			{
				ID = context.Builtin.Name,
				CssClass = context.Builtin.Properties.GetValue<string>("cssClass"),
				DataSource = context.Builtin.Properties.GetValue<object>("dataSource"),
				IsDropdown = context.Builtin.Properties.GetValue<bool>("isDropdown"),
				RenderMode = context.Builtin.Properties.GetValue<Zongsoft.Web.Controls.ListRenderMode>("renderMode", Zongsoft.Web.Controls.ListRenderMode.List),
				Height = context.Builtin.Properties.GetValue<Zongsoft.Web.Controls.Unit>("height", Zongsoft.Web.Controls.Unit.Empty),
				Width = context.Builtin.Properties.GetValue<Zongsoft.Web.Controls.Unit>("width", Zongsoft.Web.Controls.Unit.Empty),
				ScrollbarMode = context.Builtin.Properties.GetValue<Zongsoft.Web.Controls.ScrollbarMode>("scrollbarMode", Zongsoft.Web.Controls.ScrollbarMode.None),
				SelectionMode = context.Builtin.Properties.GetValue<Zongsoft.Web.Controls.SelectionMode>("selectionMode", Zongsoft.Web.Controls.SelectionMode.None),
				Visible = context.Builtin.Properties.GetValue<bool>("visible", true),
			};

			return treeView;
		}
        private IEnumerable<RouteElement> GetRouteElements( BuildMode.Controls.Route route, BuilderContext context, IRoadElement routeOwner )
        {
            return route.Items.Select( ( index, prev, current, next ) =>
                                           {
                                               var nextElement = next != null ? next.Control : null;
                                               var prevElement = prev != null ? prev.Control : null;
                                               if ( prevElement == null && index == 0 )
                                               {
                                                   prevElement = routeOwner.BuildControl;
                                               }

                                               return new RouteElement
                                                          {
                                                              PriorityType = current.PriorityType,
                                                              RoadElement = this.GetRoadElement( context, current.Control ),
                                                              Length = this.GetLength( prevElement, current, nextElement ),
                                                              CanStopOnIt = current.CanStop,
                                                          };
                                           } );
        }
コード例 #21
0
		protected override void OnBuilt(BuilderContext context)
		{
			if(context.Owner == null)
				return;

			var node = context.Result as Zongsoft.Web.Controls.TreeViewNode;

			if(node == null)
				return;

			//根据所有者对象的类型,将当前目标对象添加到其子项列表中
			if(context.Owner is Zongsoft.Web.Controls.TreeViewNode)
			{
				((Zongsoft.Web.Controls.TreeViewNode)context.Owner).Nodes.Add(node);
			}
			else if(context.Owner is Zongsoft.Web.Controls.TreeView)
			{
				((Zongsoft.Web.Controls.TreeView)context.Owner).Nodes.Add(node);
			}
		}
コード例 #22
0
		protected override void OnBuilt(BuilderContext context)
		{
			if(context.Result is RouteBase)
			{
				var routes = RouteTable.Routes;

				if(context.Owner is RouteCollection)
					routes = (RouteCollection)context.Owner;

				routes.Add(context.Builtin.Name, (RouteBase)context.Result);
			}
			else if(context.Result is System.Web.Http.Routing.IHttpRoute)
			{
				var routes = System.Web.Http.GlobalConfiguration.Configuration.Routes;

				if(context.Owner is System.Web.Http.HttpRouteCollection)
					routes = (System.Web.Http.HttpRouteCollection)context.Owner;

				routes.Add(context.Builtin.Name, (System.Web.Http.Routing.IHttpRoute)context.Result);
			}
			else
				base.OnBuilt(context);
		}
コード例 #23
0
ファイル: Parser.cs プロジェクト: dusdong/BaseComponent
 public override void Parse(System.Linq.Expressions.Expression expression)
 {
     _expression = expression;
     parser.ElementType = ElementType;
     parser.Parse(expression);
     var provider = ProviderFactory.CreateProvider(ConfigManager.DataBaseType);
     var builderFactory = provider.CreateSqlBuilderFactory();
     var builder = builderFactory.CreateSqlBuilder();
     BuilderContext context = new BuilderContext();
     var sqlType = SqlType.Select;
     if (parser.IsCallAny)
     {
         context.Take = 1;
     }
     if (parser.IsDelete)
     {
         sqlType = SqlType.Delete;
     }
     else if (parser.IsUpdate)
     {
         sqlType = SqlType.Update;
     }
     context.SqlType = sqlType;
     context.Pager = parser.Skip != -1 && parser.Take != -1;
     context.SortColumns = parser.SortColumns;
     context.Joins = parser.Joins;
     context.UpdateResult = parser.UpdateResult;
     context.Skip = parser.Skip;
     context.Take = parser.Take;
     context.AggregationColumns = parser.AggregationColumns;
     context.Columns = parser.Columns;
     context.NoLockTables = parser.NoLockTables;
     context.Conditions = parser.Conditions;
     context.ElementType = parser.ElementType;
     Result = builder.BuildSql(context);
 }
コード例 #24
0
		public override object Build(BuilderContext context)
		{
			Builtin builtin = context.Builtin;

			string url = builtin.Properties.GetRawValue("url");
			var defaults = ResolveValues(builtin.Properties.GetValue<string>("defaults"), builtin);
			var dataTokens = ResolveValues(builtin.Properties.GetValue<string>("dataTokens"), builtin);
			var constraints = ResolveValues(builtin.Properties.GetValue<string>("constraints"), builtin);

			if(!dataTokens.ContainsKey("area"))
			{
				object area = null;

				if(constraints.TryGetValue("area", out area))
					dataTokens.Add("area", area);
				else
					dataTokens.Add("area", VirtualPathUtility.GetArea(url));
			}

			if(this.IsApiUrl(url))
			{
				return System.Web.Http.GlobalConfiguration.Configuration.Routes.CreateRoute(
								url,
								defaults,
								constraints,
								dataTokens);
			}
			else
			{
				return new Route(url,
								 defaults,
								 constraints,
								 dataTokens,
								 builtin.Properties.GetValue<IRouteHandler>("handler", new System.Web.Mvc.MvcRouteHandler()));
			}
		}
コード例 #25
0
 protected abstract void ConvertToSqlConditional(Expression exp, ref CharWriteBuffer sb, BuilderContext context);
コード例 #26
0
 public virtual Expression Optimize(Expression expression, BuilderContext builderContext)
 {
     return(expression.Recurse(e => Analyze(e, builderContext)));
 }
コード例 #27
0
        /// <summary>
        /// Registers an external parameter
        /// Since these can be complex expressions, we don't try to identify them
        /// and push them every time
        /// The only loss may be a small memory loss (if anyone can prove me that the same Expression can be used twice)
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="alias"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual InputParameterExpression RegisterParameter(Expression expression, string alias, BuilderContext builderContext)
        {
            var queryParameterExpression = new InputParameterExpression(expression, alias);

            builderContext.ExpressionQuery.Parameters.Add(queryParameterExpression);
            return(queryParameterExpression);
        }
コード例 #28
0
 public BuildStepService(BuilderContext context, IMapper mapper) : base(context, mapper)
 {
 }
コード例 #29
0
ファイル: PackageBuilder.cs プロジェクト: kingland/stride
        private BuildResultCode BuildSlave()
        {
            // Mount build path
            ((FileSystemProvider)VirtualFileSystem.ApplicationData).ChangeBasePath(builderOptions.BuildDirectory);

            VirtualFileSystem.CreateDirectory(VirtualFileSystem.ApplicationDatabasePath);

            // Open ServiceWire Client Channel
            using (var client = new NpClient <IProcessBuilderRemote>(new NpEndPoint(builderOptions.SlavePipe), new StrideServiceWireSerializer()))
            {
                RegisterRemoteLogger(client);

                // Make sure to laod all assemblies containing serializers
                // TODO: Review how costly it is to do so, and possibily find a way to restrict what needs to be loaded (i.e. only app plugins?)
                foreach (var assemblyLocation in client.Proxy.GetAssemblyContainerLoadedAssemblies())
                {
                    AssemblyContainer.Default.LoadAssemblyFromPath(assemblyLocation, builderOptions.Logger);
                }

                // Create scheduler
                var scheduler = new Scheduler();

                var status = ResultStatus.NotProcessed;

                // Schedule command
                string buildPath = builderOptions.BuildDirectory;

                Builder.OpenObjectDatabase(buildPath, VirtualFileSystem.ApplicationDatabaseIndexName);

                var         logger      = builderOptions.Logger;
                MicroThread microthread = scheduler.Add(async() =>
                {
                    // Deserialize command and parameters
                    Command command = client.Proxy.GetCommandToExecute();

                    // Run command
                    var inputHashes    = FileVersionTracker.GetDefault();
                    var builderContext = new BuilderContext(inputHashes, null);

                    var commandContext = new RemoteCommandContext(client.Proxy, command, builderContext, logger);
                    MicrothreadLocalDatabases.MountDatabase(commandContext.GetOutputObjectsGroups());
                    command.PreCommand(commandContext);
                    status = await command.DoCommand(commandContext);
                    command.PostCommand(commandContext, status);

                    // Returns result to master builder
                    client.Proxy.RegisterResult(commandContext.ResultEntry);
                });

                while (true)
                {
                    scheduler.Run();

                    // Exit loop if no more micro threads
                    lock (scheduler.MicroThreads)
                    {
                        if (!scheduler.MicroThreads.Any())
                        {
                            break;
                        }
                    }

                    Thread.Sleep(0);
                }

                // Rethrow any exception that happened in microthread
                if (microthread.Exception != null)
                {
                    builderOptions.Logger.Fatal(microthread.Exception.ToString());
                    return(BuildResultCode.BuildError);
                }

                if (status == ResultStatus.Successful || status == ResultStatus.NotTriggeredWasSuccessful)
                {
                    return(BuildResultCode.Successful);
                }

                return(BuildResultCode.BuildError);
            }
        }
コード例 #30
0
ファイル: nullable.cs プロジェクト: gongfuPanada/NRefactory
 public override SLE.Expression MakeExpression(BuilderContext ctx)
 {
     return Binary.MakeExpression (ctx, Left, Right);
 }
コード例 #31
0
        async void OnItemSelected(object sender, SelectedItemChangedEventArgs args)
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;
            //viewModel.Items.Clear();
            var item = args.SelectedItem as Models.Character;

            if (item == null)
            {
                return;
            }
            BuilderContext Context = new BuilderContext(item.Player);
            PluginManager  manager = new PluginManager();

            manager.Add(new SpellPoints());
            manager.Add(new SingleLanguage());
            Context.Plugins = manager;

            if (App.AutoSaveDuringPlay)
            {
                Task.Run(async() =>
                {
                    if (Context.Player.FilePath is IFile file)
                    {
                        string name  = file.Name;
                        IFile target = await(await App.Storage.CreateFolderAsync("Backups", CreationCollisionOption.OpenIfExists).ConfigureAwait(false)).CreateFileAsync(name, CreationCollisionOption.ReplaceExisting).ConfigureAwait(false);
                        using (Stream fout = await target.OpenAsync(FileAccess.ReadAndWrite))
                        {
                            using (Stream fin = await file.OpenAsync(FileAccess.Read))
                            {
                                await fin.CopyToAsync(fout);
                            }
                        };
                    }
                }).Forget();
            }
            Context.UndoBuffer         = new LinkedList <Player>();
            Context.RedoBuffer         = new LinkedList <Player>();
            Context.UnsavedChanges     = 0;
            ItemsListView.SelectedItem = null;
            LoadingProgress loader = new LoadingProgress(Context);
            LoadingPage     l      = new LoadingPage(loader);
            await Navigation.PushModalAsync(l);

            var t = l.Cancel.Token;

            try
            {
                await loader.Load(t).ConfigureAwait(false);

                t.ThrowIfCancellationRequested();
                PlayerViewModel model = new PlayerViewModel(Context);
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await Navigation.PopModalAsync(false);
                    await Navigation.PushModalAsync(new NavigationPage(new FlowPage(model)));
                });
            }
            catch (OperationCanceledException) {
            }
            finally
            {
                IsBusy = false;
                (sender as ListView).SelectedItem = null;
            }
            // Manually deselect item
        }
コード例 #32
0
        /// <summary>
        /// Promotes a table to a common parent between its current scope and our current scope
        /// </summary>
        /// <param name="tableExpression"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        protected virtual TableExpression PromoteTable(TableExpression tableExpression, BuilderContext builderContext)
        {
            int currentIndex             = 0;
            SelectExpression oldSelect   = null;
            SelectExpression commonScope = null;
            TableExpression  foundTable  = null;

            do
            {
                // take a select
                oldSelect = builderContext.SelectExpressions[currentIndex];

                // look for a common scope
                if (oldSelect != builderContext.CurrentSelect)
                {
                    commonScope = FindCommonScope(oldSelect, builderContext.CurrentSelect);
                    if (commonScope != null)
                    {
                        // if a common scope exists, look for an equivalent table in that select
                        for (int tableIndex = 0; tableIndex < oldSelect.Tables.Count && foundTable == null; tableIndex++)
                        {
                            if (oldSelect.Tables[tableIndex].IsEqualTo(tableExpression))
                            {
                                // found a matching table!
                                foundTable = oldSelect.Tables[tableIndex];
                            }
                        }
                    }
                }
                ++currentIndex;
            }while (currentIndex < builderContext.SelectExpressions.Count && foundTable == null);

            if (foundTable != null)
            {
                oldSelect.Tables.Remove(foundTable);
                commonScope.Tables.Add(foundTable);
            }
            return(foundTable);
        }
コード例 #33
0
 public GroupService(BuilderContext context, IMapper mapper, INotificationsService notificationsService) : base(context, mapper)
 {
     _notificationsService = notificationsService;
 }
コード例 #34
0
ファイル: nullable.cs プロジェクト: Paccc/SharpDevelop
		public override SLE.Expression MakeExpression (BuilderContext ctx)
		{
			return expr.MakeExpression (ctx);
		}
コード例 #35
0
 public PlayerModel(BuilderContext context)
 {
     Context = context;
 }
コード例 #36
0
        public ColumnExpression CreateColumn(TableExpression table, MemberInfo memberInfo, BuilderContext builderContext)
        {
            var dataMember = builderContext.QueryContext.DataContext.Mapping.GetTable(table.Type).RowType
                             .GetDataMember(memberInfo);

            if (dataMember == null)
            {
                return(null);
            }
            return(new ColumnExpression(table, dataMember));
        }
コード例 #37
0
		public override SLE.Expression MakeExpression (BuilderContext ctx)
		{
#if STATIC
			return base.MakeExpression (ctx);
#else

#if NET_4_0 || MONODROID
				if (type.IsStruct && !obj.Expression.Type.IsValueType)
					return SLE.Expression.Unbox (obj.Expression, type.GetMetaInfo ());

				if (obj.Expression.NodeType == SLE.ExpressionType.Parameter) {
					if (((SLE.ParameterExpression) obj.Expression).IsByRef)
						return obj.Expression;
				}
	#endif

				return SLE.Expression.Convert (obj.Expression, type.GetMetaInfo ());
#endif
		}
コード例 #38
0
 /// <summary>
 /// Creates a default TableExpression
 /// </summary>
 /// <param name="tableType"></param>
 /// <param name="builderContext"></param>
 /// <returns></returns>
 public virtual TableExpression CreateTable(Type tableType, BuilderContext builderContext)
 {
     return(new TableExpression(tableType, DataMapper.GetTableName(tableType, builderContext.QueryContext.DataContext)));
 }
コード例 #39
0
        protected void ConvertToSqlValue(Type type, object value, ref CharWriteBuffer sb, BuilderContext context)
        {
            MemberExpression memberProperty = null;

            if (context.MemberContext.MemberAccessStack.Count > 0)
            {
                memberProperty = context.MemberContext.MemberAccessStack.Pop();
            }

            bool memberPropertyHandled = ConvertToSqlValueRender(memberProperty, type, value, ref sb, context);

            if (memberProperty != null)
            {
                if (!memberPropertyHandled)
                {
                    throw new NotSupportedException($"{type.FullName}.{memberProperty.Member.Name} not supported");
                }
                context.MemberContext.MemberAccessStack.Push(memberProperty);
            }
        }
コード例 #40
0
 public override System.Linq.Expressions.Expression MakeExpression(BuilderContext ctx)
 {
     return(expr.MakeExpression(ctx));
 }
コード例 #41
0
 public ProjectGroupService(BuilderContext context, IMapper mapper) : base(context, mapper)
 {
 }
コード例 #42
0
        private void ConvertToSqlUnary(Operator prefixOperation, string suffixOperation, Expression exp, ref CharWriteBuffer sb, BuilderContext context)
        {
            context.MemberContext.OperatorStack.Push(prefixOperation);

            var unary = exp as UnaryExpression;

            sb.Write(OperatorToString(prefixOperation));

            ConvertToSql(unary.Operand, ref sb, context);

            sb.Write(suffixOperation);

            context.MemberContext.OperatorStack.Pop();
        }
コード例 #43
0
ファイル: nullable.cs プロジェクト: gongfuPanada/NRefactory
 public override SLE.Expression MakeExpression(BuilderContext ctx)
 {
     return expr.MakeExpression (ctx);
 }
コード例 #44
0
        private void ConvertToSqlBinary(Operator operation, Expression exp, ref CharWriteBuffer sb, BuilderContext context)
        {
            context.MemberContext.OperatorStack.Push(operation);

            var binary = exp as BinaryExpression;

            var binaryLeft  = binary.Left;
            var binaryRight = binary.Right;

            if (operation == Operator.Equals || operation == Operator.NotEquals)
            {
                var leftNull  = IsNull(binaryLeft);
                var rightNull = false;
                if (leftNull == false)
                {
                    rightNull = IsNull(binaryRight);
                }
                if (leftNull || rightNull)
                {
                    operation = operation == Operator.Equals ? Operator.EqualsNull : Operator.NotEqualsNull;
                    if (leftNull)
                    {
                        binaryLeft = binaryRight;
                    }
                    binaryRight = null;
                }
            }

            sb.Write('(');
            ConvertToSql(binaryLeft, ref sb, context);
            sb.Write(')');

            sb.Write(OperatorToString(operation));

            if (binaryRight != null)
            {
                sb.Write('(');
                ConvertToSql(binaryRight, ref sb, context);
                sb.Write(')');
            }
            else
            {
                sb.Write(" NULL");
            }

            context.MemberContext.OperatorStack.Pop();
        }
コード例 #45
0
        public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
        {
            Task.Run(async() =>
            {
                if ("Inbox".Equals(Path.GetFileName(Path.GetDirectoryName(url.Path))))
                {
                    IFolder incoming = await App.Storage.CreateFolderAsync("Incoming", CreationCollisionOption.OpenIfExists);
                    IFile f          = await FileSystem.Current.GetFileFromPathAsync(url.Path);
                    await f.MoveAsync(Path.Combine(incoming.Path, f.Name), NameCollisionOption.GenerateUniqueName);
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(incoming));
                    });
                }
                else if (url.Path?.EndsWith(".cb5") ?? false)
                {
                    url.StartAccessingSecurityScopedResource();
                    try {
                        //using (MemoryStream s = new MemoryStream()) {
                        //    NSInputStream stream = NSInputStream.FromUrl(url);
                        //    byte[] buffer = new byte[1024];
                        //    while (stream.HasBytesAvailable()) {
                        //        int read = (int)stream.Read(buffer, 1024);
                        //        s.Write(buffer, 0, read);
                        //    }
                        //    s.Seek(0, SeekOrigin.Begin);
                        //NSFileHandle fs = NSFileHandle.OpenReadUrl(url, out NSError err);
                        //NSData data = fs.ReadDataToEndOfFile();
                        //fs.CloseFile();
                        //using (Stream f = data.AsStream()) {AsStream
                        //new MyInputStream(NSInputStream.FromUrl(url))) {
                        //NSData d = await url.LoadDataAsync("text/xml");
                        //File.OpenRead(url.Path)
                        using (Stream s = File.OpenRead(url.Path)) {
                            Player player          = Player.Serializer.Deserialize(s) as Player;
                            BuilderContext Context = new BuilderContext(player);
                            PluginManager manager  = new PluginManager();
                            manager.Add(new SpellPoints());
                            manager.Add(new SingleLanguage());
                            manager.Add(new CustomBackground());
                            manager.Add(new NoFreeEquipment());
                            Context.Plugins = manager;


                            Context.UndoBuffer     = new LinkedList <Player>();
                            Context.RedoBuffer     = new LinkedList <Player>();
                            Context.UnsavedChanges = 0;

                            Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                            {
                                LoadingProgress loader   = new LoadingProgress(Context);
                                LoadingPage l            = new LoadingPage(loader, false);
                                App.MainTab.SelectedItem = App.MainTab.Children[1];
                                await App.MainTab.Children[2].Navigation.PushModalAsync(l);
                                var t = l.Cancel.Token;
                                try
                                {
                                    await loader.Load(t).ConfigureAwait(false);
                                    t.ThrowIfCancellationRequested();
                                    PlayerBuildModel model = new PlayerBuildModel(Context);
                                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                                    {
                                        await App.MainTab.Children[1].Navigation.PopModalAsync(false);
                                        await App.MainTab.Children[1].Navigation.PushModalAsync(new NavigationPage(new FlowPage(model)));
                                    });
                                } catch (Exception e) {
                                    ConfigManager.LogError(e);
                                }
                            });
                        }
                        url.StopAccessingSecurityScopedResource();
                    }
                    catch (Exception e)
                    {
                        ConfigManager.LogError(e);
                    }
                }
                else if (url.Path.StartsWith(App.Storage.Path, System.StringComparison.Ordinal))
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(await FileSystem.Current.GetFolderFromPathAsync(Path.GetDirectoryName(url.Path))));
                    });
                }
                else
                {
                    url.StartAccessingSecurityScopedResource();
                    IFolder incoming = await App.Storage.CreateFolderAsync("Incoming", CreationCollisionOption.OpenIfExists);
                    IFile target     = await incoming.CreateFileAsync(url.LastPathComponent, CreationCollisionOption.GenerateUniqueName);
                    using (Stream f = File.OpenRead(url.Path))
                    {
                        using (Stream o = await target.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
                        {
                            await f.CopyToAsync(o);
                        }
                    }
                    url.StopAccessingSecurityScopedResource();
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(incoming));
                    });
                }
            }).Forget();
            return(true);
        }
コード例 #46
0
        private void ConvertToSqlConstant(Expression exp, ref CharWriteBuffer sb, BuilderContext context)
        {
            var constant = exp as ConstantExpression;

            ConvertToSqlConstantStack(constant.Type, constant.Value, ref sb, context);
        }
コード例 #47
0
ファイル: PackageBuilder.cs プロジェクト: kingland/stride
        public async Task <ResultStatus> TryExecuteRemote(Command command, BuilderContext builderContext, IExecuteContext executeContext, LocalCommandContext commandContext)
        {
            while (!CanSpawnParallelProcess())
            {
                await Task.Delay(1, command.CancellationToken);
            }

            var address   = "Stride/CompilerApp/PackageBuilderApp/" + Guid.NewGuid();
            var arguments = $"--slave=\"{address}\" --build-path=\"{builderOptions.BuildDirectory}\"";

            using (var debugger = VisualStudioDebugger.GetAttached())
            {
                if (debugger != null)
                {
                    arguments += $" --reattach-debugger={debugger.ProcessId}";
                }
            }

            // Start ServiceWire pipe for communication with process
            var processBuilderRemote = new ProcessBuilderRemote(assemblyContainer, commandContext, command);
            var host = new NpHost(address, null, null, new StrideServiceWireSerializer());

            host.AddService <IProcessBuilderRemote>(processBuilderRemote);

            var startInfo = new ProcessStartInfo
            {
                // Note: try to get exec server if it exists, otherwise use CompilerApp.exe
                FileName               = (string)AppDomain.CurrentDomain.GetData("RealEntryAssemblyFile") ?? typeof(PackageBuilder).Assembly.Location,
                Arguments              = arguments,
                WorkingDirectory       = Environment.CurrentDirectory,
                CreateNoWindow         = true,
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
            };

            host.Open();

            var output = new List <string>();

            var process = new Process {
                StartInfo = startInfo
            };

            process.Start();
            process.OutputDataReceived += (_, args) => LockProcessAndAddDataToList(process, output, args);
            process.ErrorDataReceived  += (_, args) => LockProcessAndAddDataToList(process, output, args);
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            // Note: we don't want the thread to schedule another job since the CPU core will be in use by the process, so we do a blocking WaitForExit.
            process.WaitForExit();

            host.Close();

            NotifyParallelProcessEnded();

            if (process.ExitCode != 0)
            {
                executeContext.Logger.Error($"Remote command crashed with output:{Environment.NewLine}{string.Join(Environment.NewLine, output)}");
            }

            if (processBuilderRemote.Result != null)
            {
                // Register results back locally
                foreach (var outputObject in processBuilderRemote.Result.OutputObjects)
                {
                    commandContext.RegisterOutput(outputObject.Key, outputObject.Value);
                }

                // Register log messages
                foreach (var logMessage in processBuilderRemote.Result.LogMessages)
                {
                    commandContext.Logger.Log(logMessage);
                }

                // Register tags
                foreach (var tag in processBuilderRemote.Result.TagSymbols)
                {
                    commandContext.AddTag(tag.Key, tag.Value);
                }
            }

            return(command.CancellationToken.IsCancellationRequested ? ResultStatus.Cancelled : (process.ExitCode == 0 ? ResultStatus.Successful : ResultStatus.Failed));
        }
コード例 #48
0
        private void ConvertToSqlConstantStack(Type type, object value, ref CharWriteBuffer sb, BuilderContext context)
        {
            if (context.MemberContext.MemberAccessStack.Count > 0)
            {
                var memberProperty = context.MemberContext.MemberAccessStack.Pop();
                if (value == null)
                {
                    sb.Write("NULL");
                }
                else
                {
                    switch (memberProperty.Member.MemberType)
                    {
                    case MemberTypes.Field:
                    {
                        var    field      = memberProperty.Member as FieldInfo;
                        object fieldValue = field.GetValue(value);
                        ConvertToSqlConstantStack(field.FieldType, fieldValue, ref sb, context);
                        break;
                    }

                    case MemberTypes.Property:
                    {
                        var    property      = memberProperty.Member as PropertyInfo;
                        object propertyValue = property.GetValue(value);
                        ConvertToSqlConstantStack(property.PropertyType, propertyValue, ref sb, context);
                        break;
                    }

                    default:
                        throw new NotImplementedException();
                    }
                }

                context.MemberContext.MemberAccessStack.Push(memberProperty);
            }
            else
            {
                ConvertToSqlValue(type, value, ref sb, context);
            }
        }
コード例 #49
0
        private Expression AnalyzeBinaryBoolean(Expression expression, BuilderContext builderContext)
        {
            if (expression.Type != typeof(bool))
            {
                return(expression);
            }
            var bin = expression as BinaryExpression;

            if (bin == null)
            {
                return(expression);
            }
            bool canOptimizeLeft  = bin.Left.NodeType == ExpressionType.Constant && bin.Left.Type == typeof(bool);
            bool canOptimizeRight = bin.Right.NodeType == ExpressionType.Constant && bin.Right.Type == typeof(bool);

            if (canOptimizeLeft && canOptimizeRight)
            {
                return(Expression.Constant(expression.Evaluate()));
            }
            if (canOptimizeLeft || canOptimizeRight)
            {
                switch (expression.NodeType)
                {
                case ExpressionType.AndAlso:
                    if (canOptimizeLeft)
                    {
                        if ((bool)bin.Left.Evaluate())
                        {
                            return(bin.Right);      // (TRUE and X) == X
                        }
                        else
                        {
                            return(bin.Left);       // (FALSE and X) == FALSE
                        }
                    }
                    if (canOptimizeRight)
                    {
                        if ((bool)bin.Right.Evaluate())
                        {
                            return(bin.Left);       // (X and TRUE) == X
                        }
                        else
                        {
                            return(bin.Right);      // (X and FALSE) == FALSE
                        }
                    }
                    break;

                case ExpressionType.OrElse:
                    if (canOptimizeLeft)
                    {
                        if ((bool)bin.Left.Evaluate())
                        {
                            return(bin.Left);       // (TRUE or X) == TRUE
                        }
                        else
                        {
                            return(bin.Right);      // (FALSE or X) == X
                        }
                    }
                    if (canOptimizeRight)
                    {
                        if ((bool)bin.Right.Evaluate())
                        {
                            return(bin.Right);      // (X or TRUE) == TRUE
                        }
                        else
                        {
                            return(bin.Left);       // (X or FALSE) == X
                        }
                    }
                    break;

                case ExpressionType.Equal:
                    // TODO: this optimization should work for Unary Expression Too
                    // this actually produce errors becouse of string based Sql generation
                    canOptimizeLeft = canOptimizeLeft && bin.Right is BinaryExpression;
                    if (canOptimizeLeft)
                    {
                        if ((bool)bin.Left.Evaluate())
                        {
                            return(bin.Right);                      // (TRUE == X) == X
                        }
                        else
                        {
                            return(Expression.Not(bin.Right));      // (FALSE == X) == not X
                        }
                    }
                    canOptimizeRight = canOptimizeRight && bin.Left is BinaryExpression;
                    // TODO: this optimization should work for Unary Expression Too
                    // this actually produce errors becouse of string based Sql generation
                    if (canOptimizeRight)
                    {
                        if ((bool)bin.Right.Evaluate())
                        {
                            return(bin.Left);                       // (X == TRUE) == X
                        }
                        else
                        {
                            return(Expression.Not(bin.Left));       // (X == FALSE) == not X
                        }
                    }
                    break;

                case ExpressionType.NotEqual:
                    canOptimizeLeft = canOptimizeLeft && bin.Right is BinaryExpression;
                    // TODO: this optimization should work for Unary Expression Too
                    // this actually produce errors becouse of string based Sql generation
                    if (canOptimizeLeft)
                    {
                        if ((bool)bin.Left.Evaluate())
                        {
                            return(Expression.Not(bin.Right));      // (TRUE != X) == not X
                        }
                        else
                        {
                            return(bin.Right);                      // (FALSE != X) == X
                        }
                    }
                    canOptimizeRight = canOptimizeRight && bin.Left is BinaryExpression;
                    // TODO: this optimization should work for Unary Expression Too
                    // this actually produce errors becouse of string based Sql generation
                    if (canOptimizeRight)
                    {
                        if ((bool)bin.Right.Evaluate())
                        {
                            return(Expression.Not(bin.Left));       // (X != TRUE) == not X
                        }
                        else
                        {
                            return(bin.Left);                       // (X != FALSE) == X
                        }
                    }
                    break;
                }
            }
            return(expression);
        }
コード例 #50
0
 protected abstract void ConvertToSqlParameterModel(ModelDetail modelDetail, ref CharWriteBuffer sb, BuilderContext context, bool parameterInContext);
コード例 #51
0
 public virtual void UnregisterParameter(InputParameterExpression expression, BuilderContext builderContext)
 {
     builderContext.ExpressionQuery.Parameters.Remove(expression);
 }
コード例 #52
0
        /// <summary>
        /// Registers an association
        /// </summary>
        /// <param name="tableExpression">The table holding the member, to become the joinedTable</param>
        /// <param name="tableMemberInfo"></param>
        /// <param name="otherType"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual TableExpression RegisterAssociation(TableExpression tableExpression, MemberInfo tableMemberInfo,
                                                           Type otherType, BuilderContext builderContext)
        {
            IList <MemberInfo> otherKeys;
            TableJoinType      joinType;
            string             joinID;
            var theseKeys = DataMapper.GetAssociation(tableExpression, tableMemberInfo, otherType, out otherKeys,
                                                      out joinType, out joinID, builderContext.QueryContext.DataContext);

            // if the memberInfo has no corresponding association, we get a null, that we propagate
            if (theseKeys == null)
            {
                return(null);
            }

            // the current table has the foreign key, the other table the referenced (usually primary) key
            if (theseKeys.Count != otherKeys.Count)
            {
                throw Error.BadArgument("S0128: Association arguments (FK and ref'd PK) don't match");
            }

            // we first create the table, with the JoinID, and we MUST complete the table later, with the Join() method
            var otherTableExpression = new TableExpression(otherType, DataMapper.GetTableName(otherType, builderContext.QueryContext.DataContext), joinID);

            Expression joinExpression = null;

            var createdColumns = new List <ColumnExpression>();

            for (int keyIndex = 0; keyIndex < theseKeys.Count; keyIndex++)
            {
                // joinedKey is registered, even if unused by final select (required columns will be filtered anyway)
                Expression otherKey = RegisterColumn(otherTableExpression, otherKeys[keyIndex], builderContext);
                // foreign is created, we will store it later if this assocation is registered too
                Expression thisKey = CreateColumn(tableExpression, theseKeys[keyIndex], builderContext);
                createdColumns.Add((ColumnExpression)thisKey);

                // if the key is nullable, then convert it
                // TODO: this will probably need to be changed
                if (otherKey.Type.IsNullable())
                {
                    otherKey = Expression.Convert(otherKey, otherKey.Type.GetNullableType());
                }
                if (thisKey.Type.IsNullable())
                {
                    thisKey = Expression.Convert(thisKey, thisKey.Type.GetNullableType());
                }
                // the other key is set as left operand, this must be this way
                // since some vendors (SQL Server) don't support the opposite
                var referenceExpression = Expression.Equal(otherKey, thisKey);

                // if we already have a join expression, then we have a double condition here, so "AND" it
                if (joinExpression != null)
                {
                    joinExpression = Expression.And(joinExpression, referenceExpression);
                }
                else
                {
                    joinExpression = referenceExpression;
                }
            }
            // we complete the table here, now that we have all join information
            otherTableExpression.Join(joinType, tableExpression, joinExpression);

            // our table is created, with the expressions
            // now check if we didn't register exactly the same
            var existingTable = (from t in builderContext.EnumerateScopeTables() where t.IsEqualTo(otherTableExpression) select t).SingleOrDefault();

            if (existingTable != null)
            {
                return(existingTable);
            }

            builderContext.CurrentSelect.Tables.Add(otherTableExpression);
            foreach (var createdColumn in createdColumns)
            {
                builderContext.CurrentSelect.Columns.Add(createdColumn);
            }
            return(otherTableExpression);
        }
コード例 #53
0
		public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
		{
			return obj.Expression;
		}
コード例 #54
0
 /// <summary>
 /// Registers a where clause in the current context scope
 /// </summary>
 /// <param name="whereExpression"></param>
 /// <param name="builderContext"></param>
 public virtual void RegisterWhere(Expression whereExpression, BuilderContext builderContext)
 {
     builderContext.CurrentSelect.Where.Add(whereExpression);
 }
コード例 #55
0
		public override SLE.Expression MakeExpression (BuilderContext ctx)
		{
#if STATIC
			return base.MakeExpression (ctx);
#else
			return SLE.Expression.Block (expr.MakeExpression (ctx), SLE.Expression.Default (type.GetMetaInfo ()));
#endif
		}
コード例 #56
0
 /// <summary>
 /// Registers all columns of a table.
 /// </summary>
 /// <param name="tableExpression"></param>
 /// <param name="builderContext"></param>
 /// <returns></returns>
 public virtual IEnumerable <ColumnExpression> RegisterAllColumns(TableExpression tableExpression, BuilderContext builderContext)
 {
     foreach (var metaMember in builderContext.QueryContext.DataContext.Mapping.GetTable(tableExpression.Type).RowType.PersistentDataMembers)
     {
         yield return(RegisterColumn(tableExpression, metaMember.Member, builderContext));
     }
 }
コード例 #57
0
ファイル: nullable.cs プロジェクト: Paccc/SharpDevelop
		public override SLE.Expression MakeExpression (BuilderContext ctx)
		{
			return Binary.MakeExpression (ctx, Left, Right);
		}
コード例 #58
0
        /// <summary>
        /// Builds a Row builder, based on a given list of parameters
        /// </summary>
        /// <param name="tableType"></param>
        /// <param name="parameters"></param>
        /// <param name="builderContext"></param>
        /// <returns></returns>
        public virtual LambdaExpression BuildTableReader(Type tableType, IList <string> parameters, BuilderContext builderContext)
        {
            var dataRecordParameter     = Expression.Parameter(typeof(IDataRecord), "dataRecord");
            var mappingContextParameter = Expression.Parameter(typeof(MappingContext), "mappingContext");
            //var table = builderContext.QueryContext.DataContext.Mapping.GetTable(tableType);
            var bindings = new List <MemberBinding>();

            for (int parameterIndex = 0; parameterIndex < parameters.Count; parameterIndex++)
            {
                var parameter  = parameters[parameterIndex];
                var memberInfo = tableType.GetTableColumnMember(parameter);
                if (memberInfo == null)
                {
                    memberInfo = tableType.GetSingleMember(parameter, BindingFlags.Public | BindingFlags.NonPublic
                                                           | BindingFlags.Instance | BindingFlags.IgnoreCase);
                }
#if !MONO_STRICT
                if (memberInfo == null && parameter.Contains('_'))
                {
                    memberInfo = tableType.GetSingleMember(parameter.Replace("_", ""), BindingFlags.Public | BindingFlags.NonPublic
                                                           | BindingFlags.Instance | BindingFlags.IgnoreCase);
                }
#endif
                // TODO real error
                if (memberInfo == null)
                {
                    throw new ArgumentException(string.Format("Invalid column '{0}'", parameter));
                }
                //var column = DataMapper.GetColumnName(tableType, memberInfo, builderContext.QueryContext.DataContext);
                //var columnName = DataMapper.GetColumnName(tableType, memberInfo, builderContext.QueryContext.DataContext);
                var invoke = GetOutputValueReader(memberInfo.GetMemberType(), parameterIndex, //GetTableIndex(parameters, columnName),
                                                  dataRecordParameter, mappingContextParameter);
                var parameterColumn = GetOutputValueReader(invoke, dataRecordParameter, mappingContextParameter,
                                                           builderContext);
                var binding = Expression.Bind(memberInfo, parameterColumn);
                bindings.Add(binding);
            }
            var newExpression  = Expression.New(tableType);
            var initExpression = Expression.MemberInit(newExpression, bindings);
            return(Expression.Lambda(initExpression, dataRecordParameter, mappingContextParameter));
        }
コード例 #59
0
ファイル: nullable.cs プロジェクト: saga/mono
		public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
		{
			return expr.MakeExpression (ctx);
		}
コード例 #60
0
        /// <summary>
        /// Returns an existing table or registers the current one
        /// </summary>
        /// <param name="tableExpression"></param>
        /// <param name="builderContext"></param>
        /// <returns>A registered table or the current newly registered one</returns>
        public virtual TableExpression RegisterTable(TableExpression tableExpression, BuilderContext builderContext)
        {
            // 1. Find the table in current scope
            var foundTableExpression = (from t in builderContext.EnumerateScopeTables()
                                        where t.IsEqualTo(tableExpression)
                                        select t).SingleOrDefault();

            if (foundTableExpression != null)
            {
                return(foundTableExpression);
            }
            // 2. Find it in all scopes, and promote it to current scope.
            foundTableExpression = PromoteTable(tableExpression, builderContext);
            if (foundTableExpression != null)
            {
                return(foundTableExpression);
            }
            // 3. Add it
            builderContext.CurrentSelect.Tables.Add(tableExpression);
            return(tableExpression);
        }