Esempio n. 1
0
 internal void AddRange(Join[] val)
 {
     for (int i = 0; i < val.Length; i++)
     {
         this.Add(val[i]);
     }
 }
Esempio n. 2
0
    Bot(StreamReader reader, StreamWriter writer, Join join)
    {
        this.writer = writer;
        string line;

        send(join);

        while((line = reader.ReadLine()) != null) {
            MsgWrapper msg = JsonConvert.DeserializeObject<MsgWrapper>(line);
            switch(msg.msgType) {
                case "carPositions":
                    send(new Throttle(0.5));
                    break;
                case "join":
                    Console.WriteLine("Joined");
                    send(new Ping());
                    break;
                case "gameInit":
                    Console.WriteLine("Race init");
                    send(new Ping());
                    break;
                case "gameEnd":
                    Console.WriteLine("Race ended");
                    send(new Ping());
                    break;
                case "gameStart":
                    Console.WriteLine("Race starts");
                    send(new Ping());
                    break;
                default:
                    send(new Ping());
                    break;
            }
        }
    }
Esempio n. 3
0
		public void InitializeConnect()
		{
			OutputWindow.Clear();

			// Assign events
			eventReceiving += new IRCReceived(IrcCommandReceived);
			eventServerMessage += new ServerMessage(IrcServerMessage);
			eventIrcMessageReceived += new MessageReceived(IrcMessageReceived);
			eventIrcNoticeReceived += new NoticeReceived(IrcNoticeReceived);
			eventSendReceivedCommand += new SendReceivedCommand(IrcSendReceivedCommand);
			eventSendModMessage += new SendModMessage(IrcSendModMessage);
			eventJoin += new Join(IrcJoin);
			eventPart += new Part(IrcPart);
			eventMode += new Mode(IrcMode);

			//Try to set the LogFile 
			try
			{
				logOutput = new StreamWriter(logFileName, true);
			}
			catch (Exception e)
			{
				log = false;

				if (ToggleDebugCheckBox.Checked)
					IrcCommandReceived(e.Message);
			}

			// Connect to server	
			Connect();
		}
Esempio n. 4
0
 public Text_Elemente_ermitteln(IMin_und_Max_ermitteln Min_und_Max_ermitteln, ISkalierung_berechnen Skalierung_berechnen, Join<IEnumerable<Tag>,Tuple<int,double>> join, IText_Elemente_bilden Text_Elemente_bilden) {
   this._Process += Min_und_Max_ermitteln.Process;
   this._Process += join.Input1;
   Min_und_Max_ermitteln.Result += Skalierung_berechnen.Process;
   Skalierung_berechnen.Result += join.Input2;
   join.Output += Text_Elemente_bilden.Process;
   Text_Elemente_bilden.Result += m => this.Result(m);
 }
Esempio n. 5
0
 public Query Join(JoinType joinType,
     TableSchema leftTableSchema, string leftColumn, string leftTableAlias,
     object rightTableSql, string rightColumn, string rightTableAlias)
 {
     if (_ListJoin == null) _ListJoin = new JoinList();
     Join join = new Join(joinType, leftTableSchema, leftColumn, leftTableAlias, rightTableSql, rightColumn, rightTableAlias);
     _ListJoin.Add(join);
     return this;
 }
Esempio n. 6
0
 public Query Join(JoinType joinType,
     object rightTableSql, string rightTableAlias,
     params JoinColumnPair[] pairs)
 {
     if (_ListJoin == null) _ListJoin = new JoinList();
     Join join = new Join(joinType, rightTableSql, rightTableAlias, pairs);
     _ListJoin.Add(join);
     return this;
 }
Esempio n. 7
0
 public Query Join(JoinType joinType,
     TableSchema rightTableSchema, string rightTableAlias,
     params JoinColumnPair[] pairs)
 {
     if (_ListJoin == null) _ListJoin = new JoinList();
     Join join = new Join(joinType, rightTableSchema, rightTableAlias, pairs);
     _ListJoin.Add(join);
     TableAliasMap[join.RightTableAlias] = join.RightTableSchema;
     return this;
 }
Esempio n. 8
0
        public CreateOrJoin(Create a, Join n)
        {
            cfunk = a;
            jfunk = n;
            ipAddress.Text = loadFromRegistry("ipAdress");
            port.Text = loadFromRegistry("port");
            ssName.Text = loadFromRegistry("ssName");
            passWord.Text = loadFromRegistry("passWord");

            InitializeComponent();
        }
Esempio n. 9
0
 public BowlingBoard(IBuild_frames_from_rolls Build_frames_from_rolls, ISum_rolls Sum_rolls, ISum_strikes Sum_strikes, ISum_spares Sum_spares, Join<IEnumerable<int>,IEnumerable<int>,IEnumerable<int>,Tuple<IEnumerable<int>,IEnumerable<int>,IEnumerable<int>>> join, ISum Sum) {
   this._Process += Build_frames_from_rolls.Process;
   Build_frames_from_rolls.Result += Sum_rolls.Process;
   Build_frames_from_rolls.Result += Sum_strikes.Process;
   Build_frames_from_rolls.Result += Sum_spares.Process;
   Sum_rolls.Result += join.Input1;
   Sum_strikes.Result += join.Input2;
   Sum_spares.Result += join.Input3;
   join.Output += Sum.Process;
   Sum.Result += m => this.Result(m);
 }
Esempio n. 10
0
 public ActiveObject()
 {
     join = Join.Create();
       join.Initialize(out ProcessMessage);
       join.Initialize(out Start);
       join.When(Start).Do(delegate
       {
     Thread.CurrentThread.IsBackground = true;
     while (!done) ProcessMessage();
       });
       Start();
 }
Esempio n. 11
0
		public static void Main (string[] args)
		{

			//CheesecakeFactory.DoMain();

			var tj =new TestJoin<Person,City>();
			var tjsm = tj.Select3((person, city) => new { Name="Ciudad", Id=1 });
			Console.WriteLine(tjsm);

			var mj = new MoreTestJoin22<Person,City>();
			var tmj = mj.Select4((person, city) => new { Name="Ciudad", Id=1 });
			Console.WriteLine(tmj);


			//var nj = new NewJoin<Person,City>();
			//var tnj = nj.Select3((person, city) => new { Name="Ciudad", Id=1 });
			//Console.WriteLine(tnj);

			//var tj2 =new TestJoin22<Person,City>();
			//var tjsm2 = tj2.Select4((person, city) => new { Name="Ciudad", Id=1 });
			//Console.WriteLine(tjsm2);


			OrmLiteConfig.DialectProvider= MySqlDialectProvider.Instance;

			//var connectionString= "Server = 127.0.0.1; Database = ormlite; Uid = root; Pwd = password";

			//var personVisitor = new MySqlExpressionVisitor<Person>();
			//var cityVisitor = new MySqlExpressionVisitor<City>();

			//var join = new Join<Person,City>(personVisitor,
			//                                 cityVisitor,
			//                                 (f,j)=>f.JobCityId==j.Id );

			var join =new Join<Person,City>(new Person(), new City(),
			                                (f,j)=>f.JobCityId==j.Id );

			Console.WriteLine(join);

			//join.SelectFieds((f,j)=>f.Name);
			//var s = join.SelectFieds((f,j)=>new {f.Name, f.BirthCityId});
			//Console.WriteLine(s);
			//var sm = join.Select3((person, city) => new { Name="Ciudad", Id=1 });
			//Console.WriteLine(sm);


			//using (IDbConnection db =  connectionString.OpenDbConnection())
            //using ( IDbCommand dbCmd = db.CreateCommand())
            //{
			//}
		}
        protected override void OnStoryboardCompleted()
        {
            var list = new List<Animation>(Animations);
            var join = new Join<Animation>(list.Count, a => OnAnimationCompleted());

            for (int i = 0; i < list.Count; i++)
			{
                int x = i;
                list[x].AnimationCompleted += a =>
                    {
                        int z = x;
                        join.Call[z](list[z]);
                    };
			}
        }
Esempio n. 13
0
        public Calculate(Action<Action<double?>> ejectNumber,
            Action<Tuple<char, double?>, Action<double>> applyOperation)
        {
            var opToSignal = new DropData<char>();
            var joinOpAndNumber = new Join<char, double?>();

            this.In_Process = (c) =>
                {
                    opToSignal.In_Drop(c);
                    joinOpAndNumber.Input0(c);
                };

            opToSignal.Out_Signal += () => ejectNumber(joinOpAndNumber.Input1);
            joinOpAndNumber.Output += _ => applyOperation(_, this.Out_Result);
        }
Esempio n. 14
0
 /// <summary>
 /// 连接表(带关系)
 /// </summary>
 /// <param name="ModelA">实体类A</param>
 /// <param name="JoinPropertyNameA">关联字段名A(不用加表名)</param>
 /// <param name="ModelB">实体类B</param>
 /// <param name="JoinPropertyNameB">关联字段名B(不用加表名)</param>
 /// <param name="JoinParam">A与B实体连接方式</param>
 public JoinModel(object ModelA, string JoinPropertyNameA, object ModelB, string JoinPropertyNameB, Join JoinParam)
 {
     this.ModelA = ModelA;
     this.ModelB = ModelB;
     this.DBTableNameA = "T_" + ModelA.GetType().Name.Remove(ModelA.GetType().Name.Length - 4);
     this.DBTableNameB = "T_" + ModelB.GetType().Name.Remove(ModelB.GetType().Name.Length - 4);
     if (JoinPropertyNameA.IndexOf(DBTableNameA + ".") == -1 && JoinPropertyNameA.IndexOf("SUBSTRING") == -1)
         this.JoinPropertyNameA = DBTableNameA + "." + JoinPropertyNameA + "";
     else
         this.JoinPropertyNameA = JoinPropertyNameA + "";
     if (JoinPropertyNameB.IndexOf(DBTableNameB + ".") == -1 && JoinPropertyNameB.IndexOf("SUBSTRING") == -1)
         this.JoinPropertyNameB = DBTableNameB + "." + JoinPropertyNameB + "";
     else
         this.JoinPropertyNameB = JoinPropertyNameB + "";
     this.JoinParam = (string)JoinParam.ToString();
 }
Esempio n. 15
0
        public EqualidatorFlow(bool treatAllIEnumerablesAlike)
        {
            // Build
            var flattenA = new Flatten(treatAllIEnumerablesAlike);
            var flattenB = new Flatten(treatAllIEnumerablesAlike);
            var join = new Join<IEnumerable<object>, IEnumerable<object>>();
            var check = new Check_equality();

            // Bind
            _process += t => flattenA.Process(t.Item1);
            _process += t => flattenB.Process(t.Item2);

            flattenA.Result += join.Input1;
            flattenB.Result += join.Input2;

            join.Output += check.Process;
        }
Esempio n. 16
0
        public void InitializeConnect()
        {
            OutputWindow.Clear();

            // Assign events
            eventReceiving += new IRCReceived(IrcCommandReceived);
            eventServerMessage += new ServerMessage(IrcServerMessage);
            eventIrcMessageReceived += new MessageReceived(IrcMessageReceived);
            eventIrcNoticeReceived += new NoticeReceived(IrcNoticeReceived);
            eventSendReceivedCommand += new SendReceivedCommand(IrcSendReceivedCommand);
            eventSendModMessage += new SendModMessage(IrcSendModMessage);
            eventJoin += new Join(IrcJoin);
            eventPart += new Part(IrcPart);
            eventMode += new Mode(IrcMode);

            // Connect to server
            Connect();
        }
Esempio n. 17
0
        public virtual IEntityReader <IdType, EntityType> WithJoin
            (string joinTable
            , string joinAlias
            , string[] joinColumnNames
            , JoinQueryElement[] joinQueries
            , Func <object, dynamic, object> loadVisitor)
        {
            var join = new Join()
            {
                JoinColumnNames   = joinColumnNames,
                SplitOnColumnName = "SplitOnColumn",
                JoinTable         = joinTable,
                JoinAlias         = joinAlias,
                JoinOnQueries     = joinQueries,
                Load = loadVisitor
            };

            return(WithJoin(join));
        }
Esempio n. 18
0
        protected virtual string JoinToString(Join join)
        {
            switch (join)
            {
            case Join.Cross: return("CROSS");

            case Join.Inner: return("INNER");

            case Join.Left: return("LEFT");

            case Join.Right: return("RIGHT");

            case Join.Outer: return("OUTER");

            case Join.Default: return(string.Empty);
            }

            throw new Exception("Unknown join type: " + join);
        }
        public IActionResult Join(int MovieId)
        {
            Console.WriteLine(MovieId);
            int?UserId = HttpContext.Session.GetInt32("UserId");

            if (UserId == null)
            {
                return(Redirect("/"));
            }
            Join j = new Join()
            {
                UserId  = (int)UserId,
                MovieId = MovieId
            };

            context.Joins.Add(j);
            context.SaveChanges();
            return(Redirect("/success"));
        }
Esempio n. 20
0
        public void JoinSimpleTwoTables()
        {
            JoinList list = new JoinList(global::SqlBuilder.Format.MsSQL);

            Join j1 = new Join(global::SqlBuilder.Format.MsSQL, "users");

            j1.Append("id_user", "id").Append("id_admin", "id");
            list.Append(j1);

            Join j2 = new Join(global::SqlBuilder.Format.MsSQL, "profiles", "p", Enums.JoinType.LEFT);

            j2.Append("id_profile", "id");
            list.Append(j2);

            string result = list.GetSql("t");
            string sql    = "INNER JOIN [users] ON [t].[id_user]=[users].[id] AND [t].[id_admin]=[users].[id] LEFT JOIN [profiles] as [p] ON [t].[id_profile]=[p].[id]";

            Assert.AreEqual(result, sql);
        }
Esempio n. 21
0
        // Ex4
        static T JoinList <T>(List <T> list, Join <T> join)
        {
            T    result  = default(T);
            bool isFirst = true;

            foreach (T item in list)
            {
                if (isFirst)
                {
                    result = item;
                }
                else
                {
                    result = join(result, item);
                }
                isFirst = false;
            }
            return(result);
        }
Esempio n. 22
0
        public IActionResult UnJoin(int ActId)
        {
            int?UserId = HttpContext.Session.GetInt32("UserId");

            if (UserId == null)
            {
                return(RedirectToAction("Index"));
            }

            TempData["UserId"] = HttpContext.Session.GetInt32("UserId");
            Join RemoveJoin = _context.Joins.SingleOrDefault(a => a.UserId == (int)HttpContext.Session.GetInt32("UserId") && a.ActId == ActId);

            if (RemoveJoin != null)
            {
                _context.Joins.Remove(RemoveJoin);
                _context.SaveChanges();
            }
            return(RedirectToAction("Dashboard"));
        }
Esempio n. 23
0
        /// <summary>
        /// Joins the specified join.
        /// </summary>
        /// <param name="join">The join.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">join</exception>
        /// <exception cref="InvalidOperationException">Another join with different expression is already in the query.</exception>
        public SqlQuery Join(Join join)
        {
            if (join == null)
            {
                throw new ArgumentNullException("join");
            }

            var sb = new StringBuilder();

            JoinToString(join, sb, modifySelf: false);
            string expression = sb.ToString();

            if (!string.IsNullOrEmpty(join.Name) &&
                aliasExpressions != null && aliasExpressions.TryGetValue(join.Name, out string existingExpression))
            {
                if (expression == existingExpression)
                {
                    return(this);
                }

                throw new InvalidOperationException(string.Format("Query already has a join '{0}' with expression '{1}'. " +
                                                                  "Attempted join expression is '{2}'", join.Name, existingExpression, expression));
            }

            if (from.Length > 0)
            {
                from.Append(" \n");
            }

            JoinToString(join, from, modifySelf: true);

            if (!string.IsNullOrEmpty(join.Name))
            {
                AliasExpressions[join.Name] = expression;

                if (join as IHaveJoins != null)
                {
                    AliasWithJoins[join.Name] = join as IHaveJoins;
                }
            }

            return(this);
        }
Esempio n. 24
0
        private void LayoutNextScreen(ScreenDrawingSurface surface, Point location, Join join, bool one)
        {
            int offsetX = location.X;
            int offsetY = location.Y;
            int mag     = one ? 1 : -1;

            if (join.type == JoinType.Horizontal)
            {
                offsetX += (join.offsetOne - join.offsetTwo) * stage.Tileset.TileSize * mag;
                offsetY += surfaces[join.screenOne].Screen.PixelHeight * mag;
            }
            else
            {
                offsetX += surfaces[join.screenOne].Screen.PixelWidth * mag;
                offsetY += (join.offsetOne - join.offsetTwo) * stage.Tileset.TileSize * mag;
            }

            LayoutFromScreen(surface, new Point(offsetX, offsetY));
        }
 public IActionResult GenerateActivity(ActivityEvent newEvent)
 {
     if (ModelState.IsValid)
     {
         Join newJoin = new Join();
         newEvent.UserID = (int)HttpContext.Session.GetInt32("UserId");
         context.ActivityList.Add(newEvent);
         context.SaveChanges();
         newJoin.ActivityEventId = newEvent.ActivityEventId;
         newJoin.UserId          = newEvent.UserID;
         context.Joiners.Add(newJoin);
         context.SaveChanges();
         return(Redirect($"{newEvent.ActivityEventId}"));
     }
     else
     {
         return(View("Create"));
     }
 }
Esempio n. 26
0
        private static void ProcessJoin(Join join, ExecutionContext executionContext)
        {
            Flow joiningFlow = executionContext.Flow;

            joiningFlow.End     = DateTime.Now;
            joiningFlow.ActorId = null;
            joiningFlow.Node    = join;

            if (joiningFlow.ParentReactivation)
            {
                bool         parentReactivation = false;
                IList <Flow> concurrentFlows    = executionContext.GetOtherActiveConcurrentFlows();
                if (concurrentFlows.Count == 0)
                {
                    parentReactivation = true;
                }
                else
                {
                    var           delegationRepository = ServiceLocator.Current.GetInstance <IRepository <DelegationDef> >();
                    DelegationDef joinDelegation       = delegationRepository.Get(join.JoinDelegationId);
                    if (joinDelegation != null)
                    {
                        var delegationHelper = ServiceLocator.Current.GetInstance <IDelegationHelper>();
                        parentReactivation = delegationHelper.DelegateJoin(joinDelegation, executionContext);
                    }
                }

                if (parentReactivation)
                {
                    foreach (var concurrentFlow in concurrentFlows)
                    {
                        concurrentFlow.ParentReactivation = false;
                    }

                    Flow parentFlow = joiningFlow.Parent;
                    executionContext.Flow = parentFlow;

                    var transitionRepository = ServiceLocator.Current.GetInstance <IRepository <Transition> >();
                    var leavingTransition    = transitionRepository.With(w => w.To).First(f => f.From.Id == join.Id);
                    ProcessTransition(leavingTransition, executionContext);
                }
            }
        }
Esempio n. 27
0
        public Build_index(Compile_words compileWords, Write_index_to_file writeIndexToFile)
        {
            var joinIndexAndFilename = new Join<Index, string>();
            var logStats = new Log<IndexStats>(stats => string.Format("{0} words indexed", stats.WordCount));
            var logFileWords = new Log<Tuple<string, string[]>>(fileWords =>
                                        fileWords != null ? string.Format("{0}, {1} words", fileWords.Item1, fileWords.Item2.Count())
                                                          : "EOD of words to index");

            this.in_Process = _ => logFileWords.In_Process(_);
            logFileWords.Out_Data += compileWords.In_Process;

            compileWords.Out_Statistics += logStats.In_Process;
            logStats.Out_Data += _ => this.Out_Statistics(_);

            compileWords.Out_IndexCompiled += joinIndexAndFilename.Input0;
            this.in_IndexFilename = joinIndexAndFilename.Input1;

            joinIndexAndFilename.Output += writeIndexToFile.In_Process;
        }
Esempio n. 28
0
        /// <summary>
        /// Checks whether there's any join that is part of a collection association
        /// </summary>
        /// <param name="join">Join</param>
        /// <param name="joins">All joins</param>
        /// <param name="alias">Property alias</param>
        /// <param name="propName">Property name</param>
        private void CheckJoin(Join join, Join[] joins, string alias, string propName)
        {
            if (join.ForeignKey.IsArray)
            {
                throw new InvalidSortException(string.Format("You can't sort by a field that is in a collection association: alias {0} property {1}", alias, propName));
            }

            if (!string.IsNullOrEmpty(join.ParentAlias))
            {
                foreach (Join j in joins)
                {
                    if (j.JoinAlias == join.ParentAlias)
                    {
                        CheckJoin(j, joins, alias, propName);
                        break;
                    }
                }
            }
        }
Esempio n. 29
0
    private void CrearIQueryProperty(object obj, PropertyInfo p)
    {
        var provider = new MyQueryProvider(this);



        Join MyAttribute = (Join)Attribute.GetCustomAttributes(p, false).FirstOrDefault(t => t is Join);

        if (MyAttribute == null)
        {
            return;
        }

        PropertyInfo pJoin1 = obj.GetType().GetProperties().FirstOrDefault(t => t.GetCustomAttributes(typeof(Column), true).Length > 0 && ((Column)t.GetCustomAttributes(typeof(Column), true)[0]).Name == MyAttribute.Key);

        if (pJoin1 == null)
        {
            pJoin1 = obj.GetType().GetProperty(MyAttribute.Key);
        }
        object pJoinValue1 = pJoin1.GetValue(obj, null);

        Func <object, bool> g;
        var tipoBase          = p.PropertyType.GetGenericArguments()[0];
        var delegado          = typeof(Func <,>).MakeGenericType(tipoBase, typeof(bool));
        var delegadoExpresion = typeof(Expression <>).MakeGenericType(delegado);
        var param             = Expression.Parameter(tipoBase, "e");
        var predicate         = LambdaExpression.Lambda(delegado, Expression.Equal(Expression.Property(param, MyAttribute.ForeignKey),
                                                                                   Expression.Constant(pJoinValue1)),
                                                        new ParameterExpression[] { param });


        Type _tipo = typeof(MyQueryable <>).MakeGenericType(tipoBase);
        var  query = (IQueryable)Activator.CreateInstance(_tipo, provider, this);

        query = query.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "Where",
                new Type[] { tipoBase },
                query.Expression, Expression.Quote(predicate)));

        p.SetValue(obj, query, null);
    }
Esempio n. 30
0
        private string GetJoinString(ISqlFormatter sqlFormatter, Join join, IDictionary <string, string> aliases)
        {
            if (join.JoinFields.Count == 0)
            {
                string message = string.Format("SQL cannot be created for the source '{0}' because it has a join to '{1}' without join fields",
                                               Name, join.ToSource.Name);
                throw new HabaneroDeveloperException(message, "Please check how you are building your join clause structure.");
            }
            Join.JoinField joinField             = join.JoinFields[0];
            var            toSourceNameWithAlias = sqlFormatter.DelimitTable(join.ToSource.EntityName);

            toSourceNameWithAlias += " " + aliases[join.ToSource.ToString()];
            var fromSourceAlias = sqlFormatter.DelimitTable(join.FromSource.EntityName);

            fromSourceAlias = aliases[join.FromSource.ToString()];
            var toSourceAlias = sqlFormatter.DelimitTable(join.ToSource.EntityName);

            toSourceAlias = aliases[join.ToSource.ToString()];
            string joinString = string.Format("{0} {1} ON {2}.{3} = {4}.{5}",
                                              join.GetJoinClause(),
                                              toSourceNameWithAlias,
                                              fromSourceAlias,
                                              sqlFormatter.DelimitField(joinField.FromField.FieldName),
                                              toSourceAlias,
                                              sqlFormatter.DelimitField(joinField.ToField.FieldName));

            if (join.JoinFields.Count > 1)
            {
                for (int i = 1; i < join.JoinFields.Count; i++)
                {
                    joinField = join.JoinFields[i];
                    var fromSourceAlias1 = sqlFormatter.DelimitTable(join.FromSource.EntityName);
                    fromSourceAlias1 = aliases[join.FromSource.ToString()];
                    var toSourceAlias1 = sqlFormatter.DelimitTable(join.ToSource.EntityName);
                    toSourceAlias1 = aliases[join.ToSource.ToString()];
                    joinString    += string.Format(" AND {0}.{2} = {1}.{3}",
                                                   fromSourceAlias1, toSourceAlias1,
                                                   sqlFormatter.DelimitField(joinField.FromField.FieldName), sqlFormatter.DelimitField(joinField.ToField.FieldName));
                }
            }
            return(joinString);
        }
Esempio n. 31
0
    Bot(StreamReader reader, StreamWriter writer, Join join)
    {
        this.writer = writer;
        string line;

        send(join);

        while ((line = reader.ReadLine()) != null)
        {
            MsgWrapper msg = JsonConvert.DeserializeObject <MsgWrapper>(line);
            switch (msg.msgType)
            {
            case "carPositions":
                send(new Throttle(0.5));
                break;

            case "join":
                Console.WriteLine("Joined");
                send(new Ping());
                break;

            case "gameInit":
                Console.WriteLine("Race init");
                send(new Ping());
                break;

            case "gameEnd":
                Console.WriteLine("Race ended");
                send(new Ping());
                break;

            case "gameStart":
                Console.WriteLine("Race starts");
                send(new Ping());
                break;

            default:
                send(new Ping());
                break;
            }
        }
    }
Esempio n. 32
0
        public void Empty()
        {
            // JOIN ON 'ROW_NUMBER, Y'
            //
            //        Left                 Right       --> Result
            // -------------------  -------------------  -----------
            //  # |  X  | Y          # |  Z  | Y           (empty)
            // -------------------  -------------------  -----------
            //  0 | foo | 42         0 | foo | 99
            //  1 | sna | 99         1 | sna | 2.71828
            //  2 | bar | 3.14159    2 | bar | 42
            // -------------------   3 | bar | 99
            //                      -------------------

            var criteria = new string[] { "ROW_NUMBER", "Y" };

            Assert.IsTrue(
                Join.Execute(LeftItems, RightItems, out ITaskItem[] result, criteria));
            Assert.IsTrue(result != null && result.Length == 0);
        }
Esempio n. 33
0
        /// <summary>
        /// Converts a Join type to its string representation.
        /// </summary>
        /// <param name="join">The join type.</param>
        /// <returns>The string representation.</returns>
        private static string JoinToString(Join join)
        {
            switch (join)
            {
            case Join.Join:
                return("join");

            case Join.InnerJoin:
                return("inner join");

            case Join.LeftJoin:
                return("left join");

            case Join.RightJoin:
                return("right join");

            default:
                throw new NotSupportedException();
            }
        }
Esempio n. 34
0
        public JoinForm(Join join, IEnumerable <ScreenDocument> screens)
        {
            InitializeComponent();
            this.join = join;
            joinType.SelectedIndex = 0;

            foreach (ScreenDocument s in screens)
            {
                screenOne.Items.Add(s.Name);
                screenTwo.Items.Add(s.Name);
            }

            Direction = join.direction;
            JoinWidth = join.Size;
            ScreenOne = join.screenOne;
            ScreenTwo = join.screenTwo;
            OffsetOne = join.offsetOne;
            OffsetTwo = join.offsetTwo;
            Type      = join.type;
        }
Esempio n. 35
0
        public IActionResult Join(int partyId)
        {
            int?UserId = HttpContext.Session.GetInt32("UserId");

            if (UserId == null)
            {
                return(Redirect("/"));
            }

            Join i = new Join()
            {
                UserId  = (int)UserId,
                PartyId = partyId
            };

            context.Joins.Add(i);
            context.SaveChanges();

            return(Redirect("/home"));
        }
Esempio n. 36
0
        public IActionResult Join(Join newJoin, int id, int uid)
        {
            Active newActive = dbContext.activities.Include(a => a.JoinList).ThenInclude(b => b.User).FirstOrDefault(x => x.ActivityId == id);
            User   newUser   = dbContext.users.Include(a => a.Atending).ThenInclude(b => b.Active).FirstOrDefault(us => us.UserId == uid);

            foreach (var joined in newUser.Atending)
            {
                if (joined.Active.ActivityDate.Date == newActive.ActivityDate.Date)
                {
                    ModelState.AddModelError("ActivityDate", "Date Cannot be in the past");
                    return(RedirectToAction("Home", new { id = (int)HttpContext.Session.GetInt32("UserId") }));
                }
            }

            newJoin.ActivityId = (int)id;
            newJoin.UserId     = (int)HttpContext.Session.GetInt32("UserId");
            dbContext.joinTable.Add(newJoin);
            dbContext.SaveChanges();
            return(RedirectToAction("Home"));
        }
Esempio n. 37
0
 public IActionResult Like(int id)
 {
     if (!LoggedIn())
     {
         return(RedirectToAction("Index", "Home"));
     }
     else
     {
         User CurUser = _context.Users.SingleOrDefault(a => a.UserId == (int)HttpContext.Session.GetInt32("UserId"));
         Idea CurIdea = _context.Ideas.SingleOrDefault(a => a.IdeaId == id);
         Join NewJoin = new Join
         {
             UserId = (int)HttpContext.Session.GetInt32("UserId"),
             IdeaId = id
         };
         _context.Joins.Add(NewJoin);
         _context.SaveChanges();
         return(RedirectToAction("Home"));
     }
 }
Esempio n. 38
0
        private void DrawJoinEnd(Join join, bool one)
        {
            if (joinLayer == null)
            {
                return;
            }
            using (Graphics g = Graphics.FromImage(joinLayer))
            {
                int offset = one ? join.offsetOne : join.offsetTwo;
                int start  = offset * Screen.Tileset.TileSize;
                int end    = start + (join.Size * Screen.Tileset.TileSize);
                int edge;
                Pen pen;

                if (one ? join.direction == JoinDirection.BackwardOnly : join.direction == JoinDirection.ForwardOnly)
                {
                    pen = blockPen;
                }
                else
                {
                    pen = passPen;
                }

                if (join.type == JoinType.Horizontal)
                {
                    edge = one ? Screen.PixelHeight - 2 : 2;
                    int curl = one ? edge - 6 : edge + 6;
                    g.DrawLine(pen, start, edge, end, edge);
                    g.DrawLine(pen, start + 1, edge, start + 1, curl);
                    g.DrawLine(pen, end - 1, edge, end - 1, curl);
                }
                else
                {
                    edge = one ? Screen.PixelWidth - 2 : 2;
                    int curl = one ? edge - 6 : edge + 6;
                    g.DrawLine(pen, edge, start, edge, end);
                    g.DrawLine(pen, edge, start, curl, start);
                    g.DrawLine(pen, edge, end, curl, end);
                }
            }
        }
Esempio n. 39
0
        public void Select_With_Join_Condition()
        {
            // Exercise
            CreateViewStatement sut = ParserFactory.Execute <CreateViewStatement>(@"

                CREATE VIEW SomeView
                AS 
                    SELECT FieldA
                    FROM Table1 T1 
                    JOIN Table2 T2 
                      ON T1.Field1 = T2.Field2"
                                                                                  ).First();
            SelectStatement statement = sut.SelectBlock;

            // Verify outcome
            Assert.IsNotNull(statement);
            Assert.AreEqual("SomeView", sut.Name);

            // Test From
            Assert.AreEqual(1, statement.From.Count);
            Assert.AreEqual("Table1", statement.From[0].Name);
            Assert.AreEqual("T1", statement.From[0].Alias.Name);

            // Test Join
            Assert.AreEqual(1, statement.From[0].Joins.Count);

            Join join = statement.From[0].Joins[0];

            Assert.AreEqual("Table2", join.Name);
            Assert.AreEqual("T2", join.Alias.Name);

            CriteriaExpression expr = join.Condition as CriteriaExpression;

            Assert.AreEqual(JoinType.Join, join.Type);
            Assert.AreEqual("=", expr.Operator);
            Assert.AreEqual("T1.Field1", expr.Left.Value);

            Assert.AreEqual("T2.Field2", expr.Right.Value);

            Assert.AreEqual("T1.Field1 = T2.Field2", expr.Value);
        }
Esempio n. 40
0
        /// <summary>
        ///     Builds a SELECT query with a JOIN clause.
        /// </summary>
        /// <param name="table">The main table.</param>
        /// <param name="joinedTable">The joined table.</param>
        /// <param name="tableColumn">The main table column to join.</param>
        /// <param name="joinedTableColumn">The joined table column to join.</param>
        /// <param name="join">The JOIN type.</param>
        /// <returns>The SELECT query.</returns>
        public string SelectFrom(string table, string joinedTable, string tableColumn, string joinedTableColumn,
                                 Join join)
        {
            var sb = new StringBuilder(100);

            sb.Append("select * from ");

            sb.Append(builder.ObjectNamePrefix);
            sb.Append(table);
            sb.Append(builder.ObjectNameSuffix);

            sb.Append(" ");
            sb.Append(JoinToString(join));
            sb.Append(" ");

            sb.Append(builder.ObjectNamePrefix);
            sb.Append(joinedTable);
            sb.Append(builder.ObjectNameSuffix);

            sb.Append(" on ");

            sb.Append(builder.ObjectNamePrefix);
            sb.Append(table);
            sb.Append(builder.ObjectNameSuffix);
            sb.Append(".");
            sb.Append(builder.ObjectNamePrefix);
            sb.Append(tableColumn);
            sb.Append(builder.ObjectNameSuffix);

            sb.Append(" = ");

            sb.Append(builder.ObjectNamePrefix);
            sb.Append(joinedTable);
            sb.Append(builder.ObjectNameSuffix);
            sb.Append(".");
            sb.Append(builder.ObjectNamePrefix);
            sb.Append(joinedTableColumn);
            sb.Append(builder.ObjectNameSuffix);

            return(sb.ToString());
        }
Esempio n. 41
0
        void schemaCheck()
        {
            join = new Join()
            {
                xls = schema["join"]["xls"],
                res = schema["join"]["res"]
            };

            checkWrongFields(xlsTable, join.xls, "xls");
            checkWrongFields(resTable, join.res, "res");

            foreach (object[] pair in schema["replace"])
            {
                checkWrongFields(xlsTable, pair[0].ToString(), "xls");
                checkWrongFields(resTable, pair[1].ToString(), "res");
            }
            if (wrongFields != string.Empty)
            {
                wrongFields = wrongFields.Remove(wrongFields.Length - 2, 2);
            }
        }
        public void TestFromBytesWithLengthAndRequiredMessageLength()
        {
            var buffer = new MemoryStream(1000);
            var node1  = NextNodeWith(1);
            var join   = new Join(node1);

            MessageConverters.MessageToBytes(join, buffer);
            buffer.Flip();
            var messageSize  = buffer.Length;
            var messageBytes = new byte[messageSize];

            Array.Copy(buffer.ToArray(), 0, messageBytes, 0, messageSize);
            var message = new RawMessage(messageBytes);

            message.Header(RawMessageHeader.From(node1.Id.Value, 0, message.Length));

            Assert.Equal(node1.Id.Value, message.Header().NodeId);
            Assert.Equal(message.Length, message.Header().Length);
            Assert.Equal(message.Length, message.RequiredMessageLength);
            Assert.Equal(join, OperationalMessage.MessageFrom(message.AsTextMessage()));
        }
Esempio n. 43
0
        private static void RunJoinAndVerify(Array joinTo, Array joinFrom, Array expected)
        {
            Type t = joinTo.GetType().GetElementType();

            // Build a table with padded nulls to join from (so we see nulls are also filtered out)
            XArray  joinFromxarray = TableTestHarness.Nulls(XArray.All(joinFrom));
            IXTable joinFromTable  = TableTestHarness.DatabaseContext.FromArrays(joinFromxarray.Count)
                                     .WithColumn(new ColumnDetails("ServerID", t), joinFromxarray);

            // Build the table to join to
            IXTable joinToTable = TableTestHarness.DatabaseContext.FromArrays(joinTo.Length)
                                  .WithColumn(new ColumnDetails("ID", t), XArray.All(joinTo));

            // Run the join - verify the expected values without padding are found
            IXTable       result   = new Join(joinFromTable, "ServerID", joinToTable, "ID", "Server.");
            Func <XArray> serverID = result.Columns.Find("Server.ID").CurrentGetter();

            IXTable expectedTable = TableTestHarness.DatabaseContext.FromArrays(expected.Length).WithColumn("Server.ID", expected);

            TableTestHarness.AssertAreEqual(expectedTable, result, 2);
        }
Esempio n. 44
0
        private static void AddSitemap(IRecordService recordService, string appName, List <AppComponent> appComponents)
        {
            var query = new QueryDefinition(Entities.appmodulecomponent);

            query.RootFilter.AddCondition(Fields.appmodulecomponent_.componenttype, ConditionType.Equal, OptionSets.AppModuleComponent.ObjectTypeCode.Sitemap);
            var siteMapJoin = new Join(Fields.appmodulecomponent_.objectid, Entities.sitemap, Fields.sitemap_.sitemapid);

            siteMapJoin.Fields = new[] { Fields.sitemap_.sitemapxml };
            siteMapJoin.Alias  = "SM";
            query.Joins.Add(siteMapJoin);
            var appJoin = new Join(Fields.appmodulecomponent_.appmoduleidunique, Entities.appmodule, Fields.appmodule_.appmoduleidunique);

            appJoin.RootFilter.Conditions.Add(new Condition(Fields.appmodule_.name, ConditionType.Equal, appName));
            query.Joins.Add(appJoin);
            var siteMaps = recordService.RetreiveAll(query);

            foreach (var siteMap in siteMaps)
            {
                appComponents.Add(new AppComponent("Sitemap", null, siteMapXml: siteMap.GetStringField("SM." + Fields.sitemap_.sitemapxml)));
            }
        }
Esempio n. 45
0
        /// <summary>
        /// Returns a new field an expression with specified join alias. Avoid using.
        /// </summary>
        /// <typeparam name="TField">The type of the field.</typeparam>
        /// <param name="field">The field.</param>
        /// <param name="join">The join.</param>
        /// <param name="origin">The origin.</param>
        /// <param name="extraFlags">The extra flags.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">join</exception>
        public static TField OfJoin <TField>(this TField field, Join join, string origin, FieldFlags extraFlags = FieldFlags.Internal)
            where TField : Field
        {
            if (join == null)
            {
                throw new ArgumentNullException("join");
            }

            field.Expression = join.Name + "." + origin;

            if (field.Flags == FieldFlags.Default)
            {
                field.Flags = FieldFlags.Foreign | extraFlags;
            }
            else
            {
                field.Flags = field.Flags | FieldFlags.Foreign | extraFlags;
            }

            return(field);
        }
Esempio n. 46
0
 public Join GetAsJoin()
 {
     if (RelationshipType == "nn")
     {
         var joinThrough = new Join(RecordService.GetPrimaryKey(SourceType), IntersectEntity, IntersectJoinTo);
         var join        = new Join(IntersectOtherSide, OtherType, RecordService.GetPrimaryKey(OtherType));
         joinThrough.Joins = new List <Join> {
             join
         };
         return(joinThrough);
     }
     if (RelationshipType == "1n")
     {
         return(new Join(RecordService.GetPrimaryKey(SourceType), OtherType, FieldJoinTo));
     }
     if (RelationshipType == "n1")
     {
         return(new Join(FieldJoin, OtherType, RecordService.GetPrimaryKey(OtherType)));
     }
     return(null);
 }
Esempio n. 47
0
 public void Join(Join @join)
 {
     if (@join.JoinType == JoinType.FullOuter)
     {
         Append(" FULL OUTER JOIN ");
     }
     else if (@join.JoinType == JoinType.Inner)
     {
         Append(" INNER JOIN ");
     }
     else if (@join.JoinType == JoinType.Left)
     {
         Append(" LEFT JOIN ");
     }
     else if (@join.JoinType == JoinType.Right)
     {
         Append(" RIGHT JOIN ");
     }
     TableSource(@join.Table);
     Conditions(@join.On, "ON");
 }
Esempio n. 48
0
        private Join parseJoin()
        {
            Join join = new Join();

            switch (fCurrentToken.Value.ToUpperInvariant())
            {
                case "LEFT":
                    join.JoinType = JoinType.Left;
                    break;
                case "RIGHT":
                    join.JoinType = JoinType.Right;
                    break;
                case "INNER":
                    join.JoinType = JoinType.Inner;
                    break;
                case "FULL":
                    join.JoinType = JoinType.Full;
                    break;
                case "CROSS":
                case "JOIN":
                    join.JoinType = JoinType.Cross;
                    break;
                default:
                    join.JoinType = JoinType.Cross;
                    join.TableName = join.Alias = fCurrentToken.Value.TrimQuotation();
                    ReadNextToken();
                    if (fCurrentToken.Equals("AS"))
                    {
                        ReadNextToken();
                        join.Alias = fCurrentToken.Value.TrimQuotation();
                        ReadNextToken();
                    }
                    return join;
            }

            ReadNextToken();
            if (fCurrentToken.Equals("OUTER")) ReadNextToken();
            if (fCurrentToken.Equals("JOIN")) ReadNextToken();
            join.TableName = join.Alias = fCurrentToken.Value.TrimQuotation();
            ReadNextToken();

            if (AtEndOfSource) return join;

            if (fCurrentToken.Equals("(")) // Cinar table options
            {
                ReadNextToken();
                join.CinarTableOptions = parseSetItems();
                SkipExpected(")");
            }

            if (AtEndOfSource) return join;

            if (fCurrentToken.Equals("AS"))
            {
                ReadNextToken();
                join.Alias = fCurrentToken.Value.TrimQuotation();
                ReadNextToken();
            }
            else if (!(fCurrentToken.Equals(",") || fCurrentToken.Equals("ON") || fCurrentToken.Equals("JOIN") || fCurrentToken.Equals("LEFT") || fCurrentToken.Equals("RIGHT") || fCurrentToken.Equals("INNER") || fCurrentToken.Equals("CROSS") || fCurrentToken.Equals("WHERE") || fCurrentToken.Equals("GROUP") || fCurrentToken.Equals("LIMIT") || fCurrentToken.Equals("ORDER")))
            {
                join.Alias = fCurrentToken.Value.TrimQuotation();
                ReadNextToken();
            }

            if (AtEndOfSource) return join;

            if (fCurrentToken.Equals("ON"))
            {
                ReadNextToken();
                join.On = ParseExpression();
            }

            return join;
        }
		/// <summary>
		/// Builds a SELECT query with a JOIN clause.
		/// </summary>
		/// <param name="table">The min table.</param>
		/// <param name="joinedTable">The joined table.</param>
		/// <param name="tableColumn">The main table column to join.</param>
		/// <param name="joinedTableColumn">The joined table column to join.</param>
		/// <param name="join">The JOIN type.</param>
		/// <param name="tableColumns">The main table columns to select.</param>
		/// <param name="joinedTableColumns">The joined table columns to select.</param>
		/// <returns>The SELECT query (returned columns are named like <b>[Table_Column]</b>).</returns>
		public string SelectFrom(string table, string joinedTable, string tableColumn, string joinedTableColumn, Join join,
			string[] tableColumns, string[] joinedTableColumns) {

			return SelectFrom(table, joinedTable, new string[] { tableColumn }, new string[] { joinedTableColumn }, join,
				tableColumns, joinedTableColumns);
		}
Esempio n. 50
0
        public static IList<Join> CreateJoinList(ISchemaProvider db, ObjectClass objClass, IEnumerable<Relation> relations, Relation until)
        {
            if (db == null) throw new ArgumentNullException("db");
            if (objClass == null) throw new ArgumentNullException("objClass");
            if (relations == null) throw new ArgumentNullException("relations");

            List<Join> result = new List<Join>();
            string lastColumName = "ID";
            Join lastJoin = ColumnRef.PrimaryTable;
            ObjectClass lastType = objClass;
            foreach (var rel in relations)
            {
                RelationEnd lastRelEnd;
                RelationEnd nextRelEnd;

                if (rel.A.Type == lastType)
                {
                    lastRelEnd = rel.A;
                    nextRelEnd = rel.B;
                }
                else if (rel.B.Type == lastType)
                {
                    lastRelEnd = rel.B;
                    nextRelEnd = rel.A;
                }
                else
                {
                    throw new JoinListException(string.Format("Unable to create JoinList: Unable to navigate from '{0}' over '{1}' to next type", lastType.Name, rel.ToString()));
                }

                if (rel.GetRelationType() == RelationType.n_m)
                {
                    var viewRel = new Join();
                    result.Add(viewRel);
                    viewRel.JoinTableName = db.GetTableName(rel.Module.SchemaName, rel.GetRelationTableName());
                    viewRel.JoinColumnName = new[] { new ColumnRef(Construct.ForeignKeyColumnName(lastRelEnd), ColumnRef.Local) };
                    viewRel.FKColumnName = new[] { new ColumnRef(lastColumName, lastJoin) };
                    lastJoin = viewRel;

                    viewRel = new Join();
                    result.Add(viewRel);
                    viewRel.JoinTableName = db.GetTableName(nextRelEnd.Type.Module.SchemaName, nextRelEnd.Type.TableName);
                    viewRel.JoinColumnName = new[] { new ColumnRef("ID", ColumnRef.Local) };
                    viewRel.FKColumnName = new[] { new ColumnRef(Construct.ForeignKeyColumnName(nextRelEnd), lastJoin) };

                    lastColumName = "ID"; // viewRel.FKColumnName.Single().ColumnName;
                    lastJoin = viewRel;
                }
                else
                {
                    var viewRel = new Join();
                    result.Add(viewRel);
                    viewRel.JoinTableName = db.GetTableName(nextRelEnd.Type.Module.SchemaName, nextRelEnd.Type.TableName);
                    string localCol = string.Empty;
                    string fkCol = string.Empty;
                    if (nextRelEnd == rel.A && rel.Storage == StorageType.MergeIntoA)
                    {
                        localCol = Construct.ForeignKeyColumnName(lastRelEnd);
                        fkCol = "ID";
                    }
                    else if (nextRelEnd == rel.A && rel.Storage == StorageType.MergeIntoB)
                    {
                        localCol = "ID";
                        fkCol = Construct.ForeignKeyColumnName(nextRelEnd);
                    }
                    else if (nextRelEnd == rel.B && rel.Storage == StorageType.MergeIntoA)
                    {
                        localCol = "ID";
                        fkCol = Construct.ForeignKeyColumnName(nextRelEnd);
                    }
                    else if (nextRelEnd == rel.B && rel.Storage == StorageType.MergeIntoB)
                    {
                        localCol = Construct.ForeignKeyColumnName(lastRelEnd);
                        fkCol = "ID";
                    }
                    else
                    {
                        throw new NotSupportedException(string.Format("StorageType {0} is not supported", rel.Storage));
                    }
                    viewRel.JoinColumnName = new[] { new ColumnRef(localCol, ColumnRef.Local) };
                    viewRel.FKColumnName = new[] { new ColumnRef(fkCol, lastJoin) };
                    lastColumName = localCol;
                    lastJoin = viewRel;
                }

                lastType = nextRelEnd.Type;
                if (rel == until) return result;
            }
            return result;
        }
 public void Join_CreateImplicit_Reversed()
 {
     Join j = new Join(Category.Schema, Product.Schema, Join.JoinType.Inner);
     Assert.IsTrue(j.FromColumn.ColumnName == "CategoryID" && j.FromColumn.Table.Name == "Categories");
     Assert.IsTrue(j.ToColumn.ColumnName == "CategoryID" && j.ToColumn.Table.Name == "Products");
 }
Esempio n. 52
0
 static object Initialize(Join j, int i)
 {
     switch (i % 8) {
     case 0 : {
        Asynchronous.Channel c;
        j.Initialize(out c);
        return c;
     }
     case 1 : {
        Asynchronous.Channel<string> c;
        j.Initialize(out c);
        return c;
     }
     case 2 : {
        Synchronous<string>.Channel<string> c;
        j.Initialize(out c);
        return c;
     }
     case 3 : {
        Synchronous<string>.Channel c;
        j.Initialize(out c);
        return c;
     }
     case 4 : {
        Synchronous.Channel<string> c;
        j.Initialize(out c);
        return c;
     }
     case 5 : {
        Synchronous.Channel c;
        j.Initialize(out c);
        return c;
     }
     case 6: {
       Asynchronous.Channel[] c;
       j.Initialize(out c, 1);
       return c;
     }
     case 7: {
       Asynchronous.Channel<string>[] c;
       j.Initialize(out c, 1);
       return c;
     }
     default :
       Debug.Assert(false);
       return null;
       }
 }
Esempio n. 53
0
        private Join CreateJoinComponent(IGrouping<Property, KeyValuePair<SourceColumn, SourceColumn>> referenceGroup, Dictionary<SourceColumn, Join> all_joins)
        {
            // Get SrcTbl & check for uniqueness.
            var srcTbl = referenceGroup.Select(r => r.Value.References.SourceTable).Distinct().Single();
            var directRefs = referenceGroup.Where(r => r.Value.References.References == null);

            var result = new Join()
            {
                Type = JoinType.Left,
                JoinTableName = _dst.GetTableName(srcTbl.DestinationObjectClass.Module.SchemaName, srcTbl.DestinationObjectClass.TableName),
                JoinColumnName = directRefs.Select(reference => new ColumnRef(reference.Value.References.DestinationProperty.Single().Name, ColumnRef.Local, reference.Value.References.DestinationProperty.Single().GetDbType())).ToArray(),
                FKColumnName = directRefs.Select(reference => new ColumnRef(reference.Value.Name, ColumnRef.PrimaryTable, (System.Data.DbType)reference.Value.DbType)).ToArray(),
                CompareNullsAsEqual = directRefs.Select(reference => reference.Key.CompareNulls).ToArray()
            };
            directRefs.ForEach(dr => all_joins[dr.Key] = result);
            return result;
        }
Esempio n. 54
0
        private void TableBaseComplexMigration(SourceTable tbl, Converter[] converter, List<SourceColumn> mappedColumns, List<SourceColumn> referringCols, Join[] additional_joins)
        {
            if (additional_joins != null
                && additional_joins.Length > 0
                && additional_joins.All(j => referringCols
                    .Select(c => c.DestinationProperty.Single())
                    .OfType<ObjectReferenceProperty>()
                    .Any(orp => j.JoinTableName == _dst.GetTableName(orp.RelationEnd.Parent.GetOtherEnd(orp.RelationEnd).Type.Module.SchemaName, orp.RelationEnd.Parent.GetOtherEnd(orp.RelationEnd).Type.TableName))))
            {
                throw new InvalidOperationException("Unmapped additional joins found");
            }

            // could automatically create needed indices
            var all_joins = new Dictionary<SourceColumn, Join>();
            var root_joins = referringCols
                .GroupBy(k => k.DestinationProperty.Single())
                .SelectMany(referenceGroup => CreateReferenceJoin(referenceGroup, all_joins))
                .ToArray();

            // Add manual joins
            IEnumerable<Join> joins;
            if (additional_joins != null)
            {
                joins = root_joins.Union(additional_joins);
            }
            else
            {
                joins = root_joins;
            }

            var srcColumns = mappedColumns
                                .Where(c => c.References == null)
                                .Union(
                                    referringCols
                                        .GroupBy(k => k.DestinationProperty.Single()) // referring columns cannot be mapped remotely
                                        .Select(g => g.First(p => p.References.References == null))
                                ).ToList();
            var srcColumnNames = srcColumns.Select(c =>
            {
                var orp = c.DestinationProperty.FirstOrDefault() as ObjectReferenceProperty;
                if (c.References != null)
                {
                    return new ProjectionColumn("ID", all_joins[c], System.Data.DbType.Int32, c.DestinationProperty.Single().Name);
                }
                else if (c.References == null
                    && orp != null)
                {
                    if (additional_joins != null
                        && additional_joins.Count(i => i.JoinTableName == _dst.GetTableName(orp.RelationEnd.Parent.GetOtherEnd(orp.RelationEnd).Type.Module.SchemaName, orp.RelationEnd.Parent.GetOtherEnd(orp.RelationEnd).Type.TableName)) > 0)
                    {
                        return new ProjectionColumn(
                            "ID",
                            additional_joins.Single(j => j.JoinTableName == _dst.GetTableName(orp.RelationEnd.Parent.GetOtherEnd(orp.RelationEnd).Type.Module.SchemaName, orp.RelationEnd.Parent.GetOtherEnd(orp.RelationEnd).Type.TableName)),
                            System.Data.DbType.Int32,
                            orp.Name);
                    }
                    else if (converter.Any(cnv => cnv.Column.Name == c.Name))
                    {
                        return new ProjectionColumn(c.Name, ColumnRef.PrimaryTable, c.DestinationProperty.Single().Name);
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("No join found for {0}", c));
                    }
                }
                else
                {
                    return new ProjectionColumn(c.Name, ColumnRef.PrimaryTable, (System.Data.DbType)c.DbType, null);
                }
            }).ToList();

            var dstColumnNames = GetDestinationColumnNames(tbl, srcColumns);
            long processedRows;

            using (var srcReader = _src.ReadJoin(_src.GetTableName(tbl.StagingDatabase.Schema, tbl.Name), srcColumnNames, joins))
            using (var translator = new Translator(tbl, srcReader, srcColumns, converter))
            {
                _dst.WriteTableData(_dst.GetTableName(tbl.DestinationObjectClass.Module.SchemaName, tbl.DestinationObjectClass.TableName), translator, dstColumnNames);
                processedRows = translator.ProcessedRows;
            }

            // count rows in original table, joins should not add or remove rows
            WriteLog(
                tbl.Name, _src.CountRows(_src.GetTableName(tbl.StagingDatabase.Schema, tbl.Name)),
                tbl.DestinationObjectClass.TableName, processedRows);
        }
Esempio n. 55
0
        public void TableBaseMigration(SourceTable tbl, Converter[] converter, Join[] additional_joins)
        {
            // ------------------- Argument checks -------------------
            if (tbl == null)
                throw new ArgumentNullException("tbl");
            if (tbl.DestinationObjectClass == null)
            {
                Log.InfoFormat("Skipping base migration of unmapped table [{0}]", tbl.Name);
                return;
            }

            using (Log.InfoTraceMethodCallFormat("TableBaseMigration", "{0} to {1}", tbl.Name, tbl.DestinationObjectClass.Name))
            {
                // ------------------- Build columns -------------------
                var mappedColumns = tbl.SourceColumn
                    .Where(c => c.DestinationProperty.Count > 0)
                    .OrderBy(c => c.Name)
                    .ToList();
                // Ref Cols
                var referringCols = mappedColumns.Where(c => c.References != null).ToList();

                // ------------------- Migrate -------------------
                if (referringCols.Count == 0 && (additional_joins == null || additional_joins.Length == 0))
                {
                    TableBaseSimpleMigration(tbl, converter, mappedColumns);
                }
                else
                {
                    TableBaseComplexMigration(tbl, converter, mappedColumns, referringCols, additional_joins);
                }
            }
        }
Esempio n. 56
0
		private void WriteSqlQuery(TextWriter w, Expression expr)
		{
			switch( expr.NodeType )
			{
				case NodeType.Property:
				{
					Property property = (Property)expr;
					
					EntityMap map = _maps[property.OwnerClass];
					FieldMap field = map.GetFieldMap(property.Name);
					if( field == null )
					{
						throw new Exception("Property '" + property.Name + "' could not be found for entity type '" + property.OwnerClass + "'.");
					}

					string alias;
					if( !field.IsLookup )
					{
						alias = GetAlias(property);
					}
					else // lookup field
					{
						LookupMap lookup = (LookupMap)field;
						alias = (string)_lookupFieldToAliasMap[lookup.FieldAlias];
					}
					if( alias == null )
					{
						throw new Exception("Could not find table alias for property '" + property.Name + "' in entity '" + property.OwnerClass + "'.");
					}

					WriteSqlColumn(w, alias, field.Field);
					return;
				}
				case NodeType.Parameter:
				{
					Query.Parameter node = (Query.Parameter)expr;

					string name;
					if( !_provider.NoNamedParameters )
					{
						name = _provider.ParameterPrefix + "P" + node.Ordinal;
					}
					else
					{
						name = "?";
					}

					_parameterTable.Add( new OPathParameter(name, node.ValueType) );
	
					w.Write(name);
					return;
				}
				case NodeType.Literal:
				{
					Literal node = (Literal)expr;
					WriteLiteral(w, node.Value);
					return;
				}
				case NodeType.Binary:
				{
					Binary node = (Binary)expr;

					bool isFormat;
					string keyword = GetSqlKeyword(node.Operator, out isFormat);

					if( isFormat )
					{
						WriteFormat(w, keyword, node.Left, node.Right);
					}
					else
					{
						w.Write('(');
						WriteSqlQuery(w, node.Left);
						w.Write(' ');
						w.Write(keyword);
						w.Write(' ');
						WriteSqlQuery(w, node.Right);
						w.Write(')');
					}
					return;
				}
				case NodeType.Unary:
				{
					Unary node = (Unary)expr;

					if( node.Operator == UnaryOperator.Exists )
					{
						w.Write(GetSqlKeyword(node.Operator));
						w.Write("\n(\n");
						WriteSqlQuery(w, node.Operand);
						w.Write("\n)");
					}
					else if( node.Operator == UnaryOperator.IsNull )
					{
						w.Write('(');
						WriteSqlQuery(w, node.Operand);
						w.Write(' ');
						w.Write(GetSqlKeyword(node.Operator));
						w.Write(')');
					}
					else
					{
						w.Write(GetSqlKeyword(node.Operator));
						w.Write('(');
						WriteSqlQuery(w, node.Operand);
						w.Write(')');
					}
					return;
				}
				case NodeType.Filter:
				{
					Filter filter = (Filter)expr;

					// the only supported filters are the root and ones directly below an exists node
					if( filter.Owner != null && (filter.Owner.NodeType != NodeType.Unary || (filter.Owner as Unary).Operator != UnaryOperator.Exists) )
					{
						throw new NotSupportedException("Filter with source type '" + filter.Source.NodeType + "' was not expected.");
					}

					EntityMap entity = _maps[filter.ValueType];
					string entityAlias = GetNextAlias();
					filter.Alias = entityAlias;

					bool whereStarted = false;
					if( filter.Source.NodeType == NodeType.TypeFilter ) // root filter/outer select
					{
						Join[] lookupJoins;
						WriteSelectClause(w, entity, entityAlias, out lookupJoins);

						Join[] joins;
						if( _orderByNode != null )
						{
							Join[] orderByJoins = GetJoinsFromOrderBy(entity, entityAlias, _orderByNode);
							joins = new Join[lookupJoins.Length + orderByJoins.Length];
							lookupJoins.CopyTo(joins, 0);
							orderByJoins.CopyTo(joins, lookupJoins.Length);
						}
						else
						{
							joins = lookupJoins;
						}

						WriteFromClause(w, entity.Table, entityAlias, joins);
						if( entity.BaseEntity != null )
						{
							WriteSubEntityConstraint(w, entityAlias, entity.TypeField, entity.TypeValue, ref whereStarted);
						}
						WriteFilterConstraints(w, filter, whereStarted);
						
						// add the default sort order if the entity has one defined but the query is not ordered
						if( _orderByNode == null && entity.SortOrder != null && entity.SortOrder.Length > 0 )
						{
							w.Write("\nORDER BY ");
							w.Write(entity.SortOrder);
						}
					}
					else if( filter.Source.NodeType == NodeType.Property || filter.Source.NodeType == NodeType.Filter ) // nested filter/subquery
					{
						Expression source = filter.Source;
						while( source.NodeType == NodeType.Filter )
						{
							source = (source as Filter).Source;
						}
						if( source.NodeType != NodeType.Property ) throw new Exception("Could not find source property for filter.");

						Property relProperty = (Property)source;
						if( !relProperty.IsRelational ) throw new Exception("Expected source property for Filter node to be relational.");

						RelationMap relation = relProperty.RelationMap;
						EntityMap sourceEntity = _maps[relProperty.OwnerClass];
						string sourceAlias = GetAlias(relProperty);

						string relationConstraint = ReplaceTableNameWithAlias(relation.Filter, sourceEntity.Table, sourceAlias);
						relationConstraint = ReplaceTableNameWithAlias(relationConstraint, entity.Table, entityAlias);
						
						switch( relation.Relationship )
						{
							case Relationship.Parent:
							{
								w.Write("SELECT *");
								WriteFromClause(w, entity.Table, entityAlias, null);
								if( entity.BaseEntity != null )
								{
									WriteSubEntityConstraint(w, entityAlias, entity.TypeField, entity.TypeValue, ref whereStarted);
								}
								WriteJoinCondition(w, sourceAlias, relation.Fields, entityAlias, GetFieldNames(entity.KeyFields), relationConstraint, true, ref whereStarted);
								WriteFilterConstraints(w, filter, whereStarted);
								break;
							}
							case Relationship.Child:
							{
								w.Write("SELECT *");
								WriteFromClause(w, entity.Table, entityAlias, null);
								if( entity.BaseEntity != null )
								{
									WriteSubEntityConstraint(w, entityAlias, entity.TypeField, entity.TypeValue, ref whereStarted);
								}
								WriteJoinCondition(w, sourceAlias, GetFieldNames(sourceEntity.KeyFields), entityAlias, relation.Fields, relationConstraint, true, ref whereStarted);
								WriteFilterConstraints(w, filter, whereStarted);
								break;
							}
							case Relationship.Many:
							{
								ManyMap junctionMap = (ManyMap)relation;
								string junctionAlias = GetNextAlias();

								relationConstraint = ReplaceTableNameWithAlias(relationConstraint, junctionMap.Table, junctionAlias);								

								// write the junction and child table, inner joined together in one select
								w.Write("SELECT *");
								WriteFromClause(w, junctionMap.Table, junctionAlias, null);
								w.Write(", ");
								WriteSqlTable(w, entity.Table, entityAlias);
								if( entity.BaseEntity != null )
								{
									WriteSubEntityConstraint(w, entityAlias, entity.TypeField, entity.TypeValue, ref whereStarted);
								}
								WriteJoinCondition(w, sourceAlias, GetFieldNames(sourceEntity.KeyFields), junctionAlias, junctionMap.Source, null, true, ref whereStarted);
								WriteJoinCondition(w, junctionAlias, junctionMap.Dest, entityAlias, GetFieldNames(entity.KeyFields), relationConstraint, true, ref whereStarted);
								WriteFilterConstraints(w, filter, whereStarted);

								break;
							}
							default:
							{
								throw new NotSupportedException("Relationship type '" + relation.Relationship + "' is not supported.");
							}
						}
					}
					else
					{
						throw new NotImplementedException("Filter with source type '" + filter.Source.NodeType + "' was not expected.");
					}
					return;
				}
				case NodeType.Function:
				{
					Function node = (Function)expr;

					bool isFormat;
					string keyword = GetSqlKeyword(node.Operator, out isFormat);
					if( isFormat )
					{
						WriteFormat(w, keyword, node.Params);
					}
					else
					{
						if( node.Operator != FunctionOperator.In )
						{
							throw new NotSupportedException("Function operator '" + node.Operator + "' was not expected.");
						}
						w.Write('(');
						WriteSqlQuery(w, node.Params[0]);
						w.Write(' ');
						w.Write(keyword);
						w.Write(" (");
						for( int i = 1; i < node.Params.Length; i++ )
						{
							if( i > 1 ) w.Write(", ");
							WriteSqlQuery(w, node.Params[i]);
						}
						w.Write("))");
					}
					return;
				}
				case NodeType.OrderBy:
				{
					OrderBy node = (OrderBy)expr;
					_orderByNode = node;

					Filter filter = (node.Source as Filter);
					if( filter == null )
					{
						throw new Exception("Expected source of OrderBy node to be Filter.");
					}

					WriteSqlQuery(w, filter);

					w.Write("\nORDER BY ");
					for( int i = 0; i < node.OrderByItems.Count; i++ )
					{
						OrderByItem item = node.OrderByItems[i];

						FieldMap field = item.FieldInfo;
						if( field == null )
						{
							throw new Exception("Field info does not exists for OrderByItem '" + item.Item + "'.");
						}

						string alias = (item.Join == null) ? filter.Alias : item.Join.Alias;

						if( i > 0 )	w.Write(", ");
						WriteSqlColumn(w, alias, field.Field);
						w.Write( (item.Ascending) ? " ASC" : " DESC");
					}
					return;
				}
				case NodeType.Empty:
				{
					return;
				}
				default:
				{
					throw new NotSupportedException("Expression type '" + expr.GetType() + "' is not currently supported.");
				}
			}
		}
Esempio n. 57
0
		private void WriteSelectClause(TextWriter w, EntityMap entity, string entityAlias, out Join[] lookupJoins)
		{
			w.Write("SELECT ");

			int columnCount = 0;
			ArrayList joins = new ArrayList();
			ArrayList joinMaps = new ArrayList();

			// add all core entity fields and lookup columns
			for( int i = 0; i < entity.Fields.Length; i++ )
			{
				if( columnCount > 0 ) w.Write(", ");

				FieldMap field = entity.Fields[i];
				if( !field.IsLookup )
				{
					WriteSqlColumn(w, entityAlias, field.Field);
				}
				else // lookup column
				{
					LookupMap lookup = (LookupMap)field;

					// see if we already have a join setup for the table associated to this lookup field
					string tableAlias = null;
					for( int j = 0; j < joinMaps.Count; j++ )
					{
						if( CanLookupMapsUseSameJoin((LookupMap)joinMaps[j], lookup) )
						{
							tableAlias = (joins[j] as Join).TableAlias;
							break;
						}
					}

					// create a new join if an existing one was not found above
					if( tableAlias == null )
					{
						tableAlias = GetNextAlias();
						
						StringWriter joinCondition = new StringWriter();
						bool whereStarted = false;
						WriteJoinCondition(joinCondition, entityAlias, lookup.Source, tableAlias, lookup.Dest, null, false, ref whereStarted);

						joins.Add( new Join(lookup.Table, tableAlias, joinCondition.ToString(), 1) );
						joinMaps.Add(lookup);
					}

					WriteSqlColumn(w, tableAlias, lookup.Field, lookup.FieldAlias);

					// add lookup to the map - in case we need the alias later during query generation
					_lookupFieldToAliasMap.Add(lookup.FieldAlias, tableAlias);
				}
				
				columnCount += 1;
			}

			// add any sub fields
			if( entity.SubFields.Keys.Count > 0 )
			{
				foreach( string subField in entity.SubFields.Keys )
				{
					if( columnCount > 0 ) w.Write(", ");
					WriteSqlColumn(w, entityAlias, subField);
					columnCount += 1;
				}
			}

			// add type field if specified
			if( entity.TypeField != null && entity.TypeField.Length > 0 )
			{
				if( columnCount > 0 ) w.Write(", ");
				WriteSqlColumn(w, entityAlias, entity.TypeField);
				columnCount += 1;
			}

			// return our array of joins
			lookupJoins = (Join[])joins.ToArray(typeof(Join));
		}
Esempio n. 58
0
		private void WriteFromClause(TextWriter w, string tableName, string tableAlias, Join[] joins)
		{
			// write a SQL-92 From clause with the specified joins... unless the provider is Access
			if( _provider.Provider != Provider.Access )
			{
				// SQL-92 Example Output:
				// 
				// FROM Node n1
				//   INNER OUTER JOIN Node n2 ON n1.NodeID = n2.ParentNodeID
				//     INNER OUTER JOIN Node n4 ON n2.NodeID = n4.ParentNodeID
				//     INNER OUTER JOIN Node n5 ON n2.NodeID = n5.ParentNodeID
				//   INNER OUTER JOIN Node n3 ON n1.NodeID = n3.ParentNodeID
				//     INNER OUTER JOIN Node n6 ON n3.NodeID = n6.ParentNodeID
				//     INNER OUTER JOIN Node n7 ON n3.NodeID = n7.ParentNodeID

				w.Write("\nFROM ");
				WriteSqlTable(w, tableName, tableAlias);

				if( joins != null )
				{
					for( int i = 0; i < joins.Length; i++ )
					{
						Join join = joins[i];

						w.Write('\n');
						w.Write(new string(' ', join.IndentDepth * 2));
						w.Write("LEFT OUTER JOIN ");
						WriteSqlTable(w, join.TableName, join.TableAlias);
						w.Write(" ON ");
						w.Write(join.JoinCondition);
					}
				}
			}
			else // MS Access
			{
				// MS Access Example Output:
				// 
				// FROM ((((((Node AS n1
				//   INNER JOIN Node AS n2 ON n1.NodeID = n2.ParentNodeID) 
				//     INNER JOIN Node AS n4 ON n2.NodeID = n4.ParentNodeID) 
				//     INNER JOIN Node AS n5 ON n2.NodeID = n5.ParentNodeID) 
				//   INNER JOIN Node AS n3 ON n1.NodeID = n3.ParentNodeID) 
				//     INNER JOIN Node AS n6 ON n3.NodeID = n6.ParentNodeID) 
				//     INNER JOIN Node AS n7 ON n3.NodeID = n7.ParentNodeID)

				w.Write("\nFROM ");

				if( joins != null && joins.Length > 0 )
				{
					w.Write(new string('(', joins.Length));
				}

				WriteSqlTable(w, tableName, tableAlias);

				if( joins != null )
				{
					for( int i = 0; i < joins.Length; i++ )
					{
						Join join = joins[i];

						w.Write('\n');
						w.Write(new string(' ', join.IndentDepth * 2));
						w.Write(" LEFT OUTER JOIN ");
						WriteSqlTable(w, join.TableName, join.TableAlias);
						w.Write(" ON ");
						w.Write(join.JoinCondition);
						w.Write(")");
					}
				}
			}
		}
Esempio n. 59
0
 /// <summary>
 /// Set up an implicit join between two tables.
 /// </summary>
 /// <param name="masterTableName">The name of the 'master' table</param>
 /// <param name="masterKey">The 'primary key'</param>
 /// <param name="masterPropertyName">The name to give the lookup property in the detail objects</param>
 /// <param name="detailTableName">The name of the 'master' table</param>
 /// <param name="detailKey">The 'foreign key'</param>
 /// <param name="detailPropertyName">The name to give the collection property in the master object</param>
 public void ConfigureJoin(string masterTableName, string masterKey, string masterPropertyName, string detailTableName, string detailKey, string detailPropertyName)
 {
     var join = new Join(masterTableName, masterKey, masterPropertyName, detailTableName, detailKey,
                         detailPropertyName);
     _joins.Add(join);
 }
Esempio n. 60
0
 private bool Equals(Join other)
 {
     return _node.Equals(other._node) && !_roles.Except(other._roles).Any();
 }