public QuerySorter(string field, SortingOperation sortingOperation) { ConditionChecker.Requires(string.IsNullOrEmpty(field) == false); this.Field = field; this.SortingOperation = sortingOperation; }
protected DataSet ToDataSet(string procedure, IDictionary <string, object> parameters, out int returnValue, params string[] tableNames) { ConditionChecker.Required( !tableNames.IsNullOrEmpty(), new ArgumentNullException("tableNames")); DataSet dsResults = new DataSet() { RemotingFormat = SerializationFormat.Binary }; SqlConnection dbConnection = null; SqlCommand dbCommand = null; try { dbConnection = this.GetSqlConnection(true); dbCommand = new SqlCommand(); dbCommand.CommandType = CommandType.StoredProcedure; dbCommand.CommandText = procedure; dbCommand.Connection = dbConnection; this.AddParameters(dbCommand, parameters); dbCommand.Parameters.Add(new SqlParameter("@ReturnValue", SqlDbType.Int) { Direction = ParameterDirection.ReturnValue }); using (var et = new ExecutionTracerService(procedure)) using (var dbAdapter = new SqlDataAdapter(dbCommand)) { const string tName = "Table"; for (int i = 0; i < tableNames.Length; i++) { dbAdapter.TableMappings.Add((i == 0) ? tName : tName + i, tableNames[i]); } dbAdapter.Fill(dsResults); returnValue = TypeHelper.To <int>(dbCommand.Parameters["@ReturnValue"].Value); } } catch (Exception x) { if (this.OperationError != null) { this.OperationError(this, new CrudOperationErrorEventArgs(x, procedure, parameters)); } throw; } finally { dbCommand.SafeDispose(); dbConnection.SafeDispose(); } return(dsResults); }
protected ObjectColor GetColor(IMetricTypeCacheReadObject metricType, IMetricCacheReadObject metric, double?value) { var conditionRed = metric.ConditionRed ?? metricType.ConditionRed; var conditionYellow = metric.ConditionYellow ?? metricType.ConditionYellow; var conditionGreen = metric.ConditionGreen ?? metricType.ConditionGreen; var color = metric.ElseColor ?? metricType.ElseColor ?? ObjectColor.Gray; var parameters = new[] { new KeyValuePair <string, double?>("value", value) }; if (ConditionChecker.Check(parameters, conditionRed)) { color = ObjectColor.Red; } else if (ConditionChecker.Check(parameters, conditionYellow)) { color = ObjectColor.Yellow; } else if (ConditionChecker.Check(parameters, conditionGreen)) { color = ObjectColor.Green; } return(color); }
private void CalculateSnowLoad2() { if (ConditionChecker.ForDesignSituation(snowLoad.ExcepctionalSituation, snowLoad.CurrentDesignSituation, true)) { RightSnowLoad = SnowLoadCalc.CalculateSnowLoadForAnnexB(RightShapeCoefficient, snowLoad.SnowLoadForSpecificReturnPeriod); } }
public bool Update() { bool hasBeenUpdated = false; if (!Reached) { switch (Milestone.getType()) { case Completable.Milestone.MilestoneType.COMPLETABLE: var targetCompletable = AnalyticsExtension.Instance.GetCompletable(Milestone.getId()); Reached = targetCompletable.End.Reached; break; case Completable.Milestone.MilestoneType.CONDITION: Reached = ConditionChecker.check(Milestone.getConditions()); break; } if (Reached) { hasBeenUpdated = true; } } return(hasBeenUpdated); }
public void checkTimers() { foreach (Timer t in timers) { if (ConditionChecker.check(t.getInitCond())) { if (!isRunning(t)) { TimerState ts = new TimerState(); if (t.isCountDown()) { ts.type = TimerType.COUNTDOWN; ts.max_time = 0; ts.current_time = System.Convert.ToInt64(t.getTime() * 1000) / 1000f; } else { ts.type = TimerType.NORMAL; ts.max_time = System.Convert.ToInt64(t.getTime() * 1000) / 1000f; ts.current_time = 0; } ts.timer = t; running_timers.Add(ts); } } else if (isRunning(t)) { removeFromRunning(t); } } }
private void CalculateSnowLoad1() { if (ConditionChecker.ForDesignSituation(snowLoad.ExcepctionalSituation, snowLoad.CurrentDesignSituation, true)) { SnowLoadNearTheTop = SnowLoadCalc.CalculateSnowLoadForAnnexB(ShapeCoefficient1, snowLoad.SnowLoadForSpecificReturnPeriod); } }
IEnumerable <T> IQueryFilterEngine <T> .SortCollection(IEnumerable <T> collection, QueryGroup queryGroup) { ConditionChecker.Requires(collection != null, "Occurrences list cannot be null."); var querySorters = queryGroup.SortingRules; if (querySorters == null || querySorters.Count == 0) { return(collection); } var targetedType = typeof(T); IOrderedEnumerable <T> result = querySorters[0].SortingOperation == SortingOperation.Ascending ? collection.OrderBy(x => targetedType.GetPropertyValue(querySorters[0].Field, x)) : collection.OrderByDescending( x => targetedType.GetPropertyValue(querySorters[0].Field, x)); if (querySorters.Count > 1) { result = querySorters.Skip(1).Aggregate( (IOrderedEnumerable <T>)result, (current, thenBy) => thenBy.SortingOperation == SortingOperation.Ascending ? current.ThenBy(x => targetedType.GetPropertyValue(thenBy.Field, x)) : current.ThenByDescending(x => targetedType.GetPropertyValue(thenBy.Field, x))); } return(result); }
public void OnQRCode(string content) { if (qr != null) { return; } bool blackList = QRPromptEffect.SelectionType == QRPromptEffect.ListType.BlackList; bool contained = QRPromptEffect.ValidIds.Contains(content); if ((blackList && !contained) || (!blackList && contained)) { qr = Game.Instance.GameState.FindElement <QR>(content); if (qr != null && ConditionChecker.check(qr.Conditions)) {// Si existe y además cumple las condiciones // Mostramos el contenido y el resto de efectos var effects = new Effects(); if (qr.Content != "") { effects.add(new SpeakPlayerEffect(qr.Content)); } foreach (var effect in qr.Effects.getEffects()) { effects.add(effect); } effectHolder = new EffectHolder(effects); this.transform.GetChild(0).gameObject.SetActive(false); } } }
public void UpdateConditions() { var display = !Element.IsRemoved() && (Reference.Conditions == null || ConditionChecker.check(Reference.Conditions)); this.gameObject.SetActive(display); }
/// <summary> /// Saves (or updates) the entity in the database. /// </summary> /// /// <param name="entity"> /// Entity to save or update. /// </param> /// /// <param name="options"> /// Optional options. /// </param> /// /// <returns> /// The number of affected rows. /// </returns> public override int Save(ref VahapYigit.Test.Models.UserRole entity, SaveOptions options = null) { ConditionChecker.Required( entity != null, new ArgumentNullException("entity")); if (options == null) { options = SaveOptions.Default; } int rowCount = 0; using (var scope = TransactionScopeHelper.CreateDefaultTransactionScope()) { this.OnSaving(ref entity, options); if (options.SaveChildren) { rowCount = this.PersistWithChildren(ref entity, new ObjectIDGenerator(), options); } else { rowCount = this.Persist(ref entity, options); } this.OnSaved(ref entity, options); scope.Complete(); } return(rowCount); }
void Start() { playerStatistics.ResetValues(); EntityKilledEvent.Register(onEntityKilled); CrystalDeliveredEvent.Register(onCrystalDelivered); conditionChecker = GetComponent <ConditionChecker>(); }
public void UpdateConditions() { var display = !Context.IsRemoved() && (Context.Conditions == null || ConditionChecker.check(Context.Conditions)); this.gameObject.SetActive(display); this.Representable.checkResources(); }
/// <summary> /// Checks the comparison between left and right member. /// </summary> /// <param name="data">The BotData used for variable replacement.</param> /// <returns>Whether the comparison is valid</returns> public bool CheckKey(BotData data) { try { return(ConditionChecker.Verify(LeftTerm, Condition, RightTerm, data)); } catch { return(false); } // Return false if e.g. we can't parse the number for a LessThan/GreaterThan comparison. }
/// <summary> /// Asynchronously transforms the user's 32-byte key using ECB AES. /// /// Since Rijndael works on 16-byte blocks, the k is split in half and /// each half is encrypted separately the same number of times. /// </summary> /// <param name="rawKey">The key to transform.</param> /// <param name="token">Token used to cancel the transform task.</param> /// <returns>The transformed key.</returns> public async Task <IBuffer> TransformKeyAsync(IBuffer rawKey, CancellationToken token) { if (rawKey == null) { throw new ArgumentNullException(nameof(rawKey)); } if (rawKey.Length != 32) { throw new ArgumentException("Key must be 32 bytes", nameof(rawKey)); } // Split the k buffer in half byte[] rawKeyBytes = rawKey.ToArray(); IBuffer lowerBuffer = WindowsRuntimeBuffer.Create(rawKeyBytes, 0, 16, 16); IBuffer upperBuffer = WindowsRuntimeBuffer.Create(rawKeyBytes, 16, 16, 16); // Set up the encryption parameters var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb); CryptographicKey key = aes.CreateSymmetricKey(this.algoParams.Seed); IBuffer iv = null; // Run the encryption rounds in two threads (upper and lower) ConditionChecker checkForCancel = () => token.IsCancellationRequested; Task <bool> lowerTask = Task.Run(() => { lowerBuffer = KeePassHelper.TransformKey(this.algoParams.Rounds, this.algoParams.Seed, iv, lowerBuffer, checkForCancel); return(!checkForCancel()); } ); Task <bool> upperTask = Task.Run(() => { upperBuffer = KeePassHelper.TransformKey(this.algoParams.Rounds, this.algoParams.Seed, iv, upperBuffer, checkForCancel); return(!checkForCancel()); } ); // Verify the work was completed successfully await Task.WhenAll(lowerTask, upperTask); if (!(lowerTask.Result && upperTask.Result)) { return(null); } // Copy the units of work back into one buffer, hash it, and return. IBuffer transformedKey = (new byte[32]).AsBuffer(); lowerBuffer.CopyTo(0, transformedKey, 0, 16); upperBuffer.CopyTo(0, transformedKey, 16, 16); var sha256 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256); CryptographicHash hash = sha256.CreateHash(); hash.Append(transformedKey); return(hash.GetValueAndReset()); }
protected QueryField( string name, string type) { ConditionChecker.Requires(string.IsNullOrEmpty(name) == false); ConditionChecker.Requires(string.IsNullOrEmpty(type) == false); this.Name = name; this.Type = type; }
/// <summary> /// Gets the Action that needs to be executed. /// </summary> /// <param name="line">The data line to parse</param> /// <param name="data">The BotData needed for variable replacement</param> /// <returns>The Action to execute</returns> public static Action Parse(string line, BotData data) { var input = line.Trim(); var field = LineParser.ParseToken(ref input, TokenType.Parameter, true).ToUpper(); return(new Action(() => { var name = ""; Condition cond = Condition.EqualTo; switch (field) { case "COOKIE": if (LineParser.Lookahead(ref input) == TokenType.Parameter) { cond = (Condition)LineParser.ParseEnum(ref input, "TYPE", typeof(Condition)); } name = LineParser.ParseLiteral(ref input, "NAME"); for (int i = 0; i < data.Cookies.Count; i++) { var curr = data.Cookies.ToList()[i].Key; if (ConditionChecker.Verify(curr, cond, name, data)) { data.Cookies.Remove(curr); } } break; case "VAR": if (LineParser.Lookahead(ref input) == TokenType.Parameter) { cond = (Condition)LineParser.ParseEnum(ref input, "TYPE", typeof(Condition)); } name = LineParser.ParseLiteral(ref input, "NAME"); data.Variables.Remove(cond, name, data); break; case "GVAR": if (LineParser.Lookahead(ref input) == TokenType.Parameter) { cond = (Condition)LineParser.ParseEnum(ref input, "TYPE", typeof(Condition)); } name = LineParser.ParseLiteral(ref input, "NAME"); try { data.GlobalVariables.Remove(cond, name, data); } catch { } break; default: throw new ArgumentException($"Invalid identifier {field}"); } data.Log(new LogEntry($"DELETE command executed on field {field}", Colors.White)); })); }
private static void Postfix(CharacterDrop __instance) { try { if (ConfigurationManager.CharacterDropConfigs == null) { Log.LogDebug("Loading drop tables"); ConfigurationManager.LoadAllCharacterDropConfigurations(); } string name = __instance.gameObject.name; CharacterDropMobConfiguration configMatch = FindConfigMatch(name); // Find drop list string dropListName = configMatch?.UseDropList?.Value; CharacterDropListConfiguration listConfig = null; if (!string.IsNullOrWhiteSpace(dropListName) && ConfigurationManager.CharacterDropLists is not null && ConfigurationManager.CharacterDropLists.TryGet(dropListName, out CharacterDropListConfiguration dropList)) { listConfig = dropList; } bool skipExisting = false; if (GeneralConfig.ClearAllExistingCharacterDrops || GeneralConfig.ClearAllExistingCharacterDropsWhenModified && (configMatch?.Subsections?.Any(x => x.Value.EnableConfig) == true || listConfig?.Subsections?.Any(x => x.Value.EnableConfig) == true)) { skipExisting = true; } if (skipExisting && __instance.m_drops.Count > 0) { Log.LogTrace($"[{name}]: Clearing '{__instance.m_drops.Count}'"); __instance.m_drops.Clear(); } // Merge list and mob config var configs = MobDropInitializationService.PrepareInsertion(listConfig, configMatch); foreach (var config in configs) { InsertDrops(__instance, config); } __instance.m_drops = ConditionChecker.FilterOnStart(__instance); } catch (Exception e) { Log.LogError("Error while attempting to configure creature drops.", e); } }
public QueryRule(string field, FieldOperation fieldOperation, object value, LogicalOperation logicalOperation) { ConditionChecker.Requires(string.IsNullOrEmpty(field) == false); ConditionChecker.Requires(value != null); Field = field; FieldOperation = fieldOperation; Value = value; LogicalOperation = logicalOperation; }
Predicate <T> IQueryCompiler <T> .CompileRule(QueryRule queryRule) { ConditionChecker.Requires(queryRule != null, "Query Rule cannot be null."); // When migrating the database, some fields of the old DTO might be missing. if (!typeof(T).HasProperty(queryRule.Field)) { return(null); } var targetedType = Expression.Parameter(typeof(T)); var leftMember = Expression.Property(targetedType, queryRule.Field); var propertyType = typeof(T).GetProperty(queryRule.Field)?.PropertyType; if (propertyType == null) { return(null); } Expression expression; // The given rule is binary(aka : equal, less than , gte, etc.) if (Enum.TryParse(Operations.Get(queryRule.FieldOperation), out ExpressionType binaryOperator)) { var queriedValue = GetQueriedValue(queryRule, propertyType); expression = Expression.MakeBinary(binaryOperator, leftMember, queriedValue); } else { // The given rule is a method(aka: Contains, Equals, etc. var queriedMethod = GetQueriedMethod(queryRule, propertyType); if (queriedMethod == null) { return(null); } var rightMember = GetRightMember(queryRule, queriedMethod); if (propertyType == typeof(string)) { var toLowerMethodInfo = typeof(string).GetMethod("ToLower", new Type[] { }); Expression leftMemberLowerCase = Expression.Call(leftMember, toLowerMethodInfo ?? throw new MissingMethodException()); Expression rightMemberLowerCase = Expression.Call(rightMember, toLowerMethodInfo ?? throw new MissingMethodException()); expression = Expression.Call(leftMemberLowerCase, queriedMethod, rightMemberLowerCase); } else { expression = Expression.Call(leftMember, queriedMethod, rightMember); } } return(Expression.Lambda <Predicate <T> >(expression, targetedType).Compile()); }
public void IsNullConditionTest() { var parameters = new[] { new KeyValuePair <string, double?>("HDD", null) }; var condition = @"HDD == null"; var result = ConditionChecker.Check(parameters, condition); Assert.True(result); }
public int checkGlobalState(string global_state) { int ret = GlobalStateCondition.GS_SATISFIED; GlobalState gs = data.getChapters() [current_chapter].getGlobalState(global_state); if (gs != null) { ret = ConditionChecker.check(gs); } return(ret); }
public void NullAndZero2Test() { var parameters = new[] { new KeyValuePair <string, double?>("value", null), }; var condition = @"value > 10"; var result = ConditionChecker.Check(parameters, condition); Assert.False(result); }
public void EmptyConditionTest() { var parameters = new[] { new KeyValuePair <string, double?>("HDD", null) }; var condition = @""; var result = ConditionChecker.Check(parameters, condition); Assert.False(result); }
protected void checkResources() { foreach (ResourcesUni resource in element.getResources()) { if (ConditionChecker.check(resource.getConditions())) { this.resource = resource; break; } } }
public void ReleaseElement(MapElement mapElement) { if (AdoptedElements.Contains(mapElement)) { AdoptedElements.Remove(mapElement); if (mapElement.Conditions == null || ConditionChecker.check(mapElement.Conditions)) { OrphanElements.Add(mapElement); } } }
/// <summary> /// Parses a condition made of left-hand term, condition type and right-hand term and verifies if it's true. /// </summary> /// <param name="cfLine">The reference to the line to parse</param> /// <param name="data">The BotData needed for variable replacement</param> /// <returns></returns> public static bool ParseCheckCondition(ref string cfLine, BotData data) { var first = LineParser.ParseLiteral(ref cfLine, "STRING"); var condition = (Condition)LineParser.ParseEnum(ref cfLine, "CONDITION", typeof(Condition)); var second = ""; if (condition != Condition.Exists) { second = LineParser.ParseLiteral(ref cfLine, "STRING"); } return(ConditionChecker.Verify(first, condition, second, data)); }
private void RedirectSubmitEventsToThisController(Control control, int pageId) { foreach (var v in control.Controls) { if (v is Button) { ((Button)v).Enabled = ConditionChecker.IsSubmitEnabled(StageId, pageId); ((Button)v).Click += SubmitClick; } } }
public void UnSatisfiedConditionTest() { var parameters = new[] { new KeyValuePair <string, double?>("HDD", 100), new KeyValuePair <string, double?>("MEM", 500), }; var condition = @"HDD <= 100 && MEM <= 100"; var result = ConditionChecker.Check(parameters, condition); Assert.False(result); }
public void updateResource() { current_resource = null; foreach (ResourcesUni cr in player.getResources()) { if (ConditionChecker.check(cr.getConditions())) { current_resource = cr; break; } } }
void SetCondition(CEnemy.Condition cond_, int cond_num_) { if (state_cond[cond_num_] == null) { switch (cond_) { case Condition.NULL: state_cond[cond_num_] = new ConditionChecker(OnThisState); break; case Condition.CheckTime: state_cond[cond_num_] = new ConditionChecker(CheckTime); break; case Condition.CheckOneFrame: state_cond[cond_num_] = new ConditionChecker(CheckOneFrame); break; case Condition.CheckLeftSide: state_cond[cond_num_] = new ConditionChecker(CheckLeftSide); break; case Condition.CheckRightSide: state_cond[cond_num_] = new ConditionChecker(CheckRightSide); break; case Condition.CheckUpperSide: state_cond[cond_num_] = new ConditionChecker(CheckUpperSide); break; case Condition.CheckLowerSide: state_cond[cond_num_] = new ConditionChecker(CheckLowerSide); break; case Condition.CheckDistance: state_cond[cond_num_] = new ConditionChecker(CheckDistance); break; case Condition.CheckDistanceX: state_cond[cond_num_] = new ConditionChecker(CheckDistanceX); break; case Condition.CheckDistanceY: state_cond[cond_num_] = new ConditionChecker(CheckDistanceY); break; case Condition.CheckRadius: state_cond[cond_num_] = new ConditionChecker(CheckRadius); break; case Condition.CheckHP: state_cond[cond_num_] = new ConditionChecker(CheckHP); break; default: break; } } }
public EventLink(Condition c, IRenderer renderer, Part p) { m_checker = new ConditionChecker(c, renderer, p); m_executed = false; }