//Initialize task from Weak variables public Task(XmlElement Element) { if (Element.Name != "Task") throw new Exception("Incorrect XML markup"); this.Name = Element.GetElementsByTagName("Name")[0].InnerText; this.GroupName = Element.GetElementsByTagName("GroupName")[0].InnerText; this.Description = Element.GetElementsByTagName("Description")[0].InnerText; this.Active = Element.GetElementsByTagName("Active")[0].InnerText == "1"; XmlElement TriggersElement = (XmlElement)Element.GetElementsByTagName("Triggers")[0]; foreach (XmlElement TriggerElement in TriggersElement.ChildNodes) { Trigger Trigger = new Trigger(TriggerElement); Triggers.Add(Trigger); Trigger.AssignTask(this); } XmlElement ConditionsElement = (XmlElement)Element.GetElementsByTagName("Conditions")[0]; foreach (XmlElement ConditionElement in ConditionsElement.ChildNodes) { Condition Condition = new Condition(ConditionElement); Conditions.Add(Condition); Condition.AssignTask(this); } XmlElement ActionsElement = (XmlElement)Element.GetElementsByTagName("Actions")[0]; foreach (XmlElement ActionElement in ActionsElement.ChildNodes) { Actions.Action Action = new Actions.Action(ActionElement); Actions.Add(Action); Action.AssignTask(this); } }
public bool IsValid(object caller, Condition condition) { if (WorkbenchSingleton.Workbench == null) { return false; } string openwindow = condition.Properties["openwindow"]; if (openwindow == "*") { return WorkbenchSingleton.Workbench.ActiveWorkbenchWindow != null; } foreach (IViewContent view in WorkbenchSingleton.Workbench.ViewContentCollection) { Type currentType = view.GetType(); if (currentType.ToString() == openwindow) { return true; } foreach (Type i in currentType.GetInterfaces()) { if (i.ToString() == openwindow) { return true; } } } return false; }
public bool IsValid(object owner, Condition condition) { var surface = owner as DesignSurface; if (surface != null) return surface.CanDelete(); return false; }
/// <summary> /// Constructor /// </summary> /// <param name="Id">The rank ID</param> /// <param name="Conditions">The conditions to earn the rank</param> public Rank(int Id, Condition Conditions) { this.Id = Id; this.Name = GetName(Id); this.Conditions = Conditions; this.OrigConditions = (Condition)Conditions.Clone(); }
public bool IsValid(object owner, Condition condition) { XmlView xmlView = XmlView.ActiveXmlView; if (xmlView != null) return xmlView.StylesheetFileName != null; return false; }
private AutomationElement FindOrWaitForOpenWindow(Condition condition, TimeSpan timeout) { DateTime startedAt = DateTime.Now; Monitor.Enter(_waitingRoom); AutomationElement windowElement; AutomationEventHandler handler = delegate { windowElement = WindowOpened(condition); }; Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Children, handler); windowElement = FindOpenWindow(condition); while (windowElement == null && (DateTime.Now.Subtract(startedAt)).CompareTo(timeout) < 0) { // We are polling because sometimes the event handler doesn't fire // quickly enough for my liking - the system is too busy. This lets // us check every second, while still taking advantage of the event handling // if it does decide to fire. Monitor.Wait(_waitingRoom, Math.Min(1000, timeout.Milliseconds)); } Automation.RemoveAutomationEventHandler( WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, handler); Monitor.Exit(_waitingRoom); return windowElement; }
public bool IsValid(object caller, Condition condition) { string activeWindow = condition.Properties["activewindow"]; if (activeWindow == "*") { return SD.Workbench.ActiveWorkbenchWindow != null; } Type activeWindowType = condition.AddIn.FindType(activeWindow); if (activeWindowType == null) { SD.Log.WarnFormatted("WindowActiveCondition: cannot find Type {0}", activeWindow); return false; } if (SD.GetActiveViewContentService(activeWindowType) != null) return true; if (SD.Workbench.ActiveWorkbenchWindow == null || SD.Workbench.ActiveWorkbenchWindow.ActiveViewContent == null) return false; Type currentType = SD.Workbench.ActiveWorkbenchWindow.ActiveViewContent.GetType(); if (currentType.FullName == activeWindow) return true; foreach (Type interf in currentType.GetInterfaces()) { if (interf.FullName == activeWindow) return true; } while ((currentType = currentType.BaseType) != null) { if (currentType.FullName == activeWindow) return true; } return false; }
public string ToString(Condition c) { var s = ExportExpressionList(c); if (!s.HasValue()) s = "MatchAnything = 1[True]"; return s; }
public bool IsValid(object caller, Condition condition) { if (WorkbenchSingleton.Workbench == null) { return false; } string activewindow = condition.Properties["activewindow"]; if (activewindow == "*") { return WorkbenchSingleton.Workbench.ActiveWorkbenchWindow != null; } if (WorkbenchSingleton.Workbench.ActiveWorkbenchWindow == null || WorkbenchSingleton.Workbench.ActiveWorkbenchWindow.ActiveViewContent == null) { return false; } Type currentType = WorkbenchSingleton.Workbench.ActiveWorkbenchWindow.ActiveViewContent.GetType(); if (currentType.FullName == activewindow) return true; foreach (Type interf in currentType.GetInterfaces()) { if (interf.FullName == activewindow) return true; } while ((currentType = currentType.BaseType) != null) { if (currentType.FullName == activewindow) return true; } return false; }
private string ExportExpressionList(Condition c) { if (!c.IsGroup) return c.ToString(); if (!c.Conditions.Any()) return null; var list = c.Conditions.Select(ExportExpression).ToList(); string andOrNot; string not = ""; switch (c.ComparisonType) { case CompareType.AllTrue: andOrNot = $"\n{Level}AND "; break; case CompareType.AnyTrue: andOrNot = $"\n{Level}OR "; break; case CompareType.AllFalse: andOrNot = $"\n{Level}AND NOT "; not = "NOT "; break; default: throw new ArgumentException(); } var inner = string.Join(andOrNot, list.Where(vv => vv.HasCode())); return $"{Level}{not}{inner}"; }
public Automation WithCondition(ConditionRelation relation, Condition condition) { if (condition == null) throw new ArgumentNullException(nameof(condition)); Conditions.Add(new RelatedCondition().WithCondition(condition).WithRelation(relation)); return this; }
public void TestAddConditionGroupWithChildren() { IPolicyLanguage language = new PolicyLanguage(new Guid("{E8B22533-98EB-4D00-BDE4-406DC3E1858B}"), "en"); XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance; catalogueStore.Reset(); PolicyCatalogue policyCatalogue = new PolicyCatalogue(new Guid("{AB5E2A43-01FB-4AA6-98FC-8F74BB0621CA}"), language.Identifier, new TranslateableLanguageItem("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), catalogueStore); catalogueStore.AddPolicyCatalogue(policyCatalogue); PolicySetObserver policySetObserver = new PolicySetObserver(policyCatalogue); Assert.AreEqual(0, policyCatalogue.Conditions.Count); Assert.AreEqual(0, policyCatalogue.ConditionGroups.Count); IConditionGroup conditionGroup = new ConditionGroup(new Guid("{5823E98A-1F4D-44B9-BC0E-A538BD2C9262}"), new TranslateableLanguageItem("Test group"), ConditionLogic.AND, false); IConditionGroup subConditionGroup = new ConditionGroup(new Guid("{B87DF614-2400-4C1F-BEA8-3C2EB3964EAE}"), new TranslateableLanguageItem("Test sub group"), ConditionLogic.AND, false); ICondition condition = new Condition(new Guid("{98C73BC3-3E20-403C-8023-C91E2818355F}"), "TestClass", new TranslateableLanguageItem("This is a test"), OperatorType.Equals); subConditionGroup.Conditions.Add(condition); conditionGroup.Conditions.Add(subConditionGroup); policySetObserver.AddObject(conditionGroup); Assert.AreEqual(1, policyCatalogue.Conditions.Count); Assert.AreEqual(2, policyCatalogue.ConditionGroups.Count); }
public bool IsValid(object caller, Condition condition) { if (WorkbenchSingleton.Workbench == null) { return false; } ITextEditorProvider provider = WorkbenchSingleton.Workbench.ActiveViewContent as ITextEditorProvider; if (provider == null) return false; LanguageProperties language = ParserService.CurrentProjectContent.Language; if (language == null) return false; if (string.IsNullOrEmpty(provider.TextEditor.FileName)) return false; RefactoringProvider rp = language.RefactoringProvider; if (!rp.IsEnabledForFile(provider.TextEditor.FileName)) return false; string supports = condition.Properties["supports"]; if (supports == "*") return true; Type t = rp.GetType(); try { return (bool)t.InvokeMember("Supports" + supports, BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty, null, rp, null); } catch (Exception ex) { LoggingService.Warn(ex.ToString()); return false; } }
private IPolicyObjectCollection<IPolicyObject> BuildConditions() { DataMethod dataMethod = new DataMethod("Test method"); dataMethod.Parameters.Add(new Parameter("FindSomething", new DataElement(new TranslateableLanguageItem("string value"), new TranslateableLanguageItem(""), DataType.String, "missing"))); dataMethod.Parameters.Add(new Parameter("RunSomething", new DataElement(new TranslateableLanguageItem("string value"), new TranslateableLanguageItem(""), DataType.String, "just do it!"))); DataSource dataSource = new DataSource("Testme.dll", "TestMe", dataMethod); ICondition subCondition = new Condition(new Guid("{6B7F6B0C-747A-4BD0-A65D-A1FB9E44FE7C}"), "ITestOne", OperatorType.GreaterThan); subCondition.DataLeft = new DataElement(new Guid("{4E2F50C5-D310-47A1-AE3A-621F5C77FA68}"), new TranslateableLanguageItem("Do testing stuff"), new TranslateableLanguageItem(""), DataType.Object, dataSource); IDataItem dataItem = DataItem.CreateDataItem(new TranslateableLanguageItem("Test data item"), DataType.Long, "10"); subCondition.DataRight = new DataElement(new Guid("{EB56B397-954D-45C2-ADBA-263372A8B59F}"), new TranslateableLanguageItem("Test data item stored in data element"), new TranslateableLanguageItem(""), DataType.Long, dataItem); IConditionGroup subConditionGroup = new ConditionGroup(new Guid("{661EDD6F-D750-493A-9932-E56C8C22E2CF}"), new TranslateableLanguageItem("Test group two"), ConditionLogic.AND, false); subConditionGroup.Conditions.Add(subCondition); IConditionGroup conditionGroup = new ConditionGroup(new Guid("{D64056E5-A19D-4B29-8F4A-A70337B42A19}"), new TranslateableLanguageItem("Test group one"), ConditionLogic.OR, true); conditionGroup.Conditions.Add(subConditionGroup); DataMethod dataMethod2 = new DataMethod("Test method two"); dataMethod2.Parameters.Add(new Parameter("DoIt", new DataElement(new TranslateableLanguageItem("string value"), new TranslateableLanguageItem(""), DataType.String, "You should do this"))); dataMethod2.Parameters.Add(new Parameter("DontDoIt", new DataElement(new TranslateableLanguageItem("string value"), new TranslateableLanguageItem(""), DataType.String, "You should not do this"))); DataSource dataSource2 = new DataSource("Test2.dll", "JustDoIt", dataMethod2); ICondition condition = new Condition(new Guid("{A6F876B6-AD6D-4842-BC0D-4635D1EEE916}"), "ITestTwo", OperatorType.GreaterThanOrEqualTo); condition.DataLeft = new DataElement(new Guid("{7CED5561-FD8C-423C-838F-9440EDFE6758}"), new TranslateableLanguageItem("Some data source"), new TranslateableLanguageItem(""), DataType.Object, dataSource2); IDataItem dataItem2 = DataItem.CreateDataItem(new TranslateableLanguageItem("Test data item 2"), DataType.Long, "2"); condition.DataRight = new DataElement(new Guid("{C6E38158-AB8C-496B-B97D-FD413680977D}"), new TranslateableLanguageItem("Test result2"), new TranslateableLanguageItem(""), DataType.Long, dataItem2); IPolicyObjectCollection<IPolicyObject> conditions = new PolicyObjectCollection<IPolicyObject>(); conditions.Add(conditionGroup); conditions.Add(condition); return conditions; }
public CandidateCall(Condition _condition, Candidate _Candidate, string _date, string _comment) { Candidate = _Candidate; condition = _condition; callDate = _date; comment = _comment; }
/// <summary> /// Creates a new instance of the Rule using the rule defined in the policy document. /// </summary> /// <param name="rule">The rule defined in the policy document.</param> public Rule(RuleElement rule) { if (rule == null) throw new ArgumentNullException("rule"); _rule = rule; if (_rule.SchemaVersion == XacmlVersion.Version10 || _rule.SchemaVersion == XacmlVersion.Version11) { _condition = new Condition((ConditionElement)_rule.Condition); } else if (_rule.SchemaVersion == XacmlVersion.Version20) { _condition = new Condition2((ConditionElement)_rule.Condition); } if (rule.Target != null) { _target = new Target((TargetElement)rule.Target); // Load all the resources for the elements within this rule. foreach (ResourceElement resource in rule.Target.Resources.ItemsList) { foreach (ResourceMatchElement rmatch in resource.Match) { if (!_allResources.Contains(rmatch.AttributeValue.Contents)) { _allResources.Add(rmatch.AttributeValue.Contents); } } } } }
public Effect() { Condition = new Condition(); SetFlags = new Condition(); SpeakPlayer = new List<SpeakPlayer>(); }
private Condition(Condition condition) { this.Algorithm = condition.Algorithm; this.ConditionParameter = condition.ConditionParameter; this.Id = condition.Id; this.Operator = condition.Operator; }
public bool IsValid(object caller, Condition condition) { if (ProjectService.OpenSolution == null) { return false; } foreach (IProject p in ProjectService.OpenSolution.Projects) { // Check project name if (p.Name.Equals(condition.Properties["itemName"], StringComparison.OrdinalIgnoreCase)) { return true; } // Check references foreach (ProjectItem pi in p.Items) { ReferenceProjectItem rpi = pi as ReferenceProjectItem; if (rpi != null) { if (rpi.Name.Equals(condition.Properties["itemName"], StringComparison.OrdinalIgnoreCase)) { return true; } } } } return false; }
public bool IsValid(object caller, Condition condition) { var wb = Workbench.Instance; if (wb != null) { var exp = wb.ActiveSiteExplorer; if (exp != null) { var cmds = condition.Properties["commands"].Split(','); //NOXLATE var connMgr = ServiceRegistry.GetService<ServerConnectionManager>(); var conn = connMgr.GetConnection(exp.ConnectionName); int[] caps = conn.Capabilities.SupportedCommands; foreach (var cmdName in cmds) { try { CommandType cmd = (CommandType)Enum.Parse(typeof(CommandType), cmdName); if (Array.IndexOf(caps, (int)cmd) < 0) return false; } catch { return false; } } return true; } } return false; }
public bool IsValid(object caller, Condition condition) { var node = ProjectBrowserPad.Instance?.SelectedNode; var fileSystemInfo = node?.GetNodeFileSystemInfo(); return fileSystemInfo != null && fileSystemInfo.CanBeVersionControlledItem(); }
public void InitTest_CUST_AndPreviouslyApplied() { NumericFilterVM target = new NumericFilterVM(); string columnName = "TestColumn1"; string columnTitle = "Test Column 1"; NumericFilterSelectionType _filterType = new NumericFilterSelectionType(); _filterType = NumericFilterSelectionType.CUSTOM; FilterColumn _column = new FilterColumn(); _column.ColumnName = columnName; _column.FilterType = FilterSelectionType.NUMERIC_CUST; _column.ColumnSelectedDataList = new System.Collections.Generic.List<string>(); _column.ConditionList = new System.Collections.Generic.List<Condition>(); Condition cond = new Condition(); cond.IncludedConditionList = new System.Collections.ObjectModel.ObservableCollection<Condition>(); cond.LogicalOperatorOfIncludedCondition = LogicOperatorType.AND; Condition cond1 = new Condition("TestColumn1", OperatorType.GREATER_THAN_OR_EQUAL); Condition cond2 = new Condition("TestColumn1", OperatorType.LESS_THAN_OR_EQUAL); cond.IncludedConditionList.Add(cond1); cond.IncludedConditionList.Add(cond2); _column.ConditionList.Add(cond); _column.CurrentRowDataValue = null; target.Init(columnName, columnTitle, _filterType, _column); Assert.AreEqual(columnName, target.FieldName); Assert.AreEqual(columnTitle, target.FieldNameTitle); Assert.AreEqual(OperatorType.GREATER_THAN_OR_EQUAL, target.FirstCondition.ConditionOperator); Assert.AreEqual(cond1, target.FirstCondition); Assert.AreEqual(cond2, target.SecondCondition); }
/// <summary> /// Creates instance of the <see cref="Action"></see> class with properties initialized with specified parameters. /// </summary> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="Action"/>.</param> protected Action(Return returnType, When when, Step step, Condition condition) { Return = returnType; Step = step; When = when; Condition = condition; }
public bool IsValid(object caller, Condition condition) { if (caller is ISolutionFolderNode) return ProjectService.OpenSolution != null && !ProjectService.OpenSolution.IsReadOnly; IProject project = (caller as IProject) ?? ProjectService.CurrentProject; return project != null && !project.IsReadOnly; }
public bool IsValid(object caller, Condition condition, Codon codon) { if (caller is IOwnerState) { try { string str = condition.Properties.Get<string>("ownerstate", string.Empty); if (codon.Properties.Contains("ownerstate")) { str = codon.Properties["ownerstate"]; } if (string.IsNullOrEmpty(str) || (str == "*")) { return true; } Enum internalState = ((IOwnerState) caller).InternalState; Enum enum3 = (Enum) Enum.Parse(internalState.GetType(), str); int num = int.Parse(internalState.ToString("D")); int num2 = int.Parse(enum3.ToString("D")); if (LoggingService.IsDebugEnabled) { LoggingService.DebugFormatted("stateInt:{0}, conditionInt:{1}", new object[] { num, num2 }); } return ((num & num2) > 0); } catch (Exception) { throw new ApplicationException(string.Format("[{0}] can't parse '" + condition.Properties["ownerstate"] + "'. Not a valid value.", codon.Id)); } } return false; }
private static Node CreateInteractionBehavior(Dorf d, IInteractable i) { Condition findWork = new Condition(() => { //TODO: what check here? Maybe an action to get a work-place? return false; }); BehaviorTrees.Action goToWork = new BehaviorTrees.Action(() => { //TODO: replace vector param with location of workplace! var mc = new MoveCommand(d,new Vector3(),WALKSPEED); if (mc.isAllowed()) { mc.execute(); return Node.Status.RUNNING; } else { return Node.Status.FAIL; } }); BehaviorTrees.Action work = new BehaviorTrees.Action(() => { //TODO: replace null value with some kind of interactable variable from d. var ic = new InteractCommand(d,null); if (ic.isAllowed()) { ic.execute(); return Node.Status.RUNNING; } else { return Node.Status.FAIL; } }); SequenceSelector root = new SequenceSelector(findWork,goToWork,work); return root; }
// PUT api/Conditions/5 public HttpResponseMessage PutCondition(String id, Condition condition) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != condition.ID) { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(condition).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
public override void PerformTest() { Log("Creating " + _numberOfThreads + " threads"); Thread[] threads = new Thread[_numberOfThreads]; for (int i = 0; i < _numberOfThreads; i++) { threads[i] = new Thread(Work, ThreadPriority.Normal); } _startedThreads = 0; _startedThreadsLock = new Lock(); _allThreadsStartedLock = new Lock(); _allThreadsStartedCondition = new Condition(_allThreadsStartedLock); _allThreadsStartedLock.Acquire(); Log("Starting " + _numberOfThreads + " threads"); // TODO: ParametizedThreadStart doesn't work properly for (int i = 0; i < _numberOfThreads; i++) { threads[i].Start(); } // wait for all threads to be running _allThreadsStartedCondition.Await(); _allThreadsStartedLock.Release(); Log("Waiting for all threads to finish"); _semaphore.Acquire(_numberOfThreads); // wait for all threads to finish Assert(_failedThreads + " threads failed the calculation", _failedThreads == 0); Log("All " + _numberOfThreads + " threads finished"); }
public ANDCondition(Condition aLeftCon, Condition aRightCon) { Debug.Assert(null != aLeftCon); Debug.Assert(null != aRightCon); left = aLeftCon; right = aRightCon; }
public void AddCondition(SearchFields field, Condition condition) { if (! Conditions.ContainsKey(field)) Conditions.Add(field, new List<Condition>()); Conditions[field].Add(condition); }
public static ValueCondition <int> SiblingCount(Condition c) { var description = string.Format(CultureInfo.InvariantCulture, ConditionDescriptions.ChildCount, c); return(new ValueCondition <int>(e => SiblingCount(c, e), description)); }
protected Coroutine WaitFor(Condition condition) { return(StartCoroutine(WaitForInternal(condition, Environment.StackTrace))); }
/// <summary> /// 查询事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_DirectClick(object sender, DirectEventArgs e) { try { if (string.IsNullOrEmpty(kakou.Value) && string.IsNullOrEmpty(cbocllx.Text)) { DateTime start = Convert.ToDateTime(starttime); DateTime end = Convert.ToDateTime(endtime); TimeSpan sp = end.Subtract(start); if (sp.TotalMinutes > 120) { Notice("信息提示", "只能选择两个小时之内的时间!"); this.FormPanel2.Title = "查询结果:当前查询出符合条件的记录0条,现在显示0条"; LabNum.Html = "<font > 当前1页,共0页</font>"; ButNext.Disabled = true; ButLast.Disabled = true; Store1.DataSource = new DataTable(); Store1.DataBind(); return; } } if (!string.IsNullOrEmpty(kakou.Value)) { if (kakou.Value.Contains(",")) { string[] strs = kakou.Value.Split(','); if (strs.Length > 10) { Notice("信息提示", "最多只能选择10个卡口!"); this.FormPanel2.Title = "查询结果:当前查询出符合条件的记录0条,现在显示0条"; LabNum.Html = "<font > 当前1页,共0页</font>"; ButNext.Disabled = true; ButLast.Disabled = true; Store1.DataSource = new DataTable(); Store1.DataBind(); return; } } } if (Session["Condition"] != null) { Session["Condition"] = null; } Condition con = new Condition(); con.StartTime = starttime; con.EndTime = endtime; if (SBcsys.Value != null) { con.Csys = SBcsys.Value.ToString(); } if (!string.IsNullOrEmpty(this.kakou.Value)) { string kkid = this.kakouId.Value.ToString(); if (!string.IsNullOrEmpty(kkid)) { con.Kkid = kkid; if (Session["tree"] != null) { Session["tree"] = null; } Session["tree"] = kkid; } con.Kkidms = this.kakou.Value; } if (!string.IsNullOrEmpty(ClppChoice.Value)) { con.Clpp = ClppChoice.Value; } if (cbocllx.SelectedIndex != -1) { con.Hpzl = cbocllx.SelectedItem.Value; } con.Njb = Cnjbz.Checked; con.Zjh = Czjh.Checked; con.Zyb = Czyb.Checked; con.Dz = Cdz.Checked; con.Bj = Cbj.Checked; Session["Condition"] = con; changePage(1); } catch (Exception ex) { ILog.WriteErrorLog(ex); logManager.InsertLogError("UnlicensedVehiclesQuery.aspx-Button1_DirectClick", ex.Message + ";" + ex.StackTrace, "Button1_DirectClick has an exception"); } }
public Condition Or(Condition other) { return(New(() => IsTrue || other.IsTrue)); }
public Condition And(Condition other) { return(New(() => IsTrue && other.IsTrue)); }
public override async Task AbandonAsync(IQueueEntry <T> entry) { _logger.LogDebug("Queue {Name}:{QueueId} abandon item: {EntryId}", _options.Name, QueueId, entry.Id); if (entry.IsAbandoned || entry.IsCompleted) { _logger.LogError("Queue {Name}:{QueueId} unable to abandon item because already abandoned or completed: {EntryId}", _options.Name, QueueId, entry.Id); throw new InvalidOperationException("Queue entry has already been completed or abandoned."); } string attemptsCacheKey = GetAttemptsKey(entry.Id); var attemptsCachedValue = await Run.WithRetriesAsync(() => _cache.GetAsync <int>(attemptsCacheKey), logger : _logger).AnyContext(); int attempts = 1; if (attemptsCachedValue.HasValue) { attempts = attemptsCachedValue.Value + 1; } var retryDelay = GetRetryDelay(attempts); _logger.LogInformation("Item: {EntryId}, Retry attempts: {RetryAttempts}, Retries Allowed: {Retries}, Retry Delay: {RetryDelay:g}", entry.Id, attempts - 1, _options.Retries, retryDelay); if (attempts > _options.Retries) { _logger.LogInformation("Exceeded retry limit moving to deadletter: {EntryId}", entry.Id); var tx = Database.CreateTransaction(); tx.AddCondition(Condition.KeyExists(GetRenewedTimeKey(entry.Id))); tx.ListRemoveAsync(_workListName, entry.Id); tx.ListLeftPushAsync(_deadListName, entry.Id); tx.KeyDeleteAsync(GetRenewedTimeKey(entry.Id)); tx.KeyExpireAsync(GetPayloadKey(entry.Id), _options.DeadLetterTimeToLive); bool success = await Run.WithRetriesAsync(() => tx.ExecuteAsync(), logger : _logger).AnyContext(); if (!success) { throw new InvalidOperationException("Queue entry not in work list, it may have been auto abandoned."); } await Run.WithRetriesAsync(() => Task.WhenAll( _cache.IncrementAsync(attemptsCacheKey, 1, GetAttemptsTtl()), Database.KeyDeleteAsync(GetDequeuedTimeKey(entry.Id)), Database.KeyDeleteAsync(GetWaitTimeKey(entry.Id)) ), logger : _logger).AnyContext(); } else if (retryDelay > TimeSpan.Zero) { _logger.LogInformation("Adding item to wait list for future retry: {EntryId}", entry.Id); await Run.WithRetriesAsync(() => Task.WhenAll( _cache.SetAsync(GetWaitTimeKey(entry.Id), SystemClock.UtcNow.Add(retryDelay).Ticks, GetWaitTimeTtl()), _cache.IncrementAsync(attemptsCacheKey, 1, GetAttemptsTtl()) ), logger : _logger).AnyContext(); var tx = Database.CreateTransaction(); tx.AddCondition(Condition.KeyExists(GetRenewedTimeKey(entry.Id))); tx.ListRemoveAsync(_workListName, entry.Id); tx.ListLeftPushAsync(_waitListName, entry.Id); tx.KeyDeleteAsync(GetRenewedTimeKey(entry.Id)); bool success = await Run.WithRetriesAsync(() => tx.ExecuteAsync()).AnyContext(); if (!success) { throw new InvalidOperationException("Queue entry not in work list, it may have been auto abandoned."); } await Run.WithRetriesAsync(() => Database.KeyDeleteAsync(GetDequeuedTimeKey(entry.Id)), logger : _logger).AnyContext(); } else { _logger.LogInformation("Adding item back to queue for retry: {EntryId}", entry.Id); await Run.WithRetriesAsync(() => _cache.IncrementAsync(attemptsCacheKey, 1, GetAttemptsTtl()), logger : _logger).AnyContext(); var tx = Database.CreateTransaction(); tx.AddCondition(Condition.KeyExists(GetRenewedTimeKey(entry.Id))); tx.ListRemoveAsync(_workListName, entry.Id); tx.ListLeftPushAsync(_queueListName, entry.Id); tx.KeyDeleteAsync(GetRenewedTimeKey(entry.Id)); bool success = await Run.WithRetriesAsync(() => tx.ExecuteAsync(), logger : _logger).AnyContext(); if (!success) { throw new InvalidOperationException("Queue entry not in work list, it may have been auto abandoned."); } await Run.WithRetriesAsync(() => Task.WhenAll( Database.KeyDeleteAsync(GetDequeuedTimeKey(entry.Id)), // This should pulse the monitor. _subscriber.PublishAsync(GetTopicName(), entry.Id) ), logger : _logger).AnyContext(); } Interlocked.Increment(ref _abandonedCount); entry.MarkAbandoned(); await OnAbandonedAsync(entry).AnyContext(); _logger.LogInformation("Abandon complete: {EntryId}", entry.Id); }
public void AddCondition(Condition condition) { _conditions.Add(condition); }
private void DoValidation(Condition cond) { if (!context.ExpectingValue) { context.Count++; } if (!validate) { return; } if (has_reached_end) { throw new JsonException( "A complete JSON symbol has already been written"); } switch (cond) { case Condition.InArray: if (!context.InArray) { throw new JsonException( "Can't close an array here"); } break; case Condition.InObject: if (!context.InObject || context.ExpectingValue) { throw new JsonException( "Can't close an object here"); } break; case Condition.NotAProperty: if (context.InObject && !context.ExpectingValue) { throw new JsonException( "Expected a property"); } break; case Condition.Property: if (!context.InObject || context.ExpectingValue) { throw new JsonException( "Can't add a property here"); } break; case Condition.Value: if (!context.InArray && (!context.InObject || !context.ExpectingValue)) { throw new JsonException( "Can't add a value here"); } break; } }
public void clearSortCondition() { siftConditionArr = null; sortCondition = null; }
internal static TransportRulePredicate CreateFromInternalCondition(Condition condition) { return(SinglePropertyMatchesPredicate.CreateFromInternalCondition <SubjectMatchesPredicate>(condition, "Message.Subject")); }
public SqlServerHealthcareDeliveryContextWithLogging(string connectionString, ILoggerFactory loggerFactory) : base(connectionString) { Condition.Requires(loggerFactory, nameof(loggerFactory)).IsNotNull(); this.loggerFactory = loggerFactory; }
public override void Run(string dbname) { int contando = 0; foreach (String i in Column) { String[] o = i.Split('='); String dato1 = o[1]; if (dato1.Contains("'")) { o[1] = dato1.Trim('\''); } String nuevacolum = o[0] + "=" + o[1]; Column[contando] = nuevacolum; contando++; } if (Condition.Contains("'")) { String[] i = Condition.Split('='); i[1] = i[1].Trim('\''); Condition = i[0] + "=" + i[1]; } Boolean hayerror = false; //Error table not exits if (!File.Exists("..//..//..//data//" + dbname + "//" + Table + ".data")) { result = Constants.TableDoesNotExist; hayerror = true; } //Error column not exits if (hayerror == false) { String[] lineadef = System.IO.File.ReadAllLines("..//..//..//data//" + dbname + "//" + Table + ".def"); foreach (String lacol in Column) { String[] yasplit = lacol.Split('='); String buscar = yasplit[0]; if (lineadef[0].Contains(buscar) == false) { result = Constants.ColumnDoesNotExist; hayerror = true; } } } //Error data type incorrect if (hayerror == false) { String[] lineadef = System.IO.File.ReadAllLines("..//..//..//data//" + dbname + "//" + Table + ".def"); foreach (String parte in lineadef) { String[] lineadef2 = parte.Split(','); foreach (String parte2 in lineadef2) { String[] parte3 = parte2.Split(' '); foreach (String atributoigual in Column) { String[] atributo = atributoigual.Split('='); if (parte3[0] == atributo[0]) { String tipo = parte3[1].ToUpper(); //INT if (tipo == "INT") { try { int.Parse(atributo[1]); } catch { result = Constants.IncorrectDataType; hayerror = true; } } //DOUBLE if (tipo == "DOUBLE") { try { double.Parse(atributo[1]); } catch { result = Constants.IncorrectDataType; hayerror = true; } } } } } } } //Error primary key already exists if (hayerror == false) { String[] lineadef = System.IO.File.ReadAllLines("..//..//..//data//" + dbname + "//" + Table + ".def"); String[] atributos = lineadef[0].Split(','); int posPK = 0; String atribPK = ""; for (int i = 0; i < atributos.Length; i++) { if (atributos[i].Contains("true")) { posPK = i; String[] atrib = atributos[i].Split(' '); atribPK = atrib[0]; } } String cambio = ""; Boolean semodifica = false; foreach (String upda in Column) { String[] updaactual = upda.Split('='); String esultimo = updaactual[0] + ";"; if (updaactual[0] == atribPK) { cambio = updaactual[1]; semodifica = true; } else if (esultimo == atribPK) { cambio = updaactual[1]; semodifica = true; } } if (semodifica == true) { String[] lineas = System.IO.File.ReadAllLines("..//..//..//data//" + dbname + "//" + Table + ".data"); foreach (String lineactual in lineas) { String[] lineactualsplit = lineactual.Split(','); if (lineactualsplit[posPK] == cambio) { result = Constants.Error + "primary key already exists"; hayerror = true; } } } } //NO Error if (hayerror == false) { String[] elements = new String[2]; String operador = ""; int posicion = 0; //I need to know the operator of the condition if (Condition.Contains("=")) { elements = Condition.Split('='); operador = "="; } else if (Condition.Contains("<")) { elements = Condition.Split('<'); operador = "<"; } else if (Condition.Contains(">")) { elements = Condition.Split('>'); operador = ">"; } //I need a new line with the new dates of the row //String newRow = ""; //int longitud = Column.Length; //int cuenta = 1; //foreach (String colum in Column) //{ // if (cuenta!=longitud) // { // String[] actual = colum.Split('='); // newRow = newRow + actual[1] + ","; // } // else // { // String[] actual = colum.Split('='); // newRow = newRow + actual[1]; // } // cuenta++; //} //Open te file .def String allFile = System.IO.File.ReadAllText("..//..//..//data//" + dbname + "//" + Table + ".def"); String[] atrib = allFile.Split(','); //Search the postion of the atribute that appears in the condition String buscar = elements[0]; Boolean parar = false; foreach (String atributo in atrib) { if (!parar) { if (!atributo.Contains(buscar)) { posicion = posicion + 1; } else { parar = true; } } } //Open te file .data String[] lineas = System.IO.File.ReadAllLines("..//..//..//data//" + dbname + "//" + Table + ".data"); //[atr1/atr2] String[] lineadef = System.IO.File.ReadAllLines("..//..//..//data//" + dbname + "//" + Table + ".def"); String[] lineacoma = lineadef[0].Split(','); String[] atributos = new String[lineacoma.Length]; int cuantas = 0; foreach (string linea in lineacoma) { String[] lineaespacio = linea.Split(' '); atributos[cuantas] = lineaespacio[0]; cuantas = cuantas + 1; } //Make the update int inde = 0; foreach (String linea in lineas) { String[] datos = linea.Split(','); if (operador == "<") { int numero = Int32.Parse(datos[posicion]); if (numero < Int32.Parse(elements[1])) { foreach (String columna in Column) { String[] columnaSep = columna.Split('='); for (int i = 0; i < atributos.Length; i++) { if (columnaSep[0] == atributos[i]) { datos[i] = columnaSep[1]; } } } String newRow = ""; for (int i = 0; i < datos.Length; i++) { if (i != (datos.Length - 1)) { newRow = newRow + datos[i] + ","; } else { newRow = newRow + datos[i]; } } lineas.SetValue(newRow, inde); } inde++; } else if (operador == ">") { int numero = Int32.Parse(datos[posicion]); if (numero > Int32.Parse(elements[1])) { foreach (String columna in Column) { String[] columnaSep = columna.Split('='); for (int i = 0; i < atributos.Length; i++) { if (columnaSep[0] == atributos[i]) { datos[i] = columnaSep[1]; } } } String newRow = ""; for (int i = 0; i < datos.Length; i++) { if (i != (datos.Length - 1)) { newRow = newRow + datos[i] + ","; } else { newRow = newRow + datos[i]; } } lineas.SetValue(newRow, inde); } inde++; } else if (operador == "=") { if (datos[posicion] == elements[1]) { foreach (String columna in Column) { String[] columnaSep = columna.Split('='); for (int i = 0; i < atributos.Length; i++) { if (columnaSep[0] == atributos[i]) { datos[i] = columnaSep[1]; } } } String newRow = ""; for (int i = 0; i < datos.Length; i++) { if (i != (datos.Length - 1)) { newRow = newRow + datos[i] + ","; } else { newRow = newRow + datos[i]; } } lineas.SetValue(newRow, inde); } inde++; } } //Make changes on the file using (StreamWriter sw = System.IO.File.CreateText("..//..//..//data//" + dbname + "//" + Table + ".data")) foreach (String linea in lineas) { sw.WriteLine(linea); } result = Constants.TupleUpdateSuccess; } }
public bool Execute(params object[] Params) { Habbo Player = (Habbo)Params[0]; if (Player == null || Player.CurrentRoom == null || !Player.InRoom) { return(false); } RoomUser User = Player.CurrentRoom.GetRoomUserManager().GetRoomUserByHabbo(Player.Username); if (User == null) { return(false); } string Message = Convert.ToString(Params[1]); if ((BoolData && Instance.OwnerId != Player.Id) || Player == null || string.IsNullOrWhiteSpace(Message) || string.IsNullOrWhiteSpace(this.StringData)) { return(false); } if (Message.Contains(" " + this.StringData) || Message.Contains(this.StringData + " ") || Message == this.StringData) { Player.WiredInteraction = true; ICollection <IWiredItem> Effects = Instance.GetWired().GetEffects(this); ICollection <IWiredItem> Conditions = Instance.GetWired().GetConditions(this); foreach (IWiredItem Condition in Conditions.ToList()) { if (!Condition.Execute(Player)) { return(false); } Instance.GetWired().OnEvent(Condition.Item); } Player.GetClient().SendMessage(new WhisperComposer(User.VirtualId, Message, 0, 0)); //Check the ICollection to find the random addon effect. bool HasRandomEffectAddon = Effects.Where(x => x.Type == WiredBoxType.AddonRandomEffect).ToList().Count() > 0; if (HasRandomEffectAddon) { //Okay, so we have a random addon effect, now lets get the IWiredItem and attempt to execute it. IWiredItem RandomBox = Effects.FirstOrDefault(x => x.Type == WiredBoxType.AddonRandomEffect); if (!RandomBox.Execute()) { return(false); } //Success! Let's get our selected box and continue. IWiredItem SelectedBox = Instance.GetWired().GetRandomEffect(Effects.ToList()); if (!SelectedBox.Execute()) { return(false); } //Woo! Almost there captain, now lets broadcast the update to the room instance. if (Instance != null) { Instance.GetWired().OnEvent(RandomBox.Item); Instance.GetWired().OnEvent(SelectedBox.Item); } } else { foreach (IWiredItem Effect in Effects.ToList()) { if (!Effect.Execute(Player)) { return(false); } Instance.GetWired().OnEvent(Effect.Item); } } return(true); } return(false); }
/// <summary> /// The execute. /// </summary> /// <param name="arg"> /// The pipeline argument. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// The <see cref="PipelineArgument"/>. /// </returns> public override Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context) { Condition.Requires(arg).IsNotNull($"{Name}: The argument cannot be null."); var productFeatureActionPolicy = context.GetPolicy <ProductFeaturesActionsPolicy>(); // Only proceed if the right action was invoked if (string.IsNullOrEmpty(arg.Action) || !arg.Action.Equals(productFeatureActionPolicy.ProductFeatures, StringComparison.OrdinalIgnoreCase)) { return(Task.FromResult(arg)); } // Get the sellable item from the context var entity = context.CommerceContext.GetObject <Sitecore.Commerce.Plugin.Catalog.SellableItem>(x => x.Id.Equals(arg.EntityId)); if (entity == null) { return(Task.FromResult(arg)); } ProductFeatures component = null; // Get the notes component from the sellable item or its variation if (!string.IsNullOrWhiteSpace(arg.ItemId)) { component = entity.GetVariation(arg.ItemId).GetComponent <ProductFeatures>(); } else { component = entity.GetComponent <ProductFeatures>(); } component.Feature_Bullets_1 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_1), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_2 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_2), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_3 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_3), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_4 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_4), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_5 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_5), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_6 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_6), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_7 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_7), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_8 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_8), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_9 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_9), StringComparison.OrdinalIgnoreCase))?.Value; component.Feature_Bullets_10 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Feature_Bullets_10), StringComparison.OrdinalIgnoreCase))?.Value; component.Marketing_Claims_1 = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Marketing_Claims_1), StringComparison.OrdinalIgnoreCase))?.Value; component.Fitting_Features = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Fitting_Features), StringComparison.OrdinalIgnoreCase))?.Value; component.Mirror_Bath_Product_Type = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Mirror_Bath_Product_Type), StringComparison.OrdinalIgnoreCase))?.Value; component.Mirror_Beveled_Frame_YN = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Mirror_Beveled_Frame_YN), StringComparison.OrdinalIgnoreCase))?.Value; component.Mirror_Frame_Finish_Family = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Mirror_Frame_Finish_Family), StringComparison.OrdinalIgnoreCase))?.Value; component.Mirror_Beveled_Frame_YN = arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(ProductFeatures.Mirror_Beveled_Frame_YN), StringComparison.OrdinalIgnoreCase))?.Value; context.Logger.LogInformation("Current Entity Version : " + entity.Version); // Persist changes this.Commander.Pipeline <IPersistEntityPipeline>().Run(new PersistEntityArgument(entity), context); return(Task.FromResult(arg)); }
/// <inheritdoc /> public override void CopyTo(ExecutionMessage destination) { base.CopyTo(destination); destination.Balance = Balance; destination.Comment = Comment; destination.Condition = Condition?.Clone(); destination.ClientCode = ClientCode; destination.BrokerCode = BrokerCode; destination.Currency = Currency; destination.ServerTime = ServerTime; destination.DepoName = DepoName; destination.Error = Error; destination.ExpiryDate = ExpiryDate; destination.IsSystem = IsSystem; destination.OpenInterest = OpenInterest; destination.OrderId = OrderId; destination.OrderStringId = OrderStringId; destination.OrderBoardId = OrderBoardId; destination.ExecutionType = ExecutionType; destination.IsCancellation = IsCancellation; //destination.Action = Action; destination.OrderState = OrderState; destination.OrderStatus = OrderStatus; destination.OrderType = OrderType; destination.OriginSide = OriginSide; destination.PortfolioName = PortfolioName; destination.OrderPrice = OrderPrice; destination.SecurityId = SecurityId; destination.Side = Side; destination.SystemComment = SystemComment; destination.TimeInForce = TimeInForce; destination.TradeId = TradeId; destination.TradeStringId = TradeStringId; destination.TradePrice = TradePrice; destination.TradeStatus = TradeStatus; destination.TransactionId = TransactionId; destination.OrderVolume = OrderVolume; destination.TradeVolume = TradeVolume; //destination.IsFinished = IsFinished; destination.VisibleVolume = VisibleVolume; destination.IsUpTick = IsUpTick; destination.Commission = Commission; destination.Latency = Latency; destination.Slippage = Slippage; destination.UserOrderId = UserOrderId; //destination.DerivedOrderId = DerivedOrderId; //destination.DerivedOrderStringId = DerivedOrderStringId; destination.PnL = PnL; destination.Position = Position; destination.HasTradeInfo = HasTradeInfo; destination.HasOrderInfo = HasOrderInfo; destination.IsMarketMaker = IsMarketMaker; destination.IsMargin = IsMargin; destination.IsManual = IsManual; destination.CommissionCurrency = CommissionCurrency; destination.AveragePrice = AveragePrice; destination.Yield = Yield; destination.MinVolume = MinVolume; destination.PositionEffect = PositionEffect; destination.PostOnly = PostOnly; destination.Initiator = Initiator; }
public virtual bool Matches(string prefix, string p) { Condition.Requires(prefix, "prefix").IsNotNull(); Condition.Requires(p, "p").IsNotNull(); return(Hash(prefix + ":" + p) == HashedPassword); }
public override string ToString() { return("ANY_N_CELL (" + Condition.ToString() + ")"); }
public bool OnCycle() { bool Success = false; ICollection <RoomUser> Avatars = Instance.GetRoomUserManager().GetRoomUsers().ToList(); ICollection <IWiredItem> Effects = Instance.GetWired().GetEffects(this); ICollection <IWiredItem> Conditions = Instance.GetWired().GetConditions(this); foreach (IWiredItem Condition in Conditions.ToList()) { foreach (RoomUser Avatar in Avatars.ToList()) { if (Avatar == null || Avatar.GetClient() == null || Avatar.GetClient().GetHabbo() == null) { continue; } if (!Condition.Execute(Avatar.GetClient().GetHabbo())) { continue; } Success = true; } if (!Success) { return(false); } Success = false; Instance.GetWired().OnEvent(Condition.Item); } Success = false; //Check the ICollection to find the random addon effect. bool HasRandomEffectAddon = Effects.Count(x => x.Type == WiredBoxType.AddonRandomEffect) > 0; if (HasRandomEffectAddon) { //Okay, so we have a random addon effect, now lets get the IWiredItem and attempt to execute it. IWiredItem RandomBox = Effects.FirstOrDefault(x => x.Type == WiredBoxType.AddonRandomEffect); if (!RandomBox.Execute()) { return(false); } //Success! Let's get our selected box and continue. IWiredItem SelectedBox = Instance.GetWired().GetRandomEffect(Effects.ToList()); if (!SelectedBox.Execute()) { return(false); } //Woo! Almost there captain, now lets broadcast the update to the room instance. if (Instance != null) { Instance.GetWired().OnEvent(RandomBox.Item); Instance.GetWired().OnEvent(SelectedBox.Item); } } else { foreach (IWiredItem Effect in Effects.ToList()) { if (!Effect.Execute()) { continue; } Success = true; if (!Success) { return(false); } if (Instance != null) { Instance.GetWired().OnEvent(Effect.Item); } } } TickCount = Delay; return(true); }
public override void EnterRule_item_condition(CfgGramParser.Rule_item_conditionContext context) { Condition = new Condition(); ConditionValues = new List <string>(); }
void OnMessage(TimestampedMsg <WebSocket.IMessageIn> msg) { Condition.Requires(msg, "msg").IsNotNull(); Condition.Requires(msg.Value, "msg.Value").IsNotNull(); Condition.Requires(msg.Value.ProductId, "msg.Value.ProductId").IsNotNullOrEmpty(); Condition.Requires(_products.ContainsKey(msg.Value.ProductId)); bool myFill = _orderManager.OnMessage(msg); OrderBookBuilder book = _products[msg.Value.ProductId]; OrderBookDelta delta = null; Trade trade = null; bool ok = false; try { ok = book.OnOrderUpdate(msg.Value, out delta, out trade); } catch (Exception e) { _log.Error(e, "Unable to process order update"); } if (ok) { if (!myFill && trade != null && trade.Size > 0m) { try { OnTrade?.Invoke( msg.Value.ProductId, new TimestampedMsg <Trade>() { Received = msg.Received, Value = trade }); } catch (Exception e) { _log.Warn(e, "Ignoring exception from OnTrade"); } } if (delta != null && (delta.Bids.Any() || delta.Asks.Any())) { try { OnOrderBook?.Invoke( msg.Value.ProductId, new TimestampedMsg <OrderBookDelta>() { Received = msg.Received, Value = delta }); } catch (Exception e) { _log.Warn(e, "Ignoring exception from OnOrderBook"); } } } else { RefreshOrderBook(msg.Value.ProductId, book); } }
protected override async Task <IReadOnlyCollection <object> > QueryAsync <T>(string pk) { return(await _context.Query <T>() .WithKeyExpression(Condition <T> .On(x => x.Pk).EqualTo("test")) .ToListAsync().ConfigureAwait(false)); }
public void CursorOnContextMenuItem(MenuButton sender) { switch (_setLabelSteps) { case SetLabelSteps.ChoiceLabelType: { _activeLabelType = _labelTypeMenuButtons[sender]; _setLabelSteps = SetLabelSteps.SetValue; _contextMenu.ClearContextMenu(); if (_activeLabelType == ActiveLabelType.Variable) { SetLabelVariableMenuItems(); } else if (_activeLabelType == ActiveLabelType.Expression) { if (_setLabelTarget.ValueType == ValueType.Bool) { _setLabelTarget.Value = new LogicExpression(); } else { _setLabelTarget.Value = new Expression(); } if (_setLabelTarget.Value.Parent == null) { _setLabelValueUi.Value = _setLabelTarget.Value; } _setLabelValueUi.RebuildAnValue(); _contextMenu.gameObject.SetActive(false); _setLabelSteps = SetLabelSteps.SetTarget; } else if (_activeLabelType == ActiveLabelType.Constant) { _mainController.SetValueFromDialog(_setLabelValueUi, _setLabelTarget.Value); _contextMenu.gameObject.SetActive(false); _setLabelSteps = SetLabelSteps.SetTarget; } else if (_activeLabelType == ActiveLabelType.Operation) { if (_setLabelTarget.LabelType == ActiveLabelType.Condition) { SetRelationMenuItems(); } else { if (_setLabelTarget.ValueType == ValueType.Bool) { SetLogicOperationMenuItems(); } else { SetNumberOperationMenuItems(); } } _setLabelSteps = SetLabelSteps.SetValue; } else if (_activeLabelType == ActiveLabelType.Condition) { _setLabelTarget.Value = new Condition(); if (_setLabelTarget.Value.Parent == null) { _setLabelValueUi.Value = _setLabelTarget.Value; } _setLabelValueUi.RebuildAnValue(); _contextMenu.gameObject.SetActive(false); _setLabelSteps = SetLabelSteps.SetTarget; } } break; case SetLabelSteps.SetValue: { if (_activeLabelType == ActiveLabelType.Operation) { if (_setLabelTarget.LabelType == ActiveLabelType.Condition) { Condition condition = _setLabelTarget.Value as Condition; condition.Relation = _relationMenuButtons[sender]; } else { if (_setLabelTarget.ValueType == ValueType.Bool) { LogicExpression logicExpression = _setLabelTarget.Value as LogicExpression; logicExpression.Operation = _logicOperationMenuButtons[sender]; } else { Expression numberExpression = _setLabelTarget.Value as Expression; numberExpression.Operation = _numberOperationMenuButtons[sender]; } } _setLabelValueUi.RebuildAnValue(); } else if (_activeLabelType == ActiveLabelType.Variable) { if (_isSetedLabelVariable) { _setLabelTarget.Value = _labelVariableMenuButtons[sender]; _setVariableBlock.SetBlock.Variable = _labelVariableMenuButtons[sender]; _setVariableBlock.RefreshParameter(); } else { _setLabelTarget.Value = _labelVariableMenuButtons[sender]; if (_setLabelTarget.Value.Parent == null) { _setLabelValueUi.Value = _setLabelTarget.Value; } _setLabelValueUi.RebuildAnValue(); } } _contextMenu.gameObject.SetActive(false); _setLabelSteps = SetLabelSteps.SetTarget; } break; } }
public static Condition NotParent(Condition condition) { var parents = Parent(condition); return(new NotCondition(parents)); }
private static Condition CreateSecondChildCondition() { return(Condition.Create(e => MatchOrderInSiblings(e, 2))); }
public static Condition NoAncestor(Condition c) { return(~AnyAncestor(c)); }
public static Condition NoDescendant(Condition c) { return(~AnyDescendant(c)); }
public EventNotificationService(IConfiguration configuration) { Condition.Requires(configuration, nameof(configuration)).IsNotNull(); this.BindPropertiesFromOptions(configuration.As <EventNotificationServiceOptions>()); }
private static Condition CreateSiblingsOfSameTypeCondition() { return(Condition.Create(HasSiblingsOfSameType)); }
public bool manages(Condition c) { return(c.GetType() == condition.GetType()); }
public static Condition AnyAncestor(Condition c) { return(AnyAncestor(c, Condition.False)); }