public OneOf <object, Exception> Invoke(OneOf <object, Exception> param) { // If previous step failed, propagate failure if (param.IsT1) { return(param.AsT1); } // Otherwise, execute current step try { if (typeof(TPrevious) == typeof(Unit)) { return(_func(default));
protected OneOf <string, RenderFragment> GetShowValue(SelectOption option) { if (option.IsSearch || option.IsTag) { return(option.Value); } return(OptionLabelProp switch { "children" => option?.ChildContent, "value" => option?.Value ?? option.Label, "label" => option?.Label ?? option.Value, _ => SelectMode == SelectMode.Default ? OneOf <string, RenderFragment> .FromT1((option?.ChildContent)) : option?.Label ?? option.Value, });
/// <inheritdoc/> public override void Write(Utf8JsonWriter writer, OneOf <T1, T2> value, JsonSerializerOptions options) { var json = null as string; if (value.T1Value != null) { json = JsonSerializer.Serialize(value.T1Value); } else { json = JsonSerializer.Serialize(value.T2Value); } writer.WriteStringValue(json); }
public void Can_use_classic_switch() { var actual = new OneOf <string, int>("foo"); switch (actual.Value) { case string str: Assert.Equal("foo", str); break; default: Assert.True(false); break; } }
/// <inheritdoc/> public override void WriteJson(JsonWriter writer, OneOf <T1, T2>?value, JsonSerializer serializer) { if (value == null) { return; } if (value.T1Value != null) { serializer.Serialize(writer, value.T1Value); } else if (value.T2Value != null) { serializer.Serialize(writer, value.T2Value); } }
public void Validation_or_value_is_serializable_validation() { var expected = new OneOf <string, ValidationState>( new Validator() .Error("SomeField", "Required field") .State ); var serialized = JsonConvert.SerializeObject(expected); var deserialized = JsonConvert.DeserializeObject <OneOf <string, ValidationState> >(serialized); Assert.True(deserialized.Is2); Assert.Equal(expected.As2.Count, deserialized.As2.Count); Assert.Equal(expected.As2.GetErrorText("SomeField"), deserialized.As2.GetErrorText("SomeField")); }
private void HandleSearchResult(OneOf <CustomerResult, CustomerSearchError> result) { result.Switch(sr => { var formattedTextResult = JsonSerializer.Serialize(sr, new JsonSerializerOptions { WriteIndented = true }); _consoleWriter.WriteLine(formattedTextResult); }, error => { var formattedErrors = string.Join(", ", error.ErrorMessages); _consoleWriter.WriteLine(formattedErrors); }); }
public async Task SetLabelText(string labelText) { OneOf <string, MarkerLabel> markerLabel = await GetLabel(); if (markerLabel.IsT1) { MarkerLabel label = markerLabel.AsT1; label.Text = labelText; await SetLabel(label); } else { await SetLabel(labelText); } }
public void MatcherMatchesOnlyOnceWhenParentClassAndSubClassesAreInOneofAndCreationReferenceIsOfTypeParentButInstanceIsReallyChild() { OneOf <Fake, Fake.One, Fake.Two> hiddenOne = (Fake) new Fake.One(); Func <OneOf <Fake, Fake.One, Fake.Two>, int> testerFunc = o => { var result = o.Match((Fake f) => 3). Match((Fake.One f) => 1). Match((Fake.Two f) => 2); return(result); }; Assert.AreEqual(1, testerFunc(hiddenOne)); }
public static OneOf <IEnumerable <TResult>, TError> SelectMany <TSource, TSuccess, TError, TResult>( this IEnumerable <TSource> source, Func <TSource, OneOf <TSuccess, TError> > selector, Func <TSource, TSuccess, TResult> resultSelector) { return(source.Aggregate( OneOf <ImmutableArray <TResult>, TError> .FromT0(ImmutableArray <TResult> .Empty), (previousAggregate, currentItem) => previousAggregate.Match( previousSuccesses => selector(currentItem).Match <OneOf <ImmutableArray <TResult>, TError> >( itemSuccess => previousSuccesses.Add(resultSelector(currentItem, itemSuccess)), itemError => itemError), previousError => previousError), aggregate => aggregate.Match <OneOf <IEnumerable <TResult>, TError> >(allSuccesses => allSuccesses, error => error))); }
public override int GetHashCode() { int hash = 1; if (matchPatternCase_ == MatchPatternOneofCase.OneOf) { hash ^= OneOf.GetHashCode(); } hash ^= (int)matchPatternCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
/// <summary> /// Add the provided JSON schema as an option for the oneOf property of this JSON schema. /// </summary> /// <param name="oneOfOption"></param> /// <returns></returns> public JsonSchema AddOneOf(JsonSchema oneOfOption) { if (oneOfOption == null) { throw new ArgumentNullException(nameof(oneOfOption)); } if (OneOf == null) { OneOf = new List <JsonSchema>(); } OneOf.Add(oneOfOption); return(this); }
Should <T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> (this OneOf <T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> item) { return(new OneOfAssertions <T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> (item)); }
public bool Equals(OneOf <A, B, C> other) { if (whichOne != other.whichOne) { return(false); } if (isA) { return(EqComparer <A> .Default.Equals(_aValue, other._aValue)); } if (isB) { return(EqComparer <B> .Default.Equals(_bValue, other._bValue)); } return(EqualityComparer <C> .Default.Equals(_cValue, other._cValue)); }
internal static async Task TraceBlockAsync(Uri uri, OneOf <uint, UInt256> blockId, IConsole console) { var settings = await GetProtocolSettingsAsync(uri).ConfigureAwait(false); using var rpcClient = new RpcClient(uri, protocolSettings: settings); var block = await GetBlockAsync(rpcClient, blockId).ConfigureAwait(false); if (block.Transactions.Length == 0) { throw new Exception($"Block {block.Index} ({block.Hash}) had no transactions"); } await console.Out.WriteLineAsync($"Tracing all the transactions in block {block.Index} ({block.Hash})"); TraceBlock(uri, block, settings, console); }
private static Task <string> Process(OneOf <string, int> input) { return(input .Map( x => Task.FromResult(x + "!"), x => Task.FromResult(x + 1) ) .Map( x => x + "$$", x => x * 4 ) .Extract( a => a, b => b.ToString() )); }
public void AssertOption_OneOf_CaseNotPresent() { var itemToCheck = OneOf <Some <int>, None> .FromT0( new Some <int> { Value = 3 }); Action failureAction = () => itemToCheck.Should().BeCase <int>(); failureAction.Should().Throw <AssertionException>().WithMessage( "Unable to find any Discriminated Union method on type \"OneOf<Some<Int32>,None>\" for expected type \"Int32\""); }
/// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { unchecked { var hashCode = Type.GetHashCode(); hashCode = (hashCode * 397) ^ (Id?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Schema?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Comment?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Title?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Description?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Default?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ MultipleOf.GetHashCode(); hashCode = (hashCode * 397) ^ Maximum.GetHashCode(); hashCode = (hashCode * 397) ^ ExclusiveMaximum.GetHashCode(); hashCode = (hashCode * 397) ^ Minimum.GetHashCode(); hashCode = (hashCode * 397) ^ ExclusiveMinimum.GetHashCode(); hashCode = (hashCode * 397) ^ (MaxLength?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (MinLength?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Pattern?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (AdditionalItems?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Items?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (MaxItems?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (MinItems?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (UniqueItems?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Contains?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (AdditionalProperties?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Definitions?.GetCollectionHashCode().GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Properties?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (PatternProperties?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Dependencies?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Const?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Enum?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Format?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (ContentMediaType?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (ContentEncoding?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (If?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Then?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Else?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (AllOf?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (AnyOf?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (OneOf?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Not?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Required?.GetCollectionHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Examples?.GetCollectionHashCode() ?? 0); return(hashCode); } }
public bool Equals(OneOf <A, B, C> other) { if (whichOne != other.whichOne) { return(false); } switch (whichOne) { case OneOf.Choice.A: return(EqComparer <A> .Default.Equals(_aValue, other._aValue)); case OneOf.Choice.B: return(EqComparer <B> .Default.Equals(_bValue, other._bValue)); case OneOf.Choice.C: return(EqComparer <C> .Default.Equals(_cValue, other._cValue)); default: throw new IllegalStateException("Unreachable code"); } }
/// <summary> /// show a confirm dialog like MessageBox of Windows /// </summary> /// <param name="content">the content of dialog</param> /// <param name="title">the title of dialog</param> /// <param name="confirmButtons">the buttons of dialog</param> /// <param name="confirmIcon">the icon of dialog</param> /// <param name="options">the configuration options for dialog</param> /// <returns></returns> public async Task <ConfirmResult> Show( OneOf <string, RenderFragment> content, OneOf <string, RenderFragment> title, ConfirmButtons confirmButtons, ConfirmIcon confirmIcon, ConfirmButtonOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } ConfirmOptions confirmOptions = new ConfirmOptions() { Title = title, Content = content, ConfirmButtons = confirmButtons, ConfirmIcon = confirmIcon, }; #region config button default properties if (options.Button1Props != null) { confirmOptions.Button1Props = options.Button1Props; } if (options.Button2Props != null) { confirmOptions.Button2Props = options.Button2Props; } if (options.Button3Props != null) { confirmOptions.Button3Props = options.Button3Props; } #endregion var modalRef = new ConfirmRef(confirmOptions) { TaskCompletionSource = new TaskCompletionSource <ConfirmResult>() }; if (OnOpenEvent != null) { await OnOpenEvent.Invoke(modalRef); } return(await modalRef.TaskCompletionSource.Task); }
private IDictionary <string, JsonSchemaProperty> GetActualProperties(bool includeInherited) #endif { var ignoredSchema = includeInherited ? null : InheritedSchema; var properties = Properties .Union(AllOf.Where(s => s.ActualSchema != ignoredSchema).SelectMany(s => s.ActualSchema.GetActualProperties(false))) .Union(AnyOf.Where(s => s.ActualSchema != ignoredSchema).SelectMany(s => s.ActualSchema.GetActualProperties(true))) .Union(OneOf.Where(s => s.ActualSchema != ignoredSchema).SelectMany(s => s.ActualSchema.GetActualProperties(true))) .ToList(); // Collapse all duplicated properties, checking that the duplicated ones are compatible var duplicatedProperties = properties .GroupBy(p => p.Key) .Where(g => g.Count() > 1) .Select(g => g.ToList()) .ToList(); var invalidDuplicates = new List <string>(); foreach (var duped in duplicatedProperties) { // Make sure all the properties are the same type as each other so they are compatible primitive types var toKeep = duped[0].Value; if (duped.Any(dupe => dupe.Value.Type != toKeep.Type)) { invalidDuplicates.Add(duped[0].Key); continue; } // All good, so remove the duplicates here foreach (var c in duped.Skip(1)) { properties.Remove(c); } } if (invalidDuplicates.Count > 0) { throw new InvalidOperationException("The properties " + string.Join(", ", invalidDuplicates.Select(key => "'" + key + "'")) + " are defined multiple times and are not the same type."); } #if !LEGACY return(new ReadOnlyDictionary <string, JsonSchemaProperty>(properties.ToDictionary(p => p.Key, p => p.Value))); #else return(new Dictionary <string, JsonSchemaProperty>(properties.ToDictionary(p => p.Key, p => p.Value))); #endif }
/// <inheritdoc/> public override OneOf <T1, T2>?ReadJson(JsonReader reader, Type objectType, OneOf <T1, T2>?existingValue, bool hasExistingValue, JsonSerializer serializer) { var token = JToken.ReadFrom(reader); if (token == null) { return(null); } try { return(new(token.ToObject <T1>() !)); } catch { return(new(token.ToObject <T2>() !)); } }
private Block(OneOf < Plain, Para, LineBlock, CodeBlock, RawBlock, BlockQuote, OrderedList, BulletList, DefinitionList, Header, HorizontalRule, Table, Div, Null > value) : base(value) { }
/// <summary> /// 从当前Bundle组集合中删除一组Bundle的配置 /// </summary> public static void Delete() { if ((EGameBundle)focusGame != EGameBundle.EGB_ALL) { foreach (var OneOf in Setting.ListOfBundles) { if (OneOf.GetHashCode() == SelBundle) { Setting.ListOfBundles.Remove(OneOf); break; } } } else { EditorUtility.DisplayDialog("Warning", "Can not delete a bundle in preview model(ALL)", "Cancel"); } }
public void OneOf2Test() { string str; var item1 = OneOf <Case1, Case2> .Create(new Case1()); Assert.AreEqual("Case1", item1.GetValue(v => v.Name, v => v.Name)); str = ""; item1.Do(v => str = v.Name, v => str = v.Name); Assert.AreEqual("Case1", str); var item2 = OneOf <Case1, Case2> .Create(new Case2()); Assert.AreEqual("Case2", item2.GetValue(v => v.Name, v => v.Name)); str = ""; item2.Do(v => str = v.Name, v => str = v.Name); Assert.AreEqual("Case2", str); }
public void OneOf5Test() { string str; var item1 = OneOf <Case1, Case2, Case3, Case4, Case5> .Create(new Case1()); Assert.AreEqual("Case1", item1.GetValue(v => v.Name, v => v.Name, v => v.Name, v => v.Name, v => v.Name)); str = ""; item1.Do(v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name); Assert.AreEqual("Case1", str); var item2 = OneOf <Case1, Case2, Case3, Case4, Case5> .Create(new Case2()); Assert.AreEqual("Case2", item2.GetValue(v => v.Name, v => v.Name, v => v.Name, v => v.Name, v => v.Name)); str = ""; item2.Do(v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name); Assert.AreEqual("Case2", str); var item3 = OneOf <Case1, Case2, Case3, Case4, Case5> .Create(new Case3()); Assert.AreEqual("Case3", item3.GetValue(v => v.Name, v => v.Name, v => v.Name, v => v.Name, v => v.Name)); str = ""; item3.Do(v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name); Assert.AreEqual("Case3", str); var item4 = OneOf <Case1, Case2, Case3, Case4, Case5> .Create(new Case4()); Assert.AreEqual("Case4", item4.GetValue(v => v.Name, v => v.Name, v => v.Name, v => v.Name, v => v.Name)); str = ""; item4.Do(v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name); Assert.AreEqual("Case4", str); var item5 = OneOf <Case1, Case2, Case3, Case4, Case5> .Create(new Case5()); Assert.AreEqual("Case5", item5.GetValue(v => v.Name, v => v.Name, v => v.Name, v => v.Name, v => v.Name)); str = ""; item5.Do(v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name, v => str = v.Name); Assert.AreEqual("Case5", str); }
public void MergeFrom(ListMatcher other) { if (other == null) { return; } switch (other.MatchPatternCase) { case MatchPatternOneofCase.OneOf: if (OneOf == null) { OneOf = new global::Envoy.Type.Matcher.ValueMatcher(); } OneOf.MergeFrom(other.OneOf); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); }
private static OneOf <AndNode, OrNode, Leaf> ReduceNode(OneOf <AndNode, OrNode, Leaf> node, Dictionary <int, OneOf <AndNode, OrNode, Leaf> > rules) { if (IsLeaf(node) && !IsTrueLeaf(node)) { var subrule = rules[int.Parse(node.AsT2.Value)]; if (IsTrueLeaf(subrule)) { return(subrule); } } else if (IsAnd(node)) { var andRule = node.AsT0; if (andRule.Sequence.All(IsTrueLeaf)) { return(new Leaf(andRule.Sequence.Aggregate(string.Empty, (current, x) => current + x.AsT2.Value))); } for (var j = 0; j < andRule.Sequence.Length; j++) { andRule.Sequence[j] = ReduceNode(andRule.Sequence[j], rules); } return(andRule); } else if (IsOr(node)) { var orRule = node.AsT1; if (orRule.Sequence.All(IsTrueLeaf)) { var left = orRule.Sequence[0].AsT2.Value; var right = orRule.Sequence[1].AsT2.Value; return(new Leaf('(' + left + '|' + right + ')')); } for (var j = 0; j < orRule.Sequence.Length; j++) { orRule.Sequence[j] = ReduceNode(orRule.Sequence[j], rules); } return(orRule); } return(node); }
private async Task <Option <OneOf <PostReadModel, NotApprovedResult <PostReadModel> > > > FindApprovedPost(Expression <Func <PostEntity, bool> > predicate) { var postEntity = await CreateBasePostQuery().FirstOrDefaultAsync(predicate); if (postEntity == null) { return(Option.None <OneOf <PostReadModel, NotApprovedResult <PostReadModel> > >()); } else { var claims = await GetCreatorClaims(postEntity.CreatedBy.Id); var post = postEntity.ToReadModel(claims); var result = post.IsApproved ? OneOf <PostReadModel, NotApprovedResult <PostReadModel> > .FromT0(post) : OneOf <PostReadModel, NotApprovedResult <PostReadModel> > .FromT1(new NotApprovedResult <PostReadModel>(post)); return(Option.Some(result)); } }
public async ValueTask <bool> MoveNextAsync() { if (!_pageInfo.HasNextPage) { return(false); } Current = await NyaaSiService.SearchAsync(_request); if (Current.Match((IAniListError error) => true) .Match(data => data.PageInfo?.HasNextPage != true)) { return(false); } _request.PageNumber += 1; Current.Switch(result => _pageInfo.HasNextPage = result.PageInfo.HasNextPage = result.Data.Count >= 75); return(true); }