private TestResult(string methodName, Outcome outcome, string message = "", Exception exception = null) { MethodName = methodName; Result = outcome; Message = message; Exception = exception; }
/// <summary> /// Method that will keep track of number of rounds and wins. /// </summary> /// <param name="result"></param> public void outcomeOfRound(Outcome result) { rounds++; if (result == Outcome.Win) { wins = wins + 1; } }
private Outcome CreateSuccessfulOutcome() { Outcome o = new Outcome(OutcomeResult.Passed, "cool"); Outcome[] oArr = new Outcome[1]; oArr[0] = o; o.AddOutcomes(oArr); return o; }
/// <summary> /// Tells the Player whether they won or lost. /// </summary> /// <param name="result">The result of the round.</param> public void outcomeOfRound(Outcome result) { rounds++; if (result == Outcome.Win) { wins++; } cardCounter = 0; }
private void AddResult(string team1, string team2, Outcome outcome) { // Invert outcome for the second team. Outcome outcome2 = outcome == Outcome.WIN ? Outcome.LOSS : outcome == Outcome.LOSS ? Outcome.WIN : Outcome.DRAW; AddTeamOutcome(team1, outcome); AddTeamOutcome(team2, outcome2); }
public ActionResult Edit(Outcome outcome) { if (ModelState.IsValid) { _context.Entry(outcome).State = EntityState.Modified; _context.SaveChanges(); return RedirectToAction("Index"); } return View(outcome); }
private void AddTeamOutcome(string team, Outcome outcome) { TeamResult teamResult; if (this.teams.TryGetValue(team, out teamResult)) { teamResult.AddOutcome(outcome); } else { teamResult = new TeamResult(); teamResult.AddOutcome(outcome); this.teams.Add(team, teamResult); } }
public ActionResult Create(Outcome outcome) { if (ModelState.IsValid) { _context.Outcomes.Add(outcome); _context.SaveChanges(); return RedirectToAction("Index"); } return View(outcome); }
public ActionResult Delete(Guid id, Outcome outcome) { var outcomeToDelete = RepositoryFactory.OutcomeRepository.GetNullableById(id); if (outcomeToDelete == null) return RedirectToAction("Index"); RepositoryFactory.OutcomeRepository.Remove(outcomeToDelete); Message = "Outcome Removed Successfully"; return RedirectToAction("Index"); }
public void LoadLevel() { proposedOutcome = finalOutcome; while (proposedOutcome == finalOutcome) { finalOutcome = possibleOutcomes[Random.Range(0, possibleOutcomes.Length)].GetComponent<Outcome>(); } foreach (var item in proposedOutcome.Item) { item.GetComponent<Button>().onClick.Invoke(); } }
internal Outcome GetNewScenarioOutcome(Outcome scenarioOutcome, Outcome stepOutcome, bool scenarioSkipped) { Outcome newOutcome = scenarioOutcome; switch (stepOutcome) { case Outcome.NotRun: break; case Outcome.Skipped: switch (scenarioOutcome) { case Outcome.NotRun: if(scenarioSkipped) newOutcome = Outcome.Skipped; else newOutcome = Outcome.Failed; break; case Outcome.Passed: if(scenarioSkipped) newOutcome = Outcome.Skipped; else newOutcome = Outcome.Failed; break; } break; case Outcome.Failed: switch (scenarioOutcome) { case Outcome.NotRun: newOutcome = Outcome.Failed; break; case Outcome.Skipped: newOutcome = Outcome.Failed; break; case Outcome.Passed: newOutcome = Outcome.Failed; break; } break; case Outcome.Passed: switch (scenarioOutcome) { case Outcome.NotRun: newOutcome = Outcome.Passed; break; } break; } return newOutcome; }
internal Outcome GetNewParentOutcome(Outcome currentParentOutcome, Outcome childOutcome) { Outcome newOutcome = currentParentOutcome; switch (childOutcome) { case Outcome.NotRun: break; case Outcome.Skipped: switch (currentParentOutcome) { case Outcome.NotRun: newOutcome = Outcome.Skipped; break; case Outcome.Passed: newOutcome = Outcome.Skipped; break; } break; case Outcome.Failed: switch (currentParentOutcome) { case Outcome.NotRun: newOutcome = Outcome.Failed; break; case Outcome.Skipped: newOutcome = Outcome.Failed; break; case Outcome.Passed: newOutcome = Outcome.Failed; break; } break; case Outcome.Passed: switch (currentParentOutcome) { case Outcome.NotRun: newOutcome = Outcome.Passed; break; } break; } return newOutcome; }
public static List<string> GetBestOutcomeFromHand(List<string> listCardsIn, out Outcome outcome) { //check for Royal Flush //.. //check for 1 Pair // check for same first digit var firstDigitList = new List<string>(); foreach (string card in listCardsIn) { string firstDigit = card[0].ToString(); firstDigitList.Add(firstDigit); } // get any cards with > 1 in string firstDigitPair = firstDigitList.Count(x => x > 1); var listWinningCards = new List<string>(); listWinningCards.Add("5H"); listWinningCards.Add("5C"); outcome = Outcome.OnePair; return listWinningCards; }
private string OutputString(Outcome outcome) { switch (outcome) { case Outcome.Low: return "För lågt"; case Outcome.High: return "för högt"; case Outcome.Correct: return "Grattis du klarade det på: "; case Outcome.NoMoreGuesses: return "Misslyckat! Du har haft dina: "; case Outcome.PreviousGuess: return "Du har redan gissat på det här nummret. Prova igen"; default: return "Obefintligt"; } }
public ActionResult Create(OutcomeViewModel model) { var outcomeToCreate = new Outcome {Name = model.Name, Description = model.Description}; var outcomeImage = _fileService.Save(model.File, publicAccess: true); outcomeToCreate.ImageUrl = outcomeImage.Uri.AbsoluteUri; if (ModelState.IsValid) { RepositoryFactory.OutcomeRepository.EnsurePersistent(outcomeToCreate); Message = "Outcome Created Successfully"; return RedirectToAction("Index"); } else { var viewModel = OutcomeViewModel.Create(Repository); viewModel.Name = model.Name; viewModel.Description = model.Description; return View(viewModel); } }
public override Task BuildAsync() { if (!Outcome.HasFlag(UserSetting.Outcome.Task)) { Outcome = UserSetting.Outcome.NotSet; return(Task.CompletedTask); } if (_settings.Any(setting => setting.Key == UserSetting.SettingID.WheelTaskPreference)) { var preference = (UserSetting.WheelTaskPreferenceSetting) int.Parse(_settings.First(setting => setting.Key == UserSetting.SettingID.WheelTaskPreference).Value.Value); if (preference.HasFlag(UserSetting.WheelTaskPreferenceSetting.Task)) { this.Chance *= 6; } } DiscordEmbedBuilder builder = new DiscordEmbedBuilder(); int time = Helpers.RandomGenerator.RandomInt(this.minBanTime, this.maxBanTime); if (Helpers.RandomGenerator.RandomInt(0, 2) == 0) { builder.Title = "Content ban!"; builder.Description = $"You are banned from {bans[Helpers.RandomGenerator.RandomInt(0, bans.Length)]} for {time} days! If you already had the same ban, consider it reset."; builder.Footer = new DiscordEmbedBuilder.EmbedFooter() { Text = "Now reroll!" }; } else { int edgeAmount = Helpers.RandomGenerator.RandomInt(this.minEdgeAmount, this.maxEdgeAmount) * 2; UserSetting.WheelDifficultyPreference difficulty = UserSetting.WheelDifficultyPreference.Default; if (_settings.ContainsKey(UserSetting.SettingID.WheelDifficulty)) { difficulty = _settings.First(setting => setting.Key == UserSetting.SettingID.WheelDifficulty).Value.GetValue <UserSetting.WheelDifficultyPreference>(); } switch (difficulty) { case UserSetting.WheelDifficultyPreference.Baby: edgeAmount /= 4; break; case UserSetting.WheelDifficultyPreference.Easy: edgeAmount /= 2; break; case UserSetting.WheelDifficultyPreference.Hard: edgeAmount *= 2; break; case UserSetting.WheelDifficultyPreference.Masterbater: edgeAmount *= 4; break; } builder.Title = "Edging Task!"; builder.Description = $"You'll have to Edge {edgeAmount} times a Day, for {time} days! If you already had the same task, consider it reset."; builder.Footer = new DiscordEmbedBuilder.EmbedFooter() { Text = "Now reroll!" }; } this.Embed = builder.Build(); this.Outcome = UserSetting.Outcome.Task; return(Task.CompletedTask); }
public Task <Outcome> DisposeMessageAsync(ArraySegment <byte> deliveryTag, Outcome outcome, bool batchable, TimeSpan timeout) { return(this.DisposeMessageAsync(deliveryTag, AmqpConstants.NullBinary, outcome, batchable, timeout)); }
public IAsyncResult BeginDisposeMessage(ArraySegment <byte> deliveryTag, Outcome outcome, bool batchable, TimeSpan timeout, AsyncCallback callback, object state) { return(this.BeginDisposeMessage(deliveryTag, AmqpConstants.NullBinary, outcome, batchable, timeout, callback, state)); }
/// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } if (!string.IsNullOrEmpty(ResourceType)) { writer.WriteString("resourceType", (string)ResourceType !); } ((Fhir.R4.Models.DomainResource) this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(Url)) { writer.WriteString("url", (string)Url !); } if (_Url != null) { writer.WritePropertyName("_url"); _Url.SerializeJson(writer, options); } if ((Identifier != null) && (Identifier.Count != 0)) { writer.WritePropertyName("identifier"); writer.WriteStartArray(); foreach (Identifier valIdentifier in Identifier) { valIdentifier.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (!string.IsNullOrEmpty(Version)) { writer.WriteString("version", (string)Version !); } if (_Version != null) { writer.WritePropertyName("_version"); _Version.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Name)) { writer.WriteString("name", (string)Name !); } if (_Name != null) { writer.WritePropertyName("_name"); _Name.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Title)) { writer.WriteString("title", (string)Title !); } if (_Title != null) { writer.WritePropertyName("_title"); _Title.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(ShortTitle)) { writer.WriteString("shortTitle", (string)ShortTitle !); } if (_ShortTitle != null) { writer.WritePropertyName("_shortTitle"); _ShortTitle.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Subtitle)) { writer.WriteString("subtitle", (string)Subtitle !); } if (_Subtitle != null) { writer.WritePropertyName("_subtitle"); _Subtitle.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Status)) { writer.WriteString("status", (string)Status !); } if (_Status != null) { writer.WritePropertyName("_status"); _Status.SerializeJson(writer, options); } if (Experimental != null) { writer.WriteBoolean("experimental", (bool)Experimental !); } if (SubjectCodeableConcept != null) { writer.WritePropertyName("subjectCodeableConcept"); SubjectCodeableConcept.SerializeJson(writer, options); } if (SubjectReference != null) { writer.WritePropertyName("subjectReference"); SubjectReference.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Date)) { writer.WriteString("date", (string)Date !); } if (_Date != null) { writer.WritePropertyName("_date"); _Date.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Publisher)) { writer.WriteString("publisher", (string)Publisher !); } if (_Publisher != null) { writer.WritePropertyName("_publisher"); _Publisher.SerializeJson(writer, options); } if ((Contact != null) && (Contact.Count != 0)) { writer.WritePropertyName("contact"); writer.WriteStartArray(); foreach (ContactDetail valContact in Contact) { valContact.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (!string.IsNullOrEmpty(Description)) { writer.WriteString("description", (string)Description !); } if (_Description != null) { writer.WritePropertyName("_description"); _Description.SerializeJson(writer, options); } if ((Comment != null) && (Comment.Count != 0)) { writer.WritePropertyName("comment"); writer.WriteStartArray(); foreach (string valComment in Comment) { writer.WriteStringValue(valComment); } writer.WriteEndArray(); } if ((_Comment != null) && (_Comment.Count != 0)) { writer.WritePropertyName("_comment"); writer.WriteStartArray(); foreach (Element val_Comment in _Comment) { val_Comment.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((UseContext != null) && (UseContext.Count != 0)) { writer.WritePropertyName("useContext"); writer.WriteStartArray(); foreach (UsageContext valUseContext in UseContext) { valUseContext.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Jurisdiction != null) && (Jurisdiction.Count != 0)) { writer.WritePropertyName("jurisdiction"); writer.WriteStartArray(); foreach (CodeableConcept valJurisdiction in Jurisdiction) { valJurisdiction.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (!string.IsNullOrEmpty(Purpose)) { writer.WriteString("purpose", (string)Purpose !); } if (_Purpose != null) { writer.WritePropertyName("_purpose"); _Purpose.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Usage)) { writer.WriteString("usage", (string)Usage !); } if (_Usage != null) { writer.WritePropertyName("_usage"); _Usage.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Copyright)) { writer.WriteString("copyright", (string)Copyright !); } if (_Copyright != null) { writer.WritePropertyName("_copyright"); _Copyright.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(ApprovalDate)) { writer.WriteString("approvalDate", (string)ApprovalDate !); } if (_ApprovalDate != null) { writer.WritePropertyName("_approvalDate"); _ApprovalDate.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(LastReviewDate)) { writer.WriteString("lastReviewDate", (string)LastReviewDate !); } if (_LastReviewDate != null) { writer.WritePropertyName("_lastReviewDate"); _LastReviewDate.SerializeJson(writer, options); } if (EffectivePeriod != null) { writer.WritePropertyName("effectivePeriod"); EffectivePeriod.SerializeJson(writer, options); } if ((Topic != null) && (Topic.Count != 0)) { writer.WritePropertyName("topic"); writer.WriteStartArray(); foreach (CodeableConcept valTopic in Topic) { valTopic.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Author != null) && (Author.Count != 0)) { writer.WritePropertyName("author"); writer.WriteStartArray(); foreach (ContactDetail valAuthor in Author) { valAuthor.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Editor != null) && (Editor.Count != 0)) { writer.WritePropertyName("editor"); writer.WriteStartArray(); foreach (ContactDetail valEditor in Editor) { valEditor.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Reviewer != null) && (Reviewer.Count != 0)) { writer.WritePropertyName("reviewer"); writer.WriteStartArray(); foreach (ContactDetail valReviewer in Reviewer) { valReviewer.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Endorser != null) && (Endorser.Count != 0)) { writer.WritePropertyName("endorser"); writer.WriteStartArray(); foreach (ContactDetail valEndorser in Endorser) { valEndorser.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((RelatedArtifact != null) && (RelatedArtifact.Count != 0)) { writer.WritePropertyName("relatedArtifact"); writer.WriteStartArray(); foreach (RelatedArtifact valRelatedArtifact in RelatedArtifact) { valRelatedArtifact.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Library != null) && (Library.Count != 0)) { writer.WritePropertyName("library"); writer.WriteStartArray(); foreach (string valLibrary in Library) { writer.WriteStringValue(valLibrary); } writer.WriteEndArray(); } if ((_Library != null) && (_Library.Count != 0)) { writer.WritePropertyName("_library"); writer.WriteStartArray(); foreach (Element val_Library in _Library) { val_Library.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (Population != null) { writer.WritePropertyName("population"); Population.SerializeJson(writer, options); } if (Exposure != null) { writer.WritePropertyName("exposure"); Exposure.SerializeJson(writer, options); } if (ExposureAlternative != null) { writer.WritePropertyName("exposureAlternative"); ExposureAlternative.SerializeJson(writer, options); } if (Outcome != null) { writer.WritePropertyName("outcome"); Outcome.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } }
/// <summary> /// Send a cloud-to-device message to the specified module. /// </summary> /// <param name="deviceId">The device identifier for the target device.</param> /// <param name="moduleId">The module identifier for the target module.</param> /// <param name="message">The cloud-to-module message.</param> /// <param name="timeout">The operation timeout, which defaults to 1 minute if unspecified.</param> public virtual async Task SendAsync(string deviceId, string moduleId, Message message, TimeSpan?timeout = null) { Logging.Enter(this, $"Sending message with Id [{message?.MessageId}] for device {deviceId}, module {moduleId}", nameof(SendAsync)); if (string.IsNullOrWhiteSpace(deviceId)) { throw new ArgumentNullException(nameof(deviceId)); } if (string.IsNullOrWhiteSpace(moduleId)) { throw new ArgumentNullException(nameof(moduleId)); } if (message == null) { throw new ArgumentNullException(nameof(message)); } if (_clientOptions?.SdkAssignsMessageId == SdkAssignsMessageId.WhenUnset && message.MessageId == null) { message.MessageId = Guid.NewGuid().ToString(); } if (message.IsBodyCalled) { message.ResetBody(); } timeout ??= _operationTimeout; using AmqpMessage amqpMessage = MessageConverter.MessageToAmqpMessage(message); amqpMessage.Properties.To = "/devices/" + WebUtility.UrlEncode(deviceId) + "/modules/" + WebUtility.UrlEncode(moduleId) + "/messages/deviceBound"; try { SendingAmqpLink sendingLink = await GetSendingLinkAsync().ConfigureAwait(false); Outcome outcome = await sendingLink .SendMessageAsync( amqpMessage, IotHubConnection.GetNextDeliveryTag(ref _sendingDeliveryTag), AmqpConstants.NullBinary, timeout.Value) .ConfigureAwait(false); Logging.Info(this, $"Outcome was: {outcome?.DescriptorName}", nameof(SendAsync)); if (outcome.DescriptorCode != Accepted.Code) { throw AmqpErrorMapper.GetExceptionFromOutcome(outcome); } } catch (Exception ex) when(!ex.IsFatal()) { Logging.Error(this, $"{nameof(SendAsync)} threw an exception: {ex}", nameof(SendAsync)); throw AmqpClientHelper.ToIotHubClientContract(ex); } finally { Logging.Exit(this, $"Sending message with Id [{message?.MessageId}] for device {deviceId}, module {moduleId}", nameof(SendAsync)); } }
private async Task <string> RaiseOutcomeAsync(ExecutionThread executionThread, ITXID sourceTXID, Outcome outcome) { var executingComponent = executionThread.ExecutingComponents.FirstOrDefault( e => e.ExecutingID == sourceTXID.xid ); var parentExecutingComponent = executionThread.ExecutingComponents.FirstOrDefault( e => e.ExecutingID == executingComponent.ParentExecutingID ); executionThread.ComponentExecutingID = parentExecutingComponent.ExecutingID; executionThread.ExecutingComponentTitle = parentExecutingComponent.Title; executionThread.ExecutionStatus = (int)LogicalUnitStatusEnum.Started; // TODO: Strictly necessary here? outcome.SourceExecutionID = sourceTXID.xid; outcome.TargetExecutionID = executingComponent.ParentExecutingID; executionThread.PendingOutcomeJson = JsonConvert.SerializeObject(outcome); //executionThread.PendingOutcomeJson = CoreFunctions.ProxyAsJson(outcome); await AppExecutionApiClient.SaveExecutionThreadAsync(executionThread); return(parentExecutingComponent.URL); }
public void RegisterJoin(NodeController joinNode) { if (joinNode != previouslySelectedNode && joinNode != null) { object outcomeData; Outcome outcome = edgeCreator.AttemptModification(joinNode, out outcomeData); switch (outcome) { case Outcome.CreatedEdgeAndFaces: object[] edgeAndFaces = (object[])outcomeData; EdgeController createdEdge = (EdgeController)edgeAndFaces[0]; List <NodeController[]> createdFaces = (List <NodeController[]>)edgeAndFaces[1]; createdEdge.nodes .ForEach(n => n.OnCreateEdge()); createdFaces .SelectMany(face => face) .ToList() .ForEach(node => node.OnCreateFace()); var distinctEdges = graphLogicManager.DistinctEdgesInTriangles(createdFaces).ToList(); distinctEdges.ForEach(e => e.SetEdgeState(EdgeState.Face)); break; case Outcome.CreatedEdge: EdgeController newEdge = (EdgeController)outcomeData; joinNode.OnCreateEdge(); previouslySelectedNode.OnCreateEdge(); newEdge.SetEdgeState(EdgeState.NoFace); break; case Outcome.RemovedEdgeAndFaces: object[] removedEdgesAndFaces = (object[])outcomeData; EdgeController removedEdge = (EdgeController)removedEdgesAndFaces[0]; List <NodeController[]> removedFaces = (List <NodeController[]>)removedEdgesAndFaces[1]; removedFaces .SelectMany(face => face) .ToList() .ForEach(node => node.OnRemoveFace()); removedEdge.nodes .ForEach(n => n.OnRemoveEdge()); IEnumerable <EdgeController> edgesToUpdate = graphLogicManager.DistinctEdgesInTriangles(removedFaces); graphLogicManager.UpdateEdgeStates(edgesToUpdate); break; case Outcome.RemovedEdge: joinNode.OnRemoveEdge(); previouslySelectedNode.OnRemoveEdge(); break; case Outcome.IntersectingFace: case Outcome.IntersectingEdge: feedback.FeedbackIntersectingFace(); break; case Outcome.InvalidNodePair: feedback.FeedbackInvalidPair(); break; } } RegisterDeSelect(); edgeCreator.DePointNode(); }
public Bet(int amount, Outcome outcome) { amountBet = amount; this.outcome = outcome; }
internal int CalculateDamage(Outcome outcome, CharacterStats stats) { return(Damage.Calculate(outcome, stats, this)); }
private void UpdateStats(Outcome previousOutcome, Outcome newOutcome, OutcomeStats stats) { DecrementStat(previousOutcome, stats); IncrementStat(newOutcome, stats); }
/// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement) this).SerializeJson(writer, options, false); if (Outcome != null) { writer.WritePropertyName("outcome"); Outcome.SerializeJson(writer, options); } if (ProbabilityDecimal != null) { writer.WriteNumber("probabilityDecimal", (decimal)ProbabilityDecimal !); } if (_ProbabilityDecimal != null) { writer.WritePropertyName("_probabilityDecimal"); _ProbabilityDecimal.SerializeJson(writer, options); } if (ProbabilityRange != null) { writer.WritePropertyName("probabilityRange"); ProbabilityRange.SerializeJson(writer, options); } if (QualitativeRisk != null) { writer.WritePropertyName("qualitativeRisk"); QualitativeRisk.SerializeJson(writer, options); } if (RelativeRisk != null) { writer.WriteNumber("relativeRisk", (decimal)RelativeRisk !); } if (_RelativeRisk != null) { writer.WritePropertyName("_relativeRisk"); _RelativeRisk.SerializeJson(writer, options); } if (WhenPeriod != null) { writer.WritePropertyName("whenPeriod"); WhenPeriod.SerializeJson(writer, options); } if (WhenRange != null) { writer.WritePropertyName("whenRange"); WhenRange.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Rationale)) { writer.WriteString("rationale", (string)Rationale !); } if (_Rationale != null) { writer.WritePropertyName("_rationale"); _Rationale.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } }
public void LogMethodSummary(string methodName, Location loc, Outcome outcome, string additionalInfo, double time) { this.CloseVerificationBlockIfNecessary(); this.xwr.WriteStartElement("verification", LogFileNamespace); this.xwr.WriteAttributeString("method", methodName); this.xwr.WriteAttributeString("result", OutcomeToString(outcome)); this.xwr.WriteAttributeString("time", time.ToString("0.00")); this.WriteLocation(loc); if (!String.IsNullOrEmpty(additionalInfo)) { this.xwr.WriteElementString("info", LogFileNamespace, additionalInfo); } this.inVerificatioBlock = true; }
public static async Task <Outcome <T> > TryAsActionAsync <T, TAny>(Func <Task <Outcome <TAny> > > func, Outcome <T> returnValue) { try { var actionResult = await func(); return(actionResult.IsSuccessful ? returnValue : Outcome <T> .Reject(actionResult.FailureOrThrow())); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) { return(Fail(ex)); } #pragma warning restore CA1031 // Do not catch general exception types }
/// <summary> /// Main Enumerator for the <see cref="WebTest"/>. /// </summary> /// <returns></returns> public override IEnumerator<WebTestRequest> GetRequestEnumerator() { WebTestRequests(); foreach (var testRequest in testRequests.Requests) { currentTestRequest = testRequest; currentRequest = testRequest.Request(); currentWebTestOutcome = Outcome; currentRequest.ValidationRuleReferences.Clear(); foreach (var assert in testRequest.Asserts) { currentRequest.ValidateResponse += assert().Validate; } this.AddCommentToResult("Blah"); if (testRequest.MaxRetries == 0) { if (testRequest.WaitPeriod > 0) { Thread.Sleep(testRequest.WaitPeriod); } yield return currentRequest; } else { var retryValue = testRequest.RetryValue; if (testRequest.RetryValueDelegate != null) { retryValue = testRequest.RetryValueDelegate.Invoke(); } currentRequest.PostRequest += CurrentRequestOnPostRequest; for (var i = 0; i <= testRequest.MaxRetries; i++) { //TestValidateRetry(testRequest, i); currentRequest.ValidateResponse += new AssertRetryValidationRule(testRequest.RetryTestType, retryValue).Validate; yield return currentRequest; if (currentTestRequest.RetryTestType == RetryTestType.StatusCodeEquals && (int)LastResponse.StatusCode == int.Parse(retryValue)) { break; } if (currentTestRequest.RetryTestType == RetryTestType.BodyEquals && LastResponse.BodyString == retryValue) { break; } if (currentTestRequest.RetryTestType == RetryTestType.BodyIncludes && LastResponse.BodyString.IndexOf(retryValue, StringComparison.Ordinal) > -1) { break; } if (currentTestRequest.RetryTestType == RetryTestType.BodyDoesNotInclude && LastResponse.BodyString.IndexOf(retryValue, StringComparison.Ordinal) == -1) { break; } Thread.Sleep(testRequest.Interval); } } } AddFinalOutput(); }
private static void OnDeclareOutcome(ILink link, global::Amqp.Message message, Outcome outcome, object state) { var tcs = (TaskCompletionSource <byte[]>)state; if (outcome.Descriptor.Code == MessageSupport.DECLARED_INSTANCE.Descriptor.Code) { tcs.SetResult(((Declared)outcome).TxnId); } else if (outcome.Descriptor.Code == MessageSupport.REJECTED_INSTANCE.Descriptor.Code) { tcs.SetException(new AmqpException(((Rejected)outcome).Error)); } else { tcs.SetCanceled(); } }
public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as Procedure; if (dest != null) { base.CopyTo(dest); if (Identifier != null) { dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy()); } if (Subject != null) { dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy(); } if (StatusElement != null) { dest.StatusElement = (Code <Hl7.Fhir.Model.Procedure.ProcedureStatus>)StatusElement.DeepCopy(); } if (Category != null) { dest.Category = (Hl7.Fhir.Model.CodeableConcept)Category.DeepCopy(); } if (Code != null) { dest.Code = (Hl7.Fhir.Model.CodeableConcept)Code.DeepCopy(); } if (NotPerformedElement != null) { dest.NotPerformedElement = (Hl7.Fhir.Model.FhirBoolean)NotPerformedElement.DeepCopy(); } if (ReasonNotPerformed != null) { dest.ReasonNotPerformed = new List <Hl7.Fhir.Model.CodeableConcept>(ReasonNotPerformed.DeepCopy()); } if (BodySite != null) { dest.BodySite = new List <Hl7.Fhir.Model.CodeableConcept>(BodySite.DeepCopy()); } if (Reason != null) { dest.Reason = (Hl7.Fhir.Model.Element)Reason.DeepCopy(); } if (Performer != null) { dest.Performer = new List <Hl7.Fhir.Model.Procedure.PerformerComponent>(Performer.DeepCopy()); } if (Performed != null) { dest.Performed = (Hl7.Fhir.Model.Element)Performed.DeepCopy(); } if (Encounter != null) { dest.Encounter = (Hl7.Fhir.Model.ResourceReference)Encounter.DeepCopy(); } if (Location != null) { dest.Location = (Hl7.Fhir.Model.ResourceReference)Location.DeepCopy(); } if (Outcome != null) { dest.Outcome = (Hl7.Fhir.Model.CodeableConcept)Outcome.DeepCopy(); } if (Report != null) { dest.Report = new List <Hl7.Fhir.Model.ResourceReference>(Report.DeepCopy()); } if (Complication != null) { dest.Complication = new List <Hl7.Fhir.Model.CodeableConcept>(Complication.DeepCopy()); } if (FollowUp != null) { dest.FollowUp = new List <Hl7.Fhir.Model.CodeableConcept>(FollowUp.DeepCopy()); } if (Request != null) { dest.Request = (Hl7.Fhir.Model.ResourceReference)Request.DeepCopy(); } if (Notes != null) { dest.Notes = new List <Hl7.Fhir.Model.Annotation>(Notes.DeepCopy()); } if (FocalDevice != null) { dest.FocalDevice = new List <Hl7.Fhir.Model.Procedure.FocalDeviceComponent>(FocalDevice.DeepCopy()); } if (Used != null) { dest.Used = new List <Hl7.Fhir.Model.ResourceReference>(Used.DeepCopy()); } return(dest); } else { throw new ArgumentException("Can only copy to an object of the same type", "other"); } }
private static void OnDischargeOutcome(ILink link, global::Amqp.Message message, Outcome outcome, object state) { var tcs = (TaskCompletionSource <bool>)state; if (outcome.Descriptor.Code == MessageSupport.ACCEPTED_INSTANCE.Descriptor.Code) { tcs.SetResult(true); } else if (outcome.Descriptor.Code == MessageSupport.REJECTED_INSTANCE.Descriptor.Code) { tcs.SetException(new AmqpException(((Rejected)outcome).Error)); } else { tcs.SetCanceled(); } }
public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as ProcessResponse; if (dest != null) { base.CopyTo(dest); if (Identifier != null) { dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy()); } if (Request != null) { dest.Request = (Hl7.Fhir.Model.ResourceReference)Request.DeepCopy(); } if (Outcome != null) { dest.Outcome = (Hl7.Fhir.Model.Coding)Outcome.DeepCopy(); } if (DispositionElement != null) { dest.DispositionElement = (Hl7.Fhir.Model.FhirString)DispositionElement.DeepCopy(); } if (Ruleset != null) { dest.Ruleset = (Hl7.Fhir.Model.Coding)Ruleset.DeepCopy(); } if (OriginalRuleset != null) { dest.OriginalRuleset = (Hl7.Fhir.Model.Coding)OriginalRuleset.DeepCopy(); } if (CreatedElement != null) { dest.CreatedElement = (Hl7.Fhir.Model.FhirDateTime)CreatedElement.DeepCopy(); } if (Organization != null) { dest.Organization = (Hl7.Fhir.Model.ResourceReference)Organization.DeepCopy(); } if (RequestProvider != null) { dest.RequestProvider = (Hl7.Fhir.Model.ResourceReference)RequestProvider.DeepCopy(); } if (RequestOrganization != null) { dest.RequestOrganization = (Hl7.Fhir.Model.ResourceReference)RequestOrganization.DeepCopy(); } if (Form != null) { dest.Form = (Hl7.Fhir.Model.Coding)Form.DeepCopy(); } if (Notes != null) { dest.Notes = new List <Hl7.Fhir.Model.ProcessResponse.NotesComponent>(Notes.DeepCopy()); } if (Error != null) { dest.Error = new List <Hl7.Fhir.Model.Coding>(Error.DeepCopy()); } return(dest); } else { throw new ArgumentException("Can only copy to an object of the same type", "other"); } }
/// <summary> /// Adds or subtracts a Match Outcome. /// </summary> /// <param name="_outcome">Win, Loss, or Tie</param> /// <param name="_isAddition">Add or subtract</param> public void AddMatchOutcome(Outcome _outcome, bool _isAddition) { MatchRecord.AddOutcome(_outcome, _isAddition); }
public IAsyncResult BeginDisposeMessage(ArraySegment <byte> deliveryTag, ArraySegment <byte> txnId, Outcome outcome, bool batchable, TimeSpan timeout, AsyncCallback callback, object state) { this.ThrowIfClosed(); return(new DisposeAsyncResult(this, deliveryTag, txnId, outcome, batchable, timeout, callback, state)); }
/// <remarks/> public void ProcessTaskResponseAsync(string comments, Outcome outcome, int spTaskId) { this.ProcessTaskResponseAsync(comments, outcome, spTaskId, null); }
public Task <Outcome> DisposeMessageAsync(ArraySegment <byte> deliveryTag, ArraySegment <byte> txnId, Outcome outcome, bool batchable, TimeSpan timeout) { return(TaskHelpers.CreateTask( (c, s) => this.BeginDisposeMessage(deliveryTag, txnId, outcome, batchable, timeout, c, s), a => ((ReceivingAmqpLink)a.AsyncState).EndDisposeMessage(a), this)); }
/// <remarks/> public void ProcessTaskResponse3Async(string comments, Outcome outcome, int spTaskId, string taskListName) { this.ProcessTaskResponse3Async(comments, outcome, spTaskId, taskListName, null); }
private void ValidateOutcome(Outcome yourOutcome, Move move, Move opponentMove) { var isValid = true; switch (move) { case Move.Rock: { switch (opponentMove) { case Move.Rock: { isValid = yourOutcome == Outcome.Draw; break; } case Move.Dynamite: case Move.Paper: { isValid = yourOutcome == Outcome.Lose; break; } default: { isValid = yourOutcome == Outcome.Win; break; } } break; } case Move.Paper: { switch (opponentMove) { case Move.Paper: { isValid = yourOutcome == Outcome.Draw; break; } case Move.Dynamite: case Move.Scissors: { isValid = yourOutcome == Outcome.Lose; break; } default: { isValid = yourOutcome == Outcome.Win; break; } } break; } case Move.Scissors: { switch (opponentMove) { case Move.Scissors: { isValid = yourOutcome == Outcome.Draw; break; } case Move.Dynamite: case Move.Rock: { isValid = yourOutcome == Outcome.Lose; break; } default: { isValid = yourOutcome == Outcome.Win; break; } } break; } case Move.Dynamite: { switch (opponentMove) { case Move.Dynamite: { isValid = yourOutcome == Outcome.Draw; break; } case Move.Warterbomb: { isValid = yourOutcome == Outcome.Lose; break; } default: { isValid = yourOutcome == Outcome.Win; break; } } break; } case Move.Warterbomb: { switch (opponentMove) { case Move.Warterbomb: { isValid = yourOutcome == Outcome.Draw; break; } case Move.Dynamite: { isValid = yourOutcome == Outcome.Win; break; } default: { isValid = yourOutcome == Outcome.Lose; break; } } break; } } if (!isValid) { throw new ArgumentException(Constants.InvalidOutcome); } }
public void ProcessTaskResponseUsingToken(string comments, Outcome outcome, string taskToken, int customOutcome) { this.Invoke("ProcessTaskResponseUsingToken", new object[] { comments, outcome, taskToken, customOutcome}); }
protected override async Task OnSendAsync(IEnumerable <EventData> eventDatas, string partitionKey) { bool shouldRetry; int retryCount = 0; var timeoutHelper = new TimeoutHelper(this.EventHubClient.ConnectionStringBuilder.OperationTimeout, startTimeout: true); do { using (AmqpMessage amqpMessage = AmqpMessageConverter.EventDatasToAmqpMessage(eventDatas, partitionKey)) { shouldRetry = false; try { try { // Always use default timeout for AMQP sesssion. var amqpLink = await this.SendLinkManager.GetOrCreateAsync( TimeSpan.FromSeconds(AmqpClientConstants.AmqpSessionTimeoutInSeconds)).ConfigureAwait(false); if (amqpLink.Settings.MaxMessageSize.HasValue) { ulong size = (ulong)amqpMessage.SerializedMessageSize; if (size > amqpLink.Settings.MaxMessageSize.Value) { throw new MessageSizeExceededException(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value); } } Outcome outcome = await amqpLink.SendMessageAsync( amqpMessage, this.GetNextDeliveryTag(), AmqpConstants.NullBinary, timeoutHelper.RemainingTime()).ConfigureAwait(false); if (outcome.DescriptorCode != Accepted.Code) { Rejected rejected = (Rejected)outcome; throw new AmqpException(rejected.Error); } } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } catch (Exception ex) { if (AmqpExceptionHelper.TryTranslateToRetriableException(ex, out var retriableEx)) { throw retriableEx; } throw; } } catch (Exception ex) { // Evaluate retry condition? TimeSpan?retryInterval = this.RetryPolicy.GetNextRetryInterval(ex, timeoutHelper.RemainingTime(), ++retryCount); if (retryInterval != null && !this.IsClosed && !this.EventHubClient.IsClosed) { await Task.Delay(retryInterval.Value).ConfigureAwait(false); shouldRetry = true; } else { throw; } } } } while (shouldRetry); }
/// <remarks/> public void ProcessTaskResponseUsingTokenAsync(string comments, Outcome outcome, string taskToken, int customOutcome, object userState) { if ((this.ProcessTaskResponseUsingTokenOperationCompleted == null)) { this.ProcessTaskResponseUsingTokenOperationCompleted = new System.Threading.SendOrPostCallback(this.OnProcessTaskResponseUsingTokenOperationCompleted); } this.InvokeAsync("ProcessTaskResponseUsingToken", new object[] { comments, outcome, taskToken, customOutcome}, this.ProcessTaskResponseUsingTokenOperationCompleted, userState); }
private static string OutcomeToString(Outcome outcome) { switch (outcome) { case Outcome.Correct: return "success"; case Outcome.Errors: return "errors"; case Outcome.Inconclusive: return "inconclusive"; case Outcome.OutOfMemory: return "out of memory"; case Outcome.ReachedBound: return "bound reached"; case Outcome.TimedOut: return "timeout"; default: throw new ArgumentException(); } }
private bool testAssertion2(XdmNode assertion, Outcome outcome, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) { string tag = assertion.NodeName.LocalName; if (tag.Equals("assert-eq")) { if (outcome.isException()) { return false; } else { XPathSelector s = assertXpc.Compile("$result eq " + assertion.StringValue).Load(); s.SetVariable(new QName("result"), outcome.getResult()); XdmAtomicValue item = (XdmAtomicValue)s.EvaluateSingle(); if (s == null) { return false; } return (bool)item.Value; } } if (tag.Equals("assert-deep-eq")) { if (outcome.isException()) { return false; } else { XPathSelector s = assertXpc.Compile("deep-equal($result , (" + assertion.StringValue + "))").Load(); s.SetVariable(new QName("result"), outcome.getResult()); return (bool)((XdmAtomicValue)s.Evaluate()).Value; } } else if (tag.Equals("assert-permutation")) { // TODO: extend this to handle nodes (if required) if (outcome.isException()) { return false; } else { try { int expectedItems = 0; Hashtable expected = new Hashtable(); XPathSelector s = assertXpc.Compile("(" + assertion.StringValue + ")").Load(); s.SetVariable(new QName("result"), outcome.getResult()); // not used, but we declared it net.sf.saxon.lib.StringCollator collator = net.sf.saxon.expr.sort.CodepointCollator.getInstance(); net.sf.saxon.expr.XPathContext context = new net.sf.saxon.expr.XPathContextMajor(net.sf.saxon.value.StringValue.EMPTY_STRING, assertXpc.Processor.Implementation); /* foreach (XdmItem item in s) { expectedItems++; XdmValue value = (XdmValue) item; Object comparable = value.isNaN() ? AtomicSortComparer.COLLATION_KEY_NaN : value.getXPathComparable(false, collator, context); expected.add(comparable); } */ int actualItems = 0; /*foreach (XdmItem item in outcome.getResult()) { actualItems++; AtomicValue value = (AtomicValue) item.getUnderlyingValue(); Object comparable = value.isNaN() ? AtomicSortComparer.COLLATION_KEY_NaN : value.getXPathComparable(false, collator, context); if (!expected.Contains(comparable)) { return false; } }*/ return actualItems == expectedItems; } catch (DynamicError e) { return false; } } } else if (tag.Equals("assert-serialization")) { if (outcome.isException()) { return false; } else { string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space")); bool normalize = normalizeAtt != null && ("true".Equals(normalizeAtt.Trim()) || "1".Equals(normalizeAtt.Trim())); string ignoreAtt = assertion.GetAttributeValue(new QName("ignore-prefixes")); bool ignorePrefixes = ignoreAtt != null && ("true".Equals(ignoreAtt.Trim()) || "1".Equals(ignoreAtt.Trim())); catalogXpc.BaseUri = ""; string comparand = catalogXpc.Evaluate("if (@file) then unparsed-text(resolve-uri(@file, base-uri(.))) else string(.)", assertion).ToString(); if (normalize) { comparand = net.sf.saxon.value.Whitespace.collapseWhitespace(comparand).ToString(); } StringWriter tw = new StringWriter(); Serializer serializer = new Serializer(); serializer.SetOutputWriter(tw); serializer.SetOutputProperty(Serializer.METHOD, "xml"); serializer.SetOutputProperty(Serializer.INDENT, "no"); serializer.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes"); assertXpc.Processor.WriteXdmValue(outcome.getResult(), serializer); if (comparand.Equals(tw.ToString())) { return true; } DocumentBuilder builder = assertXpc.Processor.NewDocumentBuilder(); StringReader reader = new StringReader("<z>" + comparand + "</z>"); builder.BaseUri = assertion.BaseUri; XdmNode expected = builder.Build(reader); int flag = 0; flag |= net.sf.saxon.functions.DeepEqual.INCLUDE_COMMENTS; flag |= net.sf.saxon.functions.DeepEqual.INCLUDE_PROCESSING_INSTRUCTIONS; if (!ignorePrefixes) { flag |= net.sf.saxon.functions.DeepEqual.INCLUDE_NAMESPACES; flag |= net.sf.saxon.functions.DeepEqual.INCLUDE_PREFIXES; } flag |= net.sf.saxon.functions.DeepEqual.COMPARE_STRING_VALUES; flag |= net.sf.saxon.functions.DeepEqual.WARNING_IF_FALSE; try { net.sf.saxon.om.SequenceIterator iter0; XdmValue v = outcome.getResult(); if (v.Count == 1 && v is XdmNode && ((XdmNode)v).NodeKind == XmlNodeType.Document) { iter0 = ((XdmNode)v).Implementation.iterateAxis(net.sf.saxon.om.Axis.CHILD); } else { iter0 = net.sf.saxon.value.Value.asIterator(outcome.getResult().Unwrap()); } net.sf.saxon.om.SequenceIterator iter1 = (expected.Implementation.iterateAxis(net.sf.saxon.om.Axis.CHILD).next()).iterateAxis(net.sf.saxon.om.Axis.CHILD); return net.sf.saxon.functions.DeepEqual.deepEquals( iter0, iter1, new net.sf.saxon.expr.sort.GenericAtomicComparer(net.sf.saxon.expr.sort.CodepointCollator.getInstance(), null), assertXpc.Processor.Implementation, flag); } catch (DynamicError e) { // e.printStackTrace(); return false; } } } else if (tag.Equals("assert-serialization-error")) { if (outcome.isException()) { return false; } else { string expectedError = assertion.GetAttributeValue(new QName("code")); StringWriter sw = new StringWriter(); Serializer serializer = new Serializer(); serializer.SetOutputWriter(sw); serializer.SetOutputProperty(Serializer.METHOD, "xml"); serializer.SetOutputProperty(Serializer.INDENT, "no"); serializer.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes"); try { assertXpc.Processor.WriteXdmValue(outcome.getResult(), serializer); return false; } catch (DynamicError err) { bool b = expectedError.Equals(err.ErrorCode.LocalName); if (!b) { feedback.Message("Expected " + expectedError + ", got " + err.ErrorCode.LocalName, false); } return true; } } } else if (tag.Equals("assert-empty")) { if (outcome.isException()) { return false; } else { XdmValue result = outcome.getResult(); return result.Count == 0; } } else if (tag.Equals("assert-count")) { if (outcome.isException()) { return false; } else { XdmValue result = outcome.getResult(); return result.Count == int.Parse(assertion.StringValue); } } else if (tag.Equals("assert")) { if (outcome.isException()) { return false; } else { XPathSelector s = assertXpc.Compile(assertion.StringValue).Load(); s.SetVariable(new QName("result"), outcome.getResult()); return (bool)((XdmAtomicValue)s.EvaluateSingle()).Value; } } else if (tag.Equals("assert-string-value")) { if (outcome.isException()) { return false; } else { XdmValue resultValue = outcome.getResult(); string resultstring; string assertionstring = assertion.StringValue; if (resultValue is XdmNode) { resultstring = ((XdmNode)resultValue).StringValue; }else if(resultValue is XdmAtomicValue){ resultstring = ((XdmAtomicValue)resultValue).ToString(); } else { bool first = true; StringBuilder fsb = new StringBuilder(256); foreach (XdmItem item in resultValue) { if (first) { first = false; } else { fsb.Append(' '); } fsb.Append(item.Unwrap().getStringValue()); } resultstring = fsb.ToString(); } string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space")); if (normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1"))) { assertionstring = net.sf.saxon.value.Whitespace.collapseWhitespace(assertionstring).ToString(); resultstring = net.sf.saxon.value.Whitespace.collapseWhitespace(resultstring).ToString(); } if (resultstring.Equals(assertionstring)) { return true; } else { if (debug) { if (resultstring.Length != assertionstring.Length) { Console.WriteLine("Result length " + resultstring.Length + "; expected length " + assertionstring.Length); } int len = Math.Min(resultstring.Length, assertionstring.Length); for (int i = 0; i < len; i++) { if (resultstring[i] != assertionstring[i]) { feedback.Message("Results differ at index " + i + "(\"" + resultstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" + assertionstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\")", false); break; } } } return false; } } } else if (tag.Equals("assert-type")) { if (outcome.isException()) { return false; } else { XPathSelector s = assertXpc.Compile("$result instance of " + assertion.StringValue).Load(); s.SetVariable(new QName("result"), outcome.getResult()); return (bool)((XdmAtomicValue)s.EvaluateSingle()).Value; } } else if (tag.Equals("assert-true")) { if (outcome.isException()) { return false; } else { XdmValue result = outcome.getResult(); return result.Count == 1 && ((XdmItem)result).IsAtomic() && ((XdmAtomicValue)result).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) && (((XdmAtomicValue)result).GetBooleanValue()); } } else if (tag.Equals("assert-false")) { if (outcome.isException()) { return false; } else { XdmValue result = outcome.getResult(); return result.Count == 1 && ((XdmItem)result.Simplify).IsAtomic() && ((XdmAtomicValue)result.Simplify).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) && !(bool)((XdmAtomicValue)result.Simplify).Value; } } else if (tag.Equals("error")) { string expectedError = assertion.GetAttributeValue(new QName("code")); //noinspection ThrowableResultOfMethodCallIgnored Exception err = outcome.getException(); QName errorCode = null; if (err is DynamicError) { errorCode = ((DynamicError)outcome.getException()).ErrorCode; } else { errorCode = ((StaticError)outcome.getException()).ErrorCode; } return outcome.isException() && (expectedError.Equals("*") || (errorCode != null && errorCode.LocalName.Equals(expectedError)) || (outcome.hasReportedError(expectedError))); } else if (tag.Equals("all-of")) { XdmValue children = catalogXpc.Evaluate("*", assertion); foreach (XdmItem child in children) { if (!testAssertion((XdmNode)child, outcome, assertXpc, catalogXpc, debug)) { return false; } } return true; } else if (tag.Equals("any-of")) { XdmValue children = catalogXpc.Evaluate("*", assertion); foreach (XdmItem child in children) { if (testAssertion((XdmNode)child, outcome, assertXpc, catalogXpc, debug)) { return true; } } return false; } throw new Exception("Unknown assertion element " + tag); }
public virtual void OnModel(IList<string> labels, Model model, Outcome proverOutcome) { Contract.Requires(cce.NonNullElements(labels)); }
protected override async Task OnSendAsync(IEnumerable <EventData> eventDatas, string partitionKey) { bool shouldRetry; var timeoutHelper = new TimeoutHelper(this.EventHubClient.ConnectionStringBuilder.OperationTimeout, true); do { using (AmqpMessage amqpMessage = AmqpMessageConverter.EventDatasToAmqpMessage(eventDatas, partitionKey)) { shouldRetry = false; try { try { var amqpLink = await this.SendLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); if (amqpLink.Settings.MaxMessageSize.HasValue) { ulong size = (ulong)amqpMessage.SerializedMessageSize; if (size > amqpLink.Settings.MaxMessageSize.Value) { throw new MessageSizeExceededException(amqpMessage.DeliveryId.Value, size, amqpLink.Settings.MaxMessageSize.Value); } } Outcome outcome = await amqpLink.SendMessageAsync(amqpMessage, this.GetNextDeliveryTag(), AmqpConstants.NullBinary, timeoutHelper.RemainingTime()).ConfigureAwait(false); if (outcome.DescriptorCode != Accepted.Code) { Rejected rejected = (Rejected)outcome; throw new AmqpException(rejected.Error); } this.EventHubClient.RetryPolicy.ResetRetryCount(this.ClientId); } catch (AmqpException amqpException) { throw AmqpExceptionHelper.ToMessagingContract(amqpException.Error); } } catch (Exception ex) { // Evaluate retry condition? this.EventHubClient.RetryPolicy.IncrementRetryCount(this.ClientId); TimeSpan?retryInterval = this.EventHubClient.RetryPolicy.GetNextRetryInterval(this.ClientId, ex, timeoutHelper.RemainingTime()); if (retryInterval != null) { await Task.Delay(retryInterval.Value).ConfigureAwait(false); shouldRetry = true; } else { throw; } } } } while (shouldRetry); }
public void TerminateActivityInFinally() { s_exceptionType = typeof(InvalidCastException); s_exceptionMsg = "I want to go home now!"; s_terminationReason = "I like home!"; TestTryCatch tryCatch = new TestTryCatch("TryCatch") { Try = new TestSequence("TryingSeq") { Activities = { new TestWriteLine() { Message = "I'm Trying here", HintMessage = "I'm Trying here" }, new TestThrow <ArgumentException>("TryException") { ExpectedOutcome = Outcome.CaughtException(), }, } }, Catches = { new TestCatch <ArgumentException>() { Body = new TestSequence("CatchingSeq") { Activities = { new TestWriteLine("CaughtException") { Message = "aha I caught you!", HintMessage = "aha I caught you!", } } } } }, Finally = new TestSequence("FinallySeq") { Activities = { new TestTerminateWorkflow() { ExceptionExpression = ((env) => new InvalidCastException("I want to go home now!")), Reason = s_terminationReason }, new TestWriteLine("InFinally") { Message = "Should Not Execute!", HintMessage = "A Bug if executed", ExpectedOutcome = Outcome.None } } } }; RunTestWithWorkflowRuntime(tryCatch); }
public async Task <string> RaiseOutcomeAsync(IComponent sourceComponent, Outcome outcome) { var executionThread = await AppExecutionApiClient.LoadExecutionThreadAsync(sourceComponent.TXID.tid); return(await RaiseOutcomeAsync(executionThread, sourceComponent.TXID, outcome)); }
public bool ProcessTaskResponse(string comments, Outcome outcome, int spTaskId) { object[] results = this.Invoke("ProcessTaskResponse", new object[] { comments, outcome, spTaskId}); return ((bool)(results[0])); }
public virtual void OnModel(IList <string> labels, Model model, Outcome proverOutcome) { Contract.Requires(cce.NonNullElements(labels)); }
public ProcessTaskResponseResult ProcessTaskResponse3(string comments, Outcome outcome, int spTaskId, string taskListName) { object[] results = this.Invoke("ProcessTaskResponse3", new object[] { comments, outcome, spTaskId, taskListName}); return ((ProcessTaskResponseResult)(results[0])); }
protected async Task <Outcome <string> > GetFailedOutcomeAsync() { await Task.Delay(0); return(Outcome <string> .Reject("Test Async Failure")); }
/// <remarks/> public void ProcessTaskResponse3Async(string comments, Outcome outcome, int spTaskId, string taskListName, object userState) { if ((this.ProcessTaskResponse3OperationCompleted == null)) { this.ProcessTaskResponse3OperationCompleted = new System.Threading.SendOrPostCallback(this.OnProcessTaskResponse3OperationCompleted); } this.InvokeAsync("ProcessTaskResponse3", new object[] { comments, outcome, spTaskId, taskListName}, this.ProcessTaskResponse3OperationCompleted, userState); }
public override void HandleOutcome(Outcome outcome) { throw new NotImplementedException(); }
/// <remarks/> public void ProcessTaskResponseUsingTokenAsync(string comments, Outcome outcome, string taskToken, int customOutcome) { this.ProcessTaskResponseUsingTokenAsync(comments, outcome, taskToken, customOutcome, null); }
/// <summary> /// Sends a set of messages to the associated Queue/Topic using a batched approach. /// </summary> /// /// <param name="messageFactory"></param> /// <param name="timeout"></param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// internal virtual async Task SendBatchInternalAsync( Func <AmqpMessage> messageFactory, TimeSpan timeout, CancellationToken cancellationToken) { var stopWatch = ValueStopwatch.StartNew(); var link = default(SendingAmqpLink); try { using (AmqpMessage batchMessage = messageFactory()) { string messageHash = batchMessage.GetHashCode().ToString(CultureInfo.InvariantCulture); ArraySegment <byte> transactionId = AmqpConstants.NullBinary; Transaction ambientTransaction = Transaction.Current; if (ambientTransaction != null) { transactionId = await AmqpTransactionManager.Instance.EnlistAsync( ambientTransaction, _connectionScope, _transactionGroup, timeout).ConfigureAwait(false); } link = await _sendLink.GetOrCreateAsync(UseMinimum(_connectionScope.SessionTimeout, timeout)).ConfigureAwait(false); // Validate that the message is not too large to send. This is done after the link is created to ensure // that the maximum message size is known, as it is dictated by the service using the link. if (batchMessage.SerializedMessageSize > MaxMessageSize) { throw new ServiceBusException(string.Format(CultureInfo.InvariantCulture, Resources.MessageSizeExceeded, messageHash, batchMessage.SerializedMessageSize, MaxMessageSize, _entityPath), ServiceBusFailureReason.MessageSizeExceeded); } // Attempt to send the message batch. var deliveryTag = new ArraySegment <byte>(BitConverter.GetBytes(Interlocked.Increment(ref _deliveryCount))); Outcome outcome = await link.SendMessageAsync( batchMessage, deliveryTag, transactionId, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); if (outcome.DescriptorCode != Accepted.Code) { throw (outcome as Rejected)?.Error.ToMessagingContractException(); } cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); } } catch (Exception exception) { ExceptionDispatchInfo.Capture(AmqpExceptionHelper.TranslateException( exception, link?.GetTrackingId(), null, HasLinkCommunicationError(link))) .Throw(); throw; // will never be reached } }
private bool testAssertion(XdmNode assertion, Outcome outcome, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) { try { string tag = assertion.NodeName.LocalName; bool result = testAssertion2(assertion, outcome, assertXpc, catalogXpc, debug); if (debug && !("all-of".Equals(tag)) && !("any-of".Equals(tag))) { feedback.Message("Assertion " + tag + " (" + assertion.StringValue + ") " + (result ? " succeeded" : " failed"), false); if (tag.Equals("error")) { Console.WriteLine("Expected exception " + assertion.GetAttributeValue(new QName("code")) + ", got " + (outcome.isException() ? ((DynamicError)outcome.getException()).ErrorCode.ToString() : "success")); } } return result; } catch (Exception e) { //e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return false; } }
public static Event stealingFood(Character c) { voidFunction[] a = { () => { c.setMood(0); if (c.isSitting()) { BusManager.instance.getSeat(BusManager.instance.getSeat(c.id)).Stand(c.gameObject); } c.desired = new Vector2(1.8f, 0f); c.moving = true; c.location = -1; } }; boolFunction[] t = { () => { return(true); } }; float s = 50f; Outcome[] o = new Outcome[4] { new Outcome(new voidFunction[1] { new voidFunction(() => { c.setMood(-1); c.GetComponent <Animator>().SetBool("SpecialAction", true); isStealing = true; }) }, new boolFunction[1] { new boolFunction(() => { return(true); }) }, 7f, false), new Outcome(new voidFunction[1] { new voidFunction(() => { c.setMood(-2); }) }, new boolFunction[1] { new boolFunction(() => { return(true); }) }, 12f, false), new Outcome(new voidFunction[1] { new voidFunction(() => { stopStealing(c); }) }, new boolFunction[1] { new boolFunction(() => { return(isStealing); }) }, 18f, true), new Outcome(new voidFunction[1] { new voidFunction(() => { stopStealing(c); }) }, new boolFunction[1] { new boolFunction(() => { return(!isStealing); }) }, 20f, true) }; return(new Event(a, t, s, o)); //return this event }
/** * Run a test case * * @param testCase the test case element in the catalog * @param xpc the XPath compiler to be used for compiling XPath expressions against the catalog * @throws SaxonApiException */ private void runTestCase(XdmNode testCase, XPathCompiler xpc) { string testCaseName = testCase.GetAttributeValue(new QName("name")); feedback.Message("Test case " + testCaseName + Environment.NewLine, false); XdmNode exceptionElement = null; try { exceptionElement = exceptionsMap[testCaseName]; } catch (Exception) { } XdmNode alternativeResult = null; XdmNode optimization = null; if (exceptionElement != null) { string runAtt = exceptionElement.GetAttributeValue(new QName("run")); if ("no".Equals(runAtt)) { WriteTestCaseElement(testCaseName, "notRun", "see exceptions file"); return; } if (unfolded && "not-unfolded".Equals(runAtt)) { WriteTestCaseElement(testCaseName, "notRun", "see exceptions file"); return; } alternativeResult = (XdmNode)xpc.EvaluateSingle("result", exceptionElement); optimization = (XdmNode)xpc.EvaluateSingle("optimization", exceptionElement); } XdmNode environmentNode = (XdmNode)xpc.EvaluateSingle("environment", testCase); TestEnvironment env = null; if (environmentNode == null) { env = localEnvironments["default"]; } else { string envName = environmentNode.GetAttributeValue(new QName("ref")); if (envName == null) { env = processEnvironment(xpc, environmentNode, null); } else { try { env = localEnvironments[envName]; } catch (Exception) { } if (env == null) { try { env = globalEnvironments[envName]; } catch (Exception) { } } if (env == null) { Console.WriteLine("*** Unknown environment " + envName); WriteTestCaseElement(testCaseName, "fail", "Environment " + envName + " not found"); failures++; return; } } } env.xpathCompiler.BackwardsCompatible = false; env.processor.XmlVersion = (decimal)1.0; bool run = true; bool xpDependency = false; string hostLang; string langVersion; if (preferQuery) { hostLang = "XQ"; langVersion = "1.0"; } else { hostLang = "XP"; langVersion = "2.0"; } XdmValue dependencies = xpc.Evaluate("/*/dependency, ./dependency", testCase); foreach (XdmItem dependency in dependencies) { string type = ((XdmNode)dependency).GetAttributeValue(new QName("type")); if (type == null) { throw new Exception("dependency/@type is missing"); } string value = ((XdmNode)dependency).GetAttributeValue(new QName("value")); if (value == null) { throw new Exception("dependency/@value is missing"); } if (type.Equals("spec")) { if (value.Contains("XP") && !value.Contains("XQ")) { hostLang = "XP"; langVersion = (value.Equals("XP20") ? "2.0" : "3.0"); xpDependency = true; } else if (value.Contains("XP") && value.Contains("XQ") && preferQuery) { hostLang = "XQ"; langVersion = (value.Contains("XQ10+") || value.Contains("XQ30") ? "3.0" : "1.0"); } else if (value.Contains("XT")) { hostLang = "XT"; langVersion = (value.Contains("XT30+") || value.Contains("XT30") ? "3.0" : "1.0"); } else { hostLang = "XQ"; langVersion = (value.Contains("XQ10+") || value.Contains("XQ30") ? "3.0" : "1.0"); } } if (type.Equals("feature") && value.Equals("xpath-1.0-compatibility")) { hostLang = "XP"; langVersion = "3.0"; xpDependency = true; } if (type.Equals("feature") && value.Equals("namespace-axis")) { hostLang = "XP"; langVersion = "3.0"; xpDependency = true; } if (!DependencyIsSatisfied((XdmNode)dependency, env)) { Console.WriteLine("*** Dependency not satisfied: " + ((XdmNode)dependency).GetAttributeValue(new QName("type"))); WriteTestCaseElement(testCaseName, "notRun", "Dependency not satisfied"); run = false; } } if ((unfolded && !xpDependency) || optimization != null) { hostLang = "XQ"; if (langVersion.Equals("2.0")) { langVersion = "1.0"; } } if (run) { Outcome outcome = null; string exp = null; try { exp = xpc.Evaluate("if (test/@file) then unparsed-text(resolve-uri(test/@file, base-uri(.))) else string(test)", testCase).ToString(); } catch (DynamicError err) { Console.WriteLine("*** Failed to read query: " + err.Message); outcome = new Outcome(err); } if (outcome == null) { if (hostLang.Equals(("XP"))) { XPathCompiler testXpc = env.xpathCompiler; testXpc.XPathLanguageVersion = langVersion; testXpc.DeclareNamespace("fn", JNamespaceConstant.FN); testXpc.DeclareNamespace("xs", JNamespaceConstant.SCHEMA); testXpc.DeclareNamespace("math", JNamespaceConstant.MATH); testXpc.DeclareNamespace("map", JNamespaceConstant.MAP_FUNCTIONS); try { XPathSelector selector = testXpc.Compile(exp).Load(); foreach (QName varName in env.params1.Keys) { selector.SetVariable(varName, env.params1[varName]); } if (env.contextNode != null) { selector.ContextItem = env.contextNode; } selector.InputXmlResolver = new TestUriResolver(env); XdmValue result = selector.Evaluate(); outcome = new Outcome(result); } catch (DynamicError err) { Console.WriteLine(err.Message); outcome = new Outcome(err); } catch (StaticError err) { Console.WriteLine(err.Message); outcome = new Outcome(err); } catch (Exception err) { Console.WriteLine("*** Failed to read query: " + err.Message); outcome = new Outcome(new DynamicError("*** Failed to read query: " + err.Message)); } } else { XQueryCompiler testXqc = env.xqueryCompiler; testXqc.XQueryLanguageVersion = langVersion; testXqc.DeclareNamespace("fn", JNamespaceConstant.FN); testXqc.DeclareNamespace("xs", JNamespaceConstant.SCHEMA); testXqc.DeclareNamespace("math", JNamespaceConstant.MATH); testXqc.DeclareNamespace("map", JNamespaceConstant.MAP_FUNCTIONS); ErrorCollector errorCollector = new ErrorCollector(); //testXqc.setErrorListener(errorCollector); string decVars = env.paramDecimalDeclarations.ToString(); if (decVars.Length != 0) { int x = (exp.IndexOf("(:%DECL%:)")); if (x < 0) { exp = decVars + exp; } else { exp = exp.Substring(0, x) + decVars + exp.Substring(x + 13); } } string vars = env.paramDeclarations.ToString(); if (vars.Length != 0) { int x = (exp.IndexOf("(:%VARDECL%:)")); if (x < 0) { exp = vars + exp; } else { exp = exp.Substring(0, x) + vars + exp.Substring(x + 13); } } ModuleResolver mr = new ModuleResolver(xpc); mr.setTestCase(testCase); testXqc.QueryResolver = (IQueryResolver)mr; try { XQueryExecutable q = testXqc.Compile(exp); if (optimization != null) { /* XdmDestination expDest = new XdmDestination(); net.sf.saxon.Configuration config = driverProc.Implementation; net.sf.saxon.trace.ExpressionPresenter presenter = new net.sf.saxon.trace.ExpressionPresenter(driverProc.Implementation, expDest.getReceiver(config)); //q.getUnderlyingCompiledQuery().explain(presenter); presenter.close(); XdmNode explanation = expDest.XdmNode; XdmItem optResult = xpc.EvaluateSingle(optimization.GetAttributeValue(new QName("assert")), explanation); if ((bool)((XdmAtomicValue)optResult).Value) { Console.WriteLine("Optimization result OK"); } else { Console.WriteLine("Failed optimization test"); Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Error); driverProc.WriteXdmValue(explanation, serializer); WriteTestCaseElement(testCaseName, "fail", "Failed optimization assertions"); failures++; return; }*/ } XQueryEvaluator selector = q.Load(); foreach (QName varName in env.params1.Keys) { selector.SetExternalVariable(varName, env.params1[varName]); } if (env.contextNode != null) { selector.ContextItem = env.contextNode; } selector.InputXmlResolver= new TestUriResolver(env); XdmValue result = selector.Evaluate(); outcome = new Outcome(result); } catch (DynamicError err) { Console.WriteLine("TestSet" + testFuncSet); Console.WriteLine(err.Message); outcome = new Outcome(err); outcome.setErrorsReported(errorCollector.getErrorCodes()); } catch(StaticError err){ Console.WriteLine("TestSet" + testFuncSet); Console.WriteLine(err.Message); outcome = new Outcome(err); outcome.setErrorsReported(errorCollector.getErrorCodes()); } catch(Exception err){ Console.WriteLine("TestSet" + testFuncSet); Console.WriteLine(err.Message); outcome = new Outcome(new DynamicError(err.Message)); outcome.setErrorsReported(errorCollector.getErrorCodes()); } } } XdmNode assertion; if (alternativeResult != null) { assertion = (XdmNode)xpc.EvaluateSingle("*[1]", alternativeResult); } else { assertion = (XdmNode)xpc.EvaluateSingle("result/*[1]", testCase); } if (assertion == null) { Console.WriteLine("*** No assertions found for test case " + testCaseName); WriteTestCaseElement(testCaseName, "fail", "No assertions in test case"); failures++; return; } XPathCompiler assertXpc = env.processor.NewXPathCompiler(); assertXpc.XPathLanguageVersion = "3.0"; assertXpc.DeclareNamespace("fn", JNamespaceConstant.FN); assertXpc.DeclareNamespace("xs", JNamespaceConstant.SCHEMA); assertXpc.DeclareNamespace("math", JNamespaceConstant.MATH); assertXpc.DeclareNamespace("map", JNamespaceConstant.MAP_FUNCTIONS); assertXpc.DeclareVariable(new QName("result")); bool b = testAssertion(assertion, outcome, assertXpc, xpc, debug); if (b) { Console.WriteLine("OK"); successes++; feedback.Message("OK" + Environment.NewLine, false); WriteTestCaseElement(testCaseName, "full", null); } else { if (outcome.isException()) { XdmItem expectedError = xpc.EvaluateSingle("result//error/@code", testCase); if (expectedError == null) { // if (debug) { // outcome.getException().printStackTrace(System.out); // } if (outcome.getException() is StaticError) { WriteTestCaseElement(testCaseName, "fail", "Expected success, got " + ((StaticError)outcome.getException()).ErrorCode); feedback.Message("*** fail, result " + ((StaticError)outcome.getException()).ErrorCode.LocalName + " Expected success." + Environment.NewLine, false); } else { WriteTestCaseElement(testCaseName, "fail", "Expected success, got " + ((DynamicError)outcome.getException()).ErrorCode); feedback.Message("*** fail, result " + ((DynamicError)outcome.getException()).ErrorCode.LocalName + " Expected success." + Environment.NewLine, false); } failures++; } else { if (outcome.getException() is StaticError) { WriteTestCaseElement(testCaseName, "different-error", "Expected error:" + expectedError.ToString() /*.GetstringValue()*/ + ", got " + ((StaticError)outcome.getException()).ErrorCode.ToString()); feedback.Message("*** fail, result " + ((StaticError)outcome.getException()).ErrorCode.LocalName + " Expected error:" + expectedError.ToString() + Environment.NewLine, false); } else { WriteTestCaseElement(testCaseName, "different-error", "Expected error:" + expectedError.ToString() /*.GetstringValue()*/ + ", got " + ((DynamicError)outcome.getException()).ErrorCode.ToString()); feedback.Message("*** fail, result " + ((DynamicError)outcome.getException()).ErrorCode.LocalName + " Expected error:" + expectedError.ToString() + Environment.NewLine, false); } wrongErrorResults++; } } else { try { WriteTestCaseElement(testCaseName, "fail", "Wrong results, got " + truncate(outcome.serialize(assertXpc.Processor))); }catch (Exception) { WriteTestCaseElement(testCaseName, "fail", "Wrong results, got "); } failures++; if (debug) { try { feedback.Message("Result:" + Environment.NewLine, false); // driverProc.WriteXdmValue(outcome.getResult(), driverSerializer); feedback.Message("=======" + Environment.NewLine, false); } catch (Exception) { } feedback.Message(outcome.getResult() + Environment.NewLine, false); } else { feedback.Message("*** fail (use -debug to show actual result)" + Environment.NewLine, false); } } } feedback.Feedback(successes, failures, 25693); } }
bool isUnauthorized(Outcome <AuthorizedClient> outcome) { throw new NotImplementedException(); }