Inheritance: System.Web.UI.Page
Example #1
0
        public static void Do(Level lvl, Check C, Random rand) {
            ushort x, y, z;
            lvl.IntToPos(C.b, out x, out y, out z);
            
            if (lvl.GetTile(x, (ushort)(y - 1), z) != Block.lavastill)
                return;
            
            if (lvl.GetTile(x, (ushort)(y + 1), z) == Block.air) {
                bool keepGoing = true;
                if ((lvl.Height * 80 / 100) < y)
                    keepGoing = rand.Next(1, 20) > 1;

                if (keepGoing) {
                    int bAbove = lvl.PosToInt(x, (ushort)(y + 1), z);
                    bool unblocked = !lvl.ListUpdate.Exists(u => u.b == bAbove);
                    if (unblocked) {
                        lvl.AddUpdate(bAbove, Block.firework, false);
                        lvl.AddUpdate(C.b, Block.lavastill, false, "wait 1 dissipate 100");
                        C.extraInfo = "wait 1 dissipate 100";
                        return;
                    }
                }
            }
            Firework(x, y, z, 4, lvl, rand);
        }
Example #2
0
        public static void DoGeyser(Level lvl, Check C, Random rand) {
            C.time++;
            ushort x, y, z;
            lvl.IntToPos(C.b, out x, out y, out z);
            byte below = lvl.GetTile(x, (ushort)(y - 1), z);
            
            if (below == Block.air) {
                lvl.AddUpdate(lvl.PosToInt(x, (ushort)(y - 1), z), Block.geyser);
            } else if (below != Block.geyser) {
                byte block = lvl.blocks[C.b];
                lvl.PhysWater(lvl.PosToInt((ushort)(x + 1), y, z), block);
                lvl.PhysWater(lvl.PosToInt((ushort)(x - 1), y, z), block);
                lvl.PhysWater(lvl.PosToInt(x, y, (ushort)(z + 1)), block);
                lvl.PhysWater(lvl.PosToInt(x, y, (ushort)(z - 1)), block);
            }

            if (lvl.physics <= 1 || C.time <= 10) return;
            C.time = 0;
            bool flowUp = false;
            
            GeyserFlow(lvl, x - 1, y, z, ref flowUp);
            GeyserFlow(lvl, x + 1, y, z, ref flowUp);
            GeyserFlow(lvl, x, y - 1, z, ref flowUp);
            GeyserFlow(lvl, x, y, z - 1, ref flowUp);
            GeyserFlow(lvl, x, y, z + 1, ref flowUp);
            if (flowUp)
                GeyserFlow(lvl, x, y + 1, z, ref flowUp);
        }
 public ContrainteCheck(Table entite, string nomContrainte)
     : this()
 {
     arrayCK = entite.CK;
     arrayAttributs = entite.attributs;
     check = new Check (nomContrainte);
 }
Example #4
0
 public Check CteateCheck()
 {
     Check newCheck = new Check();
     checks.Add(newCheck);
     newCheck.Show();
     return newCheck;
 }
Example #5
0
		public static Player ClosestPlayer(Level lvl, Check C) {
			if (!lvl.ai) return null;
			
			int closestDist = 75;
			Player closetPlayer = null;
			ushort x, y, z;
			lvl.IntToPos(C.b, out x, out y, out z);
			
			Player.players.ForEach(
				delegate(Player p)
				{
					if (p.level == lvl && !p.invincible) {
						int curDist = Math.Abs((p.pos[0] / 32) - x) +
							Math.Abs((p.pos[1] / 32) - y) +
							Math.Abs((p.pos[2] / 32) - z);
						
						if (curDist < closestDist) {
							closestDist = curDist;
							closetPlayer = p;
						}
					}
				}
			);
			return closetPlayer;
		}
Example #6
0
 internal static ChequeView newCheck()
 {
     Check c = new Check();
     ChequeView cv = new ChequeView(c);
     new DAOs.CheckDAO(cv.db).insertOnSubmit(c);
     return cv;
 }
 // Delete Check <check> from database
 public static bool delete(Check check)
 {
     using (DataClasses1DataContext database = new DataClasses1DataContext(Globals.connectionString))
     {
         var query = from c in database.Checks
                     where (c.CheckID == check.CheckID)
                     select c;
         // It seems to me that a single account renders the foreach unnecessary. However, I can't
         // find another way to get the variable 'a' from 'query'.
         foreach (var c in query)
         {
             database.Checks.DeleteOnSubmit(c);
             try
             {
                 database.SubmitChanges();
                 return true;
             }
             catch (Exception e)
             {
                 return false;
             }
         }
         return false;
     }
 }
 // Update Check <check>
 public static bool update(Check check)
 {
     using (DataClasses1DataContext database = new DataClasses1DataContext(Globals.connectionString))
     {
         var query = from a in database.Checks
                     where (a.CheckID == check.CheckID)
                     select a;
         foreach (var a in query)
         {
             a.CheckAmount = check.CheckAmount;
             a.CheckAmountOwed = check.CheckAmountOwed;
             a.CheckCashierID = check.CheckCashierID;
             a.CheckDate = check.CheckDate;
             a.CheckDeleted = check.CheckDeleted;
             a.CheckNum = check.CheckNum;
             a.CheckPaidDate = check.CheckPaidDate;
         }
         try
         {
             database.SubmitChanges();
             return true;
         }
         catch (Exception e)
         {
             return false;
         }
     }
 }
Example #9
0
		public static void Do(Level lvl, Check C, Random rand) {
			int dirX = rand.Next(1, 10) <= 5 ? 1 : -1;
			int dirY = rand.Next(1, 10) <= 5 ? 1 : -1;
			int dirZ = rand.Next(1, 10) <= 5 ? 1 : -1;
			ushort x, y, z;
			lvl.IntToPos(C.b, out x, out y, out z);

			for (int cx = -dirX; cx != 2 * dirX; cx += dirX)
				for (int cy = -dirY; cy != 2 * dirY; cy += dirY)
					for (int cz = -dirZ; cz != 2 * dirZ; cz += dirZ)
			{
				byte tileBelow = lvl.GetTile((ushort)(x + cx),(ushort)(y + cy - 1), (ushort)(z + cz));
				byte tile = lvl.GetTile((ushort)(x + cx),(ushort)(y + cy), (ushort)(z + cz));
				
				if ((tileBelow == Block.red || tileBelow == Block.op_air) &&
				    (tile == Block.air || tile == Block.water)) {
					lvl.AddUpdate(lvl.PosToInt((ushort)(x + cx), 
					                           (ushort)(y + cy), (ushort)(z + cz)), Block.train);
					lvl.AddUpdate(C.b, Block.air);
					
					byte newBlock = tileBelow == Block.red ? Block.obsidian : Block.glass;
					lvl.AddUpdate(lvl.IntOffset(C.b, 0, -1, 0), newBlock, true,
					          "wait 5 revert " + tileBelow.ToString());
					return;
				}
			}
		}
		void Upsert(Check check)
		{
			if (check.Id == 0)
				repo.Add(check);
			else
				repo.Update(check);
		}
Example #11
0
 private static void RemoveError(Check check)
 {
     if (_tracker.ContainsKey(check))
     {
         _tracker.Remove(check);
     }
 }
 public static Check AddCheck(Check check)
 {
     if (!isTesting)
         return prov.AddCheck(check);
     else
         return testprov.AddCheck(check);
 }
Example #13
0
 public static void DoFlood(Level lvl, Check C, Random rand, AirFlood mode, byte block) {
     if (C.time >= 1) {
         lvl.AddUpdate(C.b, 0);
         C.time = 255; return;
     }
     ushort x, y, z;
     lvl.IntToPos(C.b, out x, out y, out z);
     
     FloodAir(lvl, lvl.PosToInt((ushort)(x + 1), y, z), block);
     FloodAir(lvl, lvl.PosToInt((ushort)(x - 1), y, z), block);
     FloodAir(lvl, lvl.PosToInt(x, y, (ushort)(z + 1)), block);
     FloodAir(lvl, lvl.PosToInt(x, y, (ushort)(z - 1)), block);
     
     switch (mode) {
         case AirFlood.Full:
             FloodAir(lvl, lvl.PosToInt(x, (ushort)(y - 1), z), block);
             FloodAir(lvl, lvl.PosToInt(x, (ushort)(y + 1), z), block);
             break;
         case AirFlood.Layer:
             break;
         case AirFlood.Down:
             FloodAir(lvl, lvl.PosToInt(x, (ushort)(y - 1), z), block);
             break;
         case AirFlood.Up:
             FloodAir(lvl, lvl.PosToInt(x, (ushort)(y + 1), z), block);
             break;
     }
     C.time++;
 }
Example #14
0
        private static List<List<string>> GetList(string fileName, Check check, DayOfWeek dayOfWeek = DayOfWeek.Monday, int numberOfWeek = -1, string subgroup = "-1")
        {
            var settings = new XmlReaderSettings { IgnoreComments = true, IgnoreWhitespace = true };
            var elementsList = new List<List<string>>();
            try
            {
                var xmlReader = XmlReader.Create(fileName, settings);
                xmlReader.Read(); //декларация
                xmlReader.Read(); //коренной элемент
                xmlReader.Read(); //дочерний элемент
                while (!xmlReader.EOF)
                {
                    List<string> element = ReadOne(ref xmlReader);
                    if ((check == null && element != null && element.Count > 0) ||
                        (check != null && check(dayOfWeek, numberOfWeek, subgroup, element)))
                    {
                        elementsList.Add(element);
                    }
                }
                xmlReader.Close();
            }
            catch (FileNotFoundException)
            {
                File.Create(fileName);
            }
            catch (Exception)
            {
                elementsList = null;
            }

            return elementsList;
        }
Example #15
0
        public static void Do(Level lvl, Check C, Random rand) {
            int dirX = rand.Next(1, 10) <= 5 ? 1 : -1;
            int dirY = rand.Next(1, 10) <= 5 ? 1 : -1;
            int dirZ = rand.Next(1, 10) <= 5 ? 1 : -1;
            ushort x, y, z;
            lvl.IntToPos(C.b, out x, out y, out z);

            for (int cx = -dirX; cx != 2 * dirX; cx += dirX)
                for (int cy = -dirY; cy != 2 * dirY; cy += dirY)
                    for (int cz = -dirZ; cz != 2 * dirZ; cz += dirZ)
            {                
                byte rocketTail = lvl.GetTile((ushort)(x + cx), (ushort)(y + cy), (ushort)(z + cz));
                if (rocketTail != Block.fire) continue;
                
                int headIndex = lvl.PosToInt((ushort)(x - cx), (ushort)(y - cy), (ushort)(z - cz));
                byte rocketHead = headIndex < 0 ? Block.Zero : lvl.blocks[headIndex];                
                bool unblocked = !lvl.ListUpdate.Exists(u => u.b == headIndex || u.b == C.b);
                
                if (unblocked && (rocketHead == Block.air || rocketHead == Block.rocketstart)) {
                    lvl.AddUpdate(headIndex, Block.rockethead);
                    lvl.AddUpdate(C.b, Block.fire);
                } else if (rocketHead == Block.fire) {
                } else {
                    if (lvl.physics > 2)
                        lvl.MakeExplosion(x, y, z, 2);
                    else
                        lvl.AddUpdate(C.b, Block.fire);
                }
            }
        }
Example #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            StaticTest test = new StaticTest();

            test.FileName = txtFileName.Text;
            test.MaxScores = txtMaxScores.Text;
            Variable[] vars = new Variable[dgVars.Rows.Count];
            int cnt = 0;
            foreach (DataGridViewRow dgvr in dgVars.Rows)
            {
                string name = dgvr.Cells[0].Value + "";
                if (!name.Equals(""))
                {
                    vars[cnt] = new Variable();
                    vars[cnt].Name = name;
                    vars[cnt].DataType = dgvr.Cells[1].Value + "";
                    vars[cnt].Score = Int32.Parse(dgvr.Cells[2].Value + "");
                    vars[cnt].ErrMsg = dgvr.Cells[3].Value + "";
                    cnt++;
                }
            }
            test.Vars = vars;
            cnt = 0;
            Statement[] stmts = new Statement[dgStmts.Rows.Count];
            foreach (DataGridViewRow dgvr in dgStmts.Rows)
            {
                string type = dgvr.Cells[0].Value + "";
                if (!type.Equals(""))
                {
                    stmts[cnt] = new Statement();
                    stmts[cnt].Type = type;
                    stmts[cnt].Score = dgvr.Cells[1].Value + "";
                    stmts[cnt].ErrMsg = dgvr.Cells[2].Value + "";
                    cnt++;
                }
            }
            test.Stmts = stmts;
            Exceptions ex = new Exceptions();
            Check []checks = new Check[dgExceptions.Rows.Count];
            cnt = 0;
            foreach (DataGridViewRow dgvr in dgExceptions.Rows)
            {
                string type = dgvr.Cells[0].Value + "";
                if (!type.Equals(""))
                {
                    checks[cnt] = new Check();
                    checks[cnt].Type = type;
                    checks[cnt].Count = dgvr.Cells[1].Value + "";
                    checks[cnt].Statement = dgvr.Cells[2].Value + "";
                    checks[cnt].Score = dgvr.Cells[3].Value + "";
                    checks[cnt].ErrMsg = dgvr.Cells[4].Value + "";
                }
            }
            ex.Checks = checks;
            test.Ex = new Exceptions[] { ex };
            TestSuiteDB.saveStaticTest(test);
            MessageBox.Show("Static Check Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Hide();
        }
Example #17
0
 public Player(IActionManager bl, ISetting setting, Random rd)
     : base(bl, setting, rd)
 {
     NbTry = 1;
     CheckCharacter = new Check(bl);
     gameOver = new EndGame(bl);
     PropertyChanged += Play_PropertyChanged;
 }
Example #18
0
 internal StringElement(uint tag, String[] values, int maxLen, bool IsText, Trim trim, Check chk, Encoding encoding )
     : base(tag, null)
 {
     this.trim = trim;
     this.maxLen = maxLen;
     this.IsText = IsText;
     m_data = toByteBuffer( values, trim, chk == null ? new Check( DoCheck ) : chk, encoding );
 }
 public static GUIContent[] buildContentFromList(Check check, List<string> toBuild)
 {
     int arraySize = toBuild.Count;
     GUIContent[] content = new GUIContent[arraySize];
     for (int i = 0; i < arraySize; i++)
         content[i] = new GUIContent(toBuild[i]);
     return content;
 }
 public static GUIContent[] buildContentFromEnum(Check check, Type toBuild)
 {
     int arraySize = Enum.GetValues(toBuild).Length;
     GUIContent[] content = new GUIContent[arraySize];
     for (int i = 0; i < arraySize; i++)
         content[i] = new GUIContent(Enum.Parse(toBuild, i.ToString()).ToString());
     return content;
 }
Example #21
0
        public async Task<bool> AgentCheckRegisterAsync(Check check)
        {
            var uri = GetRequestUri("agent/check/register");

            var request = new HttpRequestMessage(HttpMethod.Put, uri);
            request.Content = new StringContent(JsonConvert.SerializeObject(check), Encoding.UTF8, "application/json");
            var response = await Execute(request);
            return response.StatusCode == HttpStatusCode.OK;
        }
Example #22
0
 public ChecksForm(MainForm form)
 {
     InitializeComponent();
     mainform = form;
     db = mainform.DataAppCore;
     currentModel = new Check();
     //set data grid settings
     ControlFactory.SetDataGridSettings(this.dataGridViewMainSearchResult);
 }
 public ActionResult Edit(Check check)
 {
     if (ModelState.IsValid)
     {
         checkRepo.Update(check);
         checkRepo.Save();
         return Json(new { success = true });
     }
     return PartialView("Edit", check);
 }
Example #24
0
 public MainForm()
 {
     InitializeComponent();
     //order
     order = new Order();
     //checking
     check = new Check();
     //computing price
     price = new Price();
 }
Example #25
0
 public static void DoFastLava(Level lvl, Check C, Random rand) {
     if (lvl.randomFlow) {
         byte oldTime = C.time;
         DoLavaRandowFlow(lvl, C, rand, false);
         if (C.time != 255)
             C.time = oldTime;
     } else {
         DoLavaUniformFlow(lvl, C, rand, false);
     }
 }
Example #26
0
		public static void Do(Level lvl, Check C, Random rand) {
			ushort x, y, z;
			lvl.IntToPos(C.b, out x, out y, out z);
			if (C.time < 2) {
				C.time++;
				return;
			}

			if (rand.Next(1, 20) == 1 && C.time % 2 == 0) {
				int max = rand.Next(1, 18);

				if (max <= 3 && ExpandSimple(lvl, x - 1, y, z)) {
				} else if (max <= 6 && ExpandSimple(lvl, x + 1, y, z)) {
				} else if (max <= 9 && ExpandSimple(lvl, x, y - 1, z)) {
				} else if (max <= 12 && ExpandSimple(lvl, x, y + 1, z)) {
				} else if (max <= 15 && ExpandSimple(lvl, x, y, z - 1)) {
				} else if (max <= 18 && ExpandSimple(lvl, x, y, z + 1)) {
				}
			}
			for (int yy = -1; yy <= 1; yy++ ) {
				ExpandDiagonal(lvl, x, y, z, -1, yy, -1);
				ExpandDiagonal(lvl, x, y, z, +1, yy, -1);
				ExpandDiagonal(lvl, x, y, z, -1, yy, +1);
				ExpandDiagonal(lvl, x, y, z, +1, yy, +1);
			}

			if (lvl.physics >= 2) {
				if (C.time < 4) {
					C.time++;
					return;
				}
				
				ExpandAvanced(lvl, x - 1, y, z);
				ExpandAvanced(lvl, x + 1, y, z);
				ExpandAvanced(lvl, x, y - 1, z);
				ExpandAvanced(lvl, x, y + 1, z);
				ExpandAvanced(lvl, x, y, z - 1);
				ExpandAvanced(lvl, x, y, z + 1);
			}

			C.time++;
			if (C.time > 5) {
				int dropType = rand.Next(1, 10);
				if (dropType <= 2) {
					lvl.AddUpdate(C.b, Block.coal);
					C.extraInfo = "drop 63 dissipate 10";
				} else if (dropType <= 4) {
					lvl.AddUpdate(C.b, Block.obsidian);
					C.extraInfo = "drop 63 dissipate 10";
				} else if (dropType <= 8)
					lvl.AddUpdate(C.b, Block.air);
				else
					C.time = 3;
			}
		}
Example #27
0
        public static void DoSmallTnt(Level lvl, Check C, Random rand) {
            ushort x, y, z;
            lvl.IntToPos(C.b, out x, out y, out z);

            if (C.p != null && C.p.PlayingTntWars) {
                int power = 2, threshold = 3;
                switch (TntWarsGame.GetTntWarsGame(C.p).GameDifficulty) {
                    case TntWarsGame.TntWarsDifficulty.Easy:
                        threshold = 7;
                        break;
                    case TntWarsGame.TntWarsDifficulty.Normal:
                        threshold = 5;
                        break;
                    case TntWarsGame.TntWarsDifficulty.Extreme:
                        power = 3;
                        break;
                }
                
                if (C.time < threshold) {
                    C.time++;
                    lvl.Blockchange(x, (ushort)(y + 1), z, lvl.GetTile(x, (ushort)(y + 1), z) == Block.lavastill
                                    ? Block.air : Block.lavastill);
                    return;
                }
                if (C.p.TntWarsKillStreak >= TntWarsGame.Properties.DefaultStreakTwoAmount 
                    && TntWarsGame.GetTntWarsGame(C.p).Streaks) {
                    power++;
                }
                lvl.MakeExplosion(x, y, z, power - 2, true, TntWarsGame.GetTntWarsGame(C.p));
                
                List<Player> Killed = new List<Player>();
                Player.players.ForEach(
                    delegate(Player p1)
                    {
                        if (p1.level == lvl && p1.PlayingTntWars && p1 != C.p
                            && Math.Abs((int)(p1.pos[0] / 32) - x) + Math.Abs((int)(p1.pos[1] / 32) - y) + Math.Abs((int)(p1.pos[2] / 32) - z) < ((power * 3) + 1)) {
                            Killed.Add(p1);
                        }
                    });
                TntWarsGame.GetTntWarsGame(C.p).HandleKill(C.p, Killed);
            } else {
                if (lvl.physics < 3) {
                    lvl.Blockchange(x, y, z, Block.air);
                } else {
                    if (C.time < 5 && lvl.physics == 3) {
                        C.time++;
                        lvl.Blockchange(x, (ushort)(y + 1), z, lvl.GetTile(x, (ushort)(y + 1), z) == Block.lavastill
                                        ? Block.air : Block.lavastill);
                        return;
                    }
                    lvl.MakeExplosion(x, y, z, 0);
                }
            }
        }
Example #28
0
 public static void DoWater(Level lvl, Check C, Random rand) {
     if (lvl.finite) {
         lvl.liquids.Remove(C.b);
         FinitePhysics.DoWaterOrLava(lvl, C, rand);
         return;
     }        
     if (lvl.randomFlow)
         DoWaterRandowFlow(lvl, C, rand);
     else
         DoWaterUniformFlow(lvl, C, rand);
 }
Example #29
0
        public Check(Check c)
        {
            type = c.type;
            value = c.value;
            invert = c.invert;
            contains = c.contains;

            checks = new List<Check>();
            for (int i = 0; i < c.checks.Count; i++)
                checks.Add(new Check(c.checks[i]));
        }
Example #30
0
 public void Log(Check check)
 {
     if (check.Passed())
     {
         RemoveError(check);
     }
     else
     {
         AppendError(check);
     }
 }
 public virtual void Add([NotNull] MetadataReference reference)
 => _references.Add(Check.NotNull(reference, nameof(reference)));
Example #32
0
        /// <summary>
        /// Adds an annotation with the specified name and value.
        /// </summary>
        /// <param name="name">The name of the annotation property.</param>
        /// <param name="value">The value of the annotation property.</param>
        public void AddAnnotation(string name, object value)
        {
            Check.NotEmpty(name, "name");

            MetadataProperties.Source.Add(MetadataProperty.CreateAnnotation(name, value));
        }
Example #33
0
 /// <summary>
 /// Configures the discriminator column used to differentiate between types in an inheritance hierarchy.
 /// </summary>
 /// <param name="discriminator"> The name of the discriminator column. </param>
 /// <returns> A configuration object to further configure the discriminator column and values. </returns>
 public ValueConditionConfiguration Requires(string discriminator)
 {
     Check.NotEmpty(discriminator, nameof(discriminator));
     return(new ValueConditionConfiguration(this._entityMappingConfiguration, discriminator));
 }
Example #34
0
        /// <summary>
        ///     Configures the primary key property for this entity type.
        /// </summary>
        /// <param name="propertyName"> The name of the property to be used as the primary key. </param>
        /// <returns>
        ///     The same <see cref="LightweightEntityConfiguration" /> instance so that multiple calls can be chained.
        /// </returns>
        /// <remarks>
        ///     Calling this will have no effect once it has been configured of if the
        ///     property does not exist.
        /// </remarks>
        public LightweightEntityConfiguration HasKey(string propertyName)
        {
            Check.NotEmpty(propertyName, "propertyName");

            return(HasKey(new[] { propertyName }));
        }
        public DbFunctionBuilder([NotNull] IMutableDbFunction function)
        {
            Check.NotNull(function, nameof(function));

            _function = (DbFunction)function;
        }
 /// <summary>
 /// 更新站内信信息
 /// </summary>
 /// <param name="dtos">包含更新信息的站内信信息DTO信息</param>
 /// <returns>业务操作结果</returns>
 public virtual Task<OperationResult> UpdateMessages(params MessageInputDto[] dtos)
 {
     Check.Validate<MessageInputDto, Guid>(dtos, nameof(dtos));
     return MessageRepository.UpdateAsync(dtos);
 }
Example #37
0
        /// <summary>
        /// Creates a new <see cref="DbCommandTreeInterceptionContext" /> that contains all the contextual information in this
        /// interception context with the addition of the given <see cref="ObjectContext" />.
        /// </summary>
        /// <param name="context">The context to associate.</param>
        /// <returns>A new interception context associated with the given context.</returns>
        public new DbCommandTreeInterceptionContext WithObjectContext(ObjectContext context)
        {
            Check.NotNull(context, "context");

            return((DbCommandTreeInterceptionContext)base.WithObjectContext(context));
        }
 private void AssertInitialized()
 {
     Check.Requires <InvalidOperationException>(_vmDescriptor != null, "Behavior is not initalized.");
 }
Example #39
0
        /// <summary>
        /// Returns the default name for the primary key.
        /// </summary>
        /// <param name="table">The target table name.</param>
        /// <returns>The default primary key name.</returns>
        public static string BuildDefaultName(string table)
        {
            Check.NotEmpty(table, "table");

            return(string.Format(CultureInfo.InvariantCulture, "PK_{0}", table).RestrictTo(128));
        }
 public void IndexOutOfRange_8(string fixture)
 {
     var content = SampleFile.Load(fixture);
     var lexer = new CSharpLexer();
     Check.ThatCode(() => lexer.GetTokens(content)).DoesNotThrow();
 }
Example #41
0
        public virtual ObjectExtensionInfo GetOrNull([NotNull] Type type)
        {
            Check.AssignableTo <IHasExtraProperties>(type, nameof(type));

            return(ObjectsExtensions.GetOrDefault(type));
        }
        public CompositePredicateExpressionVisitorFactory([NotNull] IDbContextOptions contextOptions)
        {
            Check.NotNull(contextOptions, nameof(contextOptions));

            _contextOptions = contextOptions;
        }
Example #43
0
        protected override Expression VisitEntityQueryable(Type elementType)
        {
            Check.NotNull(elementType, nameof(elementType));

            var relationalQueryCompilationContext = QueryModelVisitor.QueryCompilationContext;
            var entityType = _model.FindEntityType(elementType);

            var selectExpression = _selectExpressionFactory.Create();

            QueryModelVisitor.AddQuery(_querySource, selectExpression);

            var name = _relationalAnnotationProvider.For(entityType).TableName;

            var tableAlias
                = _querySource.HasGeneratedItemName()
                    ? name[0].ToString().ToLowerInvariant()
                    : _querySource.ItemName;

            var fromSqlAnnotation
                = relationalQueryCompilationContext
                  .QueryAnnotations
                  .OfType <FromSqlResultOperator>()
                  .LastOrDefault(a => a.QuerySource == _querySource);

            Func <IQuerySqlGenerator> querySqlGeneratorFunc = selectExpression.CreateDefaultQuerySqlGenerator;

            if (fromSqlAnnotation == null)
            {
                selectExpression.AddTable(
                    new TableExpression(
                        name,
                        _relationalAnnotationProvider.For(entityType).Schema,
                        tableAlias,
                        _querySource));
            }
            else
            {
                selectExpression.AddTable(
                    new FromSqlExpression(
                        fromSqlAnnotation.Sql,
                        fromSqlAnnotation.Arguments,
                        tableAlias,
                        _querySource));

                var useQueryComposition
                    = fromSqlAnnotation.Sql
                      .TrimStart()
                      .StartsWith("SELECT ", StringComparison.OrdinalIgnoreCase);

                if (!useQueryComposition)
                {
                    if (relationalQueryCompilationContext.IsIncludeQuery)
                    {
                        throw new InvalidOperationException(
                                  RelationalStrings.StoredProcedureIncludeNotSupported);
                    }
                }

                if (useQueryComposition &&
                    fromSqlAnnotation.QueryModel.IsIdentityQuery() &&
                    !fromSqlAnnotation.QueryModel.ResultOperators.Any() &&
                    !relationalQueryCompilationContext.IsIncludeQuery)
                {
                    useQueryComposition = false;
                }

                if (!useQueryComposition)
                {
                    QueryModelVisitor.RequiresClientEval = true;

                    querySqlGeneratorFunc = ()
                                            => selectExpression.CreateFromSqlQuerySqlGenerator(
                        fromSqlAnnotation.Sql,
                        fromSqlAnnotation.Arguments);
                }
            }

            var shaper = CreateShaper(elementType, entityType, selectExpression);

            return(Expression.Call(
                       QueryModelVisitor.QueryCompilationContext.QueryMethodProvider // TODO: Don't use ShapedQuery when projecting
                       .ShapedQueryMethod
                       .MakeGenericMethod(shaper.Type),
                       EntityQueryModelVisitor.QueryContextParameter,
                       Expression.Constant(_shaperCommandContextFactory.Create(querySqlGeneratorFunc)),
                       Expression.Constant(shaper)));
        }
Example #44
0
 public NotNullConditionConfiguration Requires <TProperty>(
     Expression <Func <TEntityType, TProperty> > property)
 {
     Check.NotNull <Expression <Func <TEntityType, TProperty> > >(property, nameof(property));
     return(new NotNullConditionConfiguration(this._entityMappingConfiguration, property.GetComplexPropertyAccess()));
 }
 public static StringBuilder AppendFormatInvariant(this StringBuilder sb, string format, params object[] args) => Check.NotNull(nameof(sb), sb).AppendFormat(CultureInfo.InvariantCulture, format, args);
Example #46
0
 /// <summary>
 /// Creates a new <see cref="DbCommandTreeInterceptionContext" /> by copying state from the given
 /// interception context. Also see <see cref="DbCommandTreeInterceptionContext.Clone" />
 /// </summary>
 /// <param name="copyFrom">The context from which to copy state.</param>
 public DbCommandTreeInterceptionContext(DbInterceptionContext copyFrom)
     : base(copyFrom)
 {
     Check.NotNull(copyFrom, "copyFrom");
 }
 /// <summary>
 /// 删除站内信信息
 /// </summary>
 /// <param name="ids">要删除的站内信信息编号</param>
 /// <returns>业务操作结果</returns>
 public virtual Task<OperationResult> DeleteMessages(params Guid[] ids)
 {
     Check.NotNull(ids, nameof(ids));
     return MessageRepository.DeleteAsync(ids);
 }
Example #48
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual ValueGenerator Create(
            IProperty property,
            SqlServerSequenceValueGeneratorState generatorState,
            ISqlServerConnection connection,
            IRawSqlCommandBuilder rawSqlCommandBuilder)
        {
            Check.NotNull(property, nameof(property));
            Check.NotNull(generatorState, nameof(generatorState));
            Check.NotNull(connection, nameof(connection));
            Check.NotNull(rawSqlCommandBuilder, nameof(rawSqlCommandBuilder));

            var type = property.ClrType.UnwrapNullableType().UnwrapEnumType();

            if (type == typeof(long))
            {
                return(new SqlServerSequenceHiLoValueGenerator <long>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(int))
            {
                return(new SqlServerSequenceHiLoValueGenerator <int>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(decimal))
            {
                return(new SqlServerSequenceHiLoValueGenerator <decimal>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(short))
            {
                return(new SqlServerSequenceHiLoValueGenerator <short>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(byte))
            {
                return(new SqlServerSequenceHiLoValueGenerator <byte>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(char))
            {
                return(new SqlServerSequenceHiLoValueGenerator <char>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(ulong))
            {
                return(new SqlServerSequenceHiLoValueGenerator <ulong>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(uint))
            {
                return(new SqlServerSequenceHiLoValueGenerator <uint>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(ushort))
            {
                return(new SqlServerSequenceHiLoValueGenerator <ushort>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            if (type == typeof(sbyte))
            {
                return(new SqlServerSequenceHiLoValueGenerator <sbyte>(rawSqlCommandBuilder, _sqlGenerator, generatorState, connection));
            }

            throw new ArgumentException(
                      CoreStrings.InvalidValueGeneratorFactoryProperty(
                          nameof(SqlServerSequenceValueGeneratorFactory), property.Name, property.DeclaringEntityType.DisplayName()));
        }
Example #49
0
        protected override Expression VisitShapedQuery(ShapedQueryExpression shapedQueryExpression)
        {
            Check.NotNull(shapedQueryExpression, nameof(shapedQueryExpression));

            var selectExpression = (SelectExpression)shapedQueryExpression.QueryExpression;

            VerifyNoClientConstant(shapedQueryExpression.ShaperExpression);
            var nonComposedFromSql = selectExpression.IsNonComposedFromSql();
            var splitQuery = ((RelationalQueryCompilationContext)QueryCompilationContext).QuerySplittingBehavior
                == QuerySplittingBehavior.SplitQuery;
            var shaper = new ShaperProcessingExpressionVisitor(this, selectExpression, _tags, splitQuery, nonComposedFromSql).ProcessShaper(
                shapedQueryExpression.ShaperExpression, out var relationalCommandCache, out var relatedDataLoaders);

            if (nonComposedFromSql)
            {
                return Expression.New(
                    typeof(FromSqlQueryingEnumerable<>).MakeGenericType(shaper.ReturnType).GetConstructors()[0],
                    Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)),
                    Expression.Constant(relationalCommandCache),
                    Expression.Constant(
                        selectExpression.Projection.Select(pe => ((ColumnExpression)pe.Expression).Name).ToList(),
                        typeof(IReadOnlyList<string>)),
                    Expression.Constant(shaper.Compile()),
                    Expression.Constant(_contextType),
                    Expression.Constant(
                        QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution),
                    Expression.Constant(_detailedErrorsEnabled));
            }

            if (splitQuery)
            {
                var relatedDataLoadersParameter = Expression.Constant(
                    QueryCompilationContext.IsAsync ? null : relatedDataLoaders?.Compile(),
                    typeof(Action<QueryContext, IExecutionStrategy, SplitQueryResultCoordinator>));

                var relatedDataLoadersAsyncParameter = Expression.Constant(
                    QueryCompilationContext.IsAsync ? relatedDataLoaders?.Compile() : null,
                    typeof(Func<QueryContext, IExecutionStrategy, SplitQueryResultCoordinator, Task>));

                return Expression.New(
                    typeof(SplitQueryingEnumerable<>).MakeGenericType(shaper.ReturnType).GetConstructors().Single(),
                    Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)),
                    Expression.Constant(relationalCommandCache),
                    Expression.Constant(shaper.Compile()),
                    relatedDataLoadersParameter,
                    relatedDataLoadersAsyncParameter,
                    Expression.Constant(_contextType),
                    Expression.Constant(
                        QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution),
                    Expression.Constant(_detailedErrorsEnabled));
            }

            return Expression.New(
                typeof(SingleQueryingEnumerable<>).MakeGenericType(shaper.ReturnType).GetConstructors()[0],
                Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)),
                Expression.Constant(relationalCommandCache),
                Expression.Constant(shaper.Compile()),
                Expression.Constant(_contextType),
                Expression.Constant(
                    QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution),
                    Expression.Constant(_detailedErrorsEnabled));
        }
Example #50
0
 public void Properties <TObject>(
     Expression <Func <TEntityType, TObject> > propertiesExpression)
 {
     Check.NotNull <Expression <Func <TEntityType, TObject> > >(propertiesExpression, nameof(propertiesExpression));
     this._entityMappingConfiguration.Properties = propertiesExpression.GetComplexPropertyAccessList().ToList <PropertyPath>();
 }
Example #51
0
        /// <summary>
        ///     The visitor pattern method for expression visitors that produce a result value of a specific type.
        /// </summary>
        /// <param name="visitor"> An instance of a typed DbExpressionVisitor that produces a result value of type TResultType. </param>
        /// <typeparam name="TResultType">
        ///     The type of the result produced by <paramref name="visitor" />
        /// </typeparam>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="visitor" />
        ///     is null
        /// </exception>
        /// <returns>
        ///     An instance of <typeparamref name="TResultType" /> .
        /// </returns>
        public override TResultType Accept <TResultType>(DbExpressionVisitor <TResultType> visitor)
        {
            Check.NotNull(visitor, "visitor");

            return(visitor.Visit(this));
        }
        /// <inheritdoc />
        public virtual void Apply(NavigationProperty item, DbModel model)
        {
            Check.NotNull(item, "item");
            Check.NotNull(model, "model");

            var associationType = item.Association;

            if (associationType.Constraint != null)
            {
                return;
            }

            var foreignKeyAttribute
                = item.GetClrAttributes <ForeignKeyAttribute>().SingleOrDefault();

            if (foreignKeyAttribute == null)
            {
                return;
            }

            AssociationEndMember principalEnd, dependentEnd;

            if (associationType.TryGuessPrincipalAndDependentEnds(out principalEnd, out dependentEnd) ||
                associationType.IsPrincipalConfigured())
            {
                dependentEnd = dependentEnd ?? associationType.TargetEnd;
                principalEnd = principalEnd ?? associationType.SourceEnd;

                var dependentPropertyNames
                    = foreignKeyAttribute.Name
                      .Split(',')
                      .Select(p => p.Trim());

                var declaringEntityType
                    = model.ConceptualModel.EntityTypes
                      .Single(e => e.DeclaredNavigationProperties.Contains(item));

                var dependentProperties
                    = GetDependentProperties(
                          dependentEnd.GetEntityType(),
                          dependentPropertyNames,
                          declaringEntityType,
                          item).ToList();

                var constraint
                    = new ReferentialConstraint(
                          principalEnd,
                          dependentEnd,
                          principalEnd.GetEntityType().KeyProperties().ToList(),
                          dependentProperties);

                var dependentKeyProperties = dependentEnd.GetEntityType().KeyProperties();

                if (dependentKeyProperties.Count() == constraint.ToProperties.Count() &&
                    dependentKeyProperties.All(kp => constraint.ToProperties.Contains(kp)))
                {
                    principalEnd.RelationshipMultiplicity = RelationshipMultiplicity.One;

                    if (dependentEnd.RelationshipMultiplicity.IsMany())
                    {
                        dependentEnd.RelationshipMultiplicity = RelationshipMultiplicity.ZeroOrOne;
                    }
                }

                if (principalEnd.IsRequired())
                {
                    constraint.ToProperties.Each(p => p.Nullable = false);
                }

                associationType.Constraint = constraint;
            }
        }
Example #53
0
        /// <summary>
        ///     Configures a property that is defined on this type.
        /// </summary>
        /// <param name="name"> The name of the property being configured. </param>
        /// <returns> A configuration object that can be used to configure the property. </returns>
        /// <remarks>
        ///     If the property doesn't exist, any configuration will be silently ignored.
        /// </remarks>
        public LightweightPropertyConfiguration Property(string name)
        {
            Check.NotEmpty(name, "name");

            return(Property(_type.GetProperty(name)));
        }
        protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
        {
            Check.NotNull(methodCallExpression, nameof(methodCallExpression));

            if (Equals(_startsWithMethodInfo, methodCallExpression.Method) ||
                Equals(_endsWithMethodInfo, methodCallExpression.Method))
            {
                if (methodCallExpression.Arguments[0] is ConstantExpression constantArgument &&
                    constantArgument.Value is string stringValue &&
                    stringValue == string.Empty)
                {
                    // every string starts/ends with empty string.
                    return(Expression.Constant(true));
                }

                var newObject   = Visit(methodCallExpression.Object) !;
                var newArgument = Visit(methodCallExpression.Arguments[0]);

                var result = Expression.AndAlso(
                    Expression.NotEqual(newObject, _constantNullString),
                    Expression.AndAlso(
                        Expression.NotEqual(newArgument, _constantNullString),
                        methodCallExpression.Update(newObject, new[] { newArgument })));

                return(newArgument is ConstantExpression
                    ? result
                    : Expression.OrElse(
                           Expression.Equal(
                               newArgument,
                               Expression.Constant(string.Empty)),
                           result));
            }

            if (methodCallExpression.Method.IsGenericMethod &&
                methodCallExpression.Method.GetGenericMethodDefinition() is MethodInfo methodInfo &&
                (methodInfo.Equals(EnumerableMethods.AnyWithPredicate) || methodInfo.Equals(EnumerableMethods.All)) &&
                methodCallExpression.Arguments[0].NodeType is ExpressionType nodeType &&
                (nodeType == ExpressionType.Parameter || nodeType == ExpressionType.Constant) &&
                methodCallExpression.Arguments[1] is LambdaExpression lambda &&
                TryExtractEqualityOperands(lambda.Body, out var left, out var right, out var negated) &&
                (left is ParameterExpression || right is ParameterExpression))
            {
                var nonParameterExpression = left is ParameterExpression ? right : left;

                if (methodInfo.Equals(EnumerableMethods.AnyWithPredicate) &&
                    !negated)
                {
                    var containsMethod = EnumerableMethods.Contains.MakeGenericMethod(methodCallExpression.Method.GetGenericArguments()[0]);
                    return(Expression.Call(null, containsMethod, methodCallExpression.Arguments[0], nonParameterExpression));
                }

                if (methodInfo.Equals(EnumerableMethods.All) && negated)
                {
                    var containsMethod = EnumerableMethods.Contains.MakeGenericMethod(methodCallExpression.Method.GetGenericArguments()[0]);
                    return(Expression.Not(Expression.Call(null, containsMethod, methodCallExpression.Arguments[0], nonParameterExpression)));
                }
            }

            if (methodCallExpression.Method.IsGenericMethod &&
                methodCallExpression.Method.GetGenericMethodDefinition() is MethodInfo containsMethodInfo &&
                containsMethodInfo.Equals(QueryableMethods.Contains))
            {
                var typeArgument = methodCallExpression.Method.GetGenericArguments()[0];
                var anyMethod    = QueryableMethods.AnyWithPredicate.MakeGenericMethod(typeArgument);

                var anyLambdaParameter = Expression.Parameter(typeArgument, "p");
                var anyLambda          = Expression.Lambda(
                    Expression.Equal(
                        anyLambdaParameter,
                        methodCallExpression.Arguments[1]),
                    anyLambdaParameter);

                return(Expression.Call(null, anyMethod, new[] { methodCallExpression.Arguments[0], anyLambda }));
            }

            var @object = default(Expression);

            if (methodCallExpression.Object != null)
            {
                @object = MatchExpressionType(
                    Visit(methodCallExpression.Object),
                    methodCallExpression.Object.Type);
            }

            var arguments = new Expression[methodCallExpression.Arguments.Count];

            for (var i = 0; i < arguments.Length; i++)
            {
                arguments[i] = MatchExpressionType(
                    Visit(methodCallExpression.Arguments[i]),
                    methodCallExpression.Arguments[i].Type);
            }

            var visited = methodCallExpression.Update(@object !, arguments);

            // In VB.NET, comparison operators between strings (equality, greater-than, less-than) yield
            // calls to a VB-specific CompareString method. Normalize that to string.Compare.
            if (visited.Method.Name == "CompareString" &&
                visited.Method.DeclaringType?.Name == "Operators" &&
                visited.Method.DeclaringType?.Namespace == "Microsoft.VisualBasic.CompilerServices" &&
                visited.Object == null &&
                visited.Arguments.Count == 3 &&
                visited.Arguments[2] is ConstantExpression textCompareConstantExpression &&
                _stringCompareWithComparisonMethod != null &&
                _stringCompareWithoutComparisonMethod != null)
            {
                return(textCompareConstantExpression.Value is bool boolValue &&
                       boolValue
                    ? Expression.Call(
                           _stringCompareWithComparisonMethod,
                           visited.Arguments[0],
                           visited.Arguments[1],
                           Expression.Constant(StringComparison.OrdinalIgnoreCase))
                    : Expression.Call(
                           _stringCompareWithoutComparisonMethod,
                           visited.Arguments[0],
                           visited.Arguments[1]));
            }

            return(visited);
        }
Example #55
0
 public MaxExpression([NotNull] Expression expression)
     : base(Check.NotNull(expression, nameof(expression)))
 {
 }
Example #56
0
        public ITransactionApi FindTransactionApi(string key)
        {
            Check.NotNull(key, nameof(key));

            return _transactionApis.GetOrDefault(key);
        }
Example #57
0
 public virtual void SetAssignedIdTo(string assignedId)
 {
     Check.Require(!string.IsNullOrEmpty(assignedId), "Assigned Id may not be null or empty");
     Id = assignedId.Trim();
 }
Example #58
0
        public void TestFileNameConstructor()
        {
            var r = new RegistryHiveOnDemand(@"..\..\..\Hives\SAM");

            Check.That(r.Header).IsNotNull();
        }
Example #59
0
        public CSRedisClientNameAttribute([NotNull] string name)
        {
            Check.NotNullOrWhiteSpace(name, nameof(name));

            Name = name;
        }
Example #60
0
        /// <summary>
        ///     The visitor pattern method for expression visitors that do not produce a result value.
        /// </summary>
        /// <param name="visitor"> An instance of DbExpressionVisitor. </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="visitor" />
        ///     is null
        /// </exception>
        public override void Accept(DbExpressionVisitor visitor)
        {
            Check.NotNull(visitor, "visitor");

            visitor.Visit(this);
        }