/// <summary> /// Returns a <see cref="Version"/> instance where the specified number of components /// are guaranteed to be non-negative. Any applicable negative components are converted to zeros. /// </summary> /// <param name="version">The version to use as a template for the returned value.</param> /// <param name="fieldCount">The number of version components to ensure are non-negative.</param> /// <returns> /// The same as <paramref name="version"/> except with any applicable negative values /// translated to zeros. /// </returns> public static Version EnsureNonNegativeComponents(this Version version, int fieldCount = 4) { Requires.NotNull(version, nameof(version)); Requires.Range(fieldCount >= 0 && fieldCount <= 4, nameof(fieldCount)); int maj = fieldCount >= 1 ? Math.Max(0, version.Major) : version.Major; int min = fieldCount >= 2 ? Math.Max(0, version.Minor) : version.Minor; int bld = fieldCount >= 3 ? Math.Max(0, version.Build) : version.Build; int rev = fieldCount >= 4 ? Math.Max(0, version.Revision) : version.Revision; if (version.Major == maj && version.Minor == min && version.Build == bld && version.Revision == rev) { return(version); } if (rev >= 0) { return(new Version(maj, min, bld, rev)); } else if (bld >= 0) { return(new Version(maj, min, bld)); } else { throw Assumes.NotReachable(); } }
protected virtual object SubstituteValueIfRequired(object value) { Requires.NotNull(value, nameof(value)); ISubstitutedValue substitutedValue; switch (this.direction) { case Direction.ToSubstitutedValue: if (Enum32Substitution.TrySubstituteValue(value, this.resolver, out substitutedValue) || TypeSubstitution.TrySubstituteValue(value, this.resolver, out substitutedValue) || TypeArraySubstitution.TrySubstituteValue(value, this.resolver, out substitutedValue)) { value = substitutedValue; } break; case Direction.ToOriginalValue: if ((substitutedValue = value as ISubstitutedValue) != null) { value = substitutedValue.ActualValue; } break; default: throw Assumes.NotReachable(); } return(value); }
public async ValueTask <T?> GetProxyAsync <T>(ServiceRpcDescriptor serviceDescriptor, ServiceActivationOptions options = default, CancellationToken cancellationToken = default) where T : class { if (this.container.profferedServices.TryGetValue(serviceDescriptor.Moniker, out object?factory)) { if (factory is BrokeredServiceFactory fac1) { T?service = (T?) await fac1(serviceDescriptor.Moniker, options, this, cancellationToken).ConfigureAwait(false); if (service is object) { return(serviceDescriptor.ConstructLocalProxy <T>(service)); } } else if (factory is AuthorizingBrokeredServiceFactory fac2) { #pragma warning disable CA2000 // Dispose objects before losing scope T?service = (T?) await fac2(serviceDescriptor.Moniker, options, this, new AuthorizationServiceClient(new MockAuthorizationService()), cancellationToken).ConfigureAwait(false); #pragma warning restore CA2000 // Dispose objects before losing scope if (service is object) { return(serviceDescriptor.ConstructLocalProxy <T>(service)); } } else { throw Assumes.NotReachable(); } } return(default);
private async Task <T> ExecuteUnderLockCoreAsync <T>(Func <CancellationToken, Task <T> > action, CancellationToken cancellationToken = default) { Requires.NotNull(action, nameof(action)); using (var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, DisposalToken)) { CancellationToken jointCancellationToken = source.Token; try { T result = default; await _semaphore.ExecuteAsync(async() => { result = await action(jointCancellationToken); }, jointCancellationToken); return(result); } catch (Exception ex) { if (!TryTranslateException(ex, cancellationToken, DisposalToken)) { throw; } } } throw Assumes.NotReachable(); }
public async Task ExtensionsAreIdentifiedAsSignedOrUnsigned() { Protocol protocol = Protocol.Default; var opStore = new MemoryCryptoKeyAndNonceStore(); int rpStep = 0; Handle(RPUri).By( async req => { var rp = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories); RegisterMockExtension(rp.Channel); switch (++rpStep) { case 1: var response = await rp.Channel.ReadFromRequestAsync <IndirectSignedResponse>(req, CancellationToken.None); Assert.AreEqual(1, response.SignedExtensions.Count(), "Signed extension should have been received."); Assert.AreEqual(0, response.UnsignedExtensions.Count(), "No unsigned extension should be present."); break; case 2: response = await rp.Channel.ReadFromRequestAsync <IndirectSignedResponse>(req, CancellationToken.None); Assert.AreEqual(0, response.SignedExtensions.Count(), "No signed extension should have been received."); Assert.AreEqual(1, response.UnsignedExtensions.Count(), "Unsigned extension should have been received."); break; default: throw Assumes.NotReachable(); } return(new HttpResponseMessage()); }); Handle(OPUri).By( async req => { var op = new OpenIdProvider(opStore, this.HostFactories); return(await AutoProviderActionAsync(op, req, CancellationToken.None)); }); { var op = new OpenIdProvider(opStore, this.HostFactories); RegisterMockExtension(op.Channel); var redirectingResponse = await op.Channel.PrepareResponseAsync(this.CreateResponseWithExtensions(protocol)); using (var httpClient = this.HostFactories.CreateHttpClient()) { using (var response = await httpClient.GetAsync(redirectingResponse.Headers.Location)) { response.EnsureSuccessStatusCode(); } } op.SecuritySettings.SignOutgoingExtensions = false; redirectingResponse = await op.Channel.PrepareResponseAsync(this.CreateResponseWithExtensions(protocol)); using (var httpClient = this.HostFactories.CreateHttpClient()) { using (var response = await httpClient.GetAsync(redirectingResponse.Headers.Location)) { response.EnsureSuccessStatusCode(); } } } }
public void Remove(object index) { bool intIndexPresent = index is int indexInt && _importsList.IsPresent(indexInt); bool stringIndexPresent = index is string removeImport && _importsList.IsPresent(removeImport); if (intIndexPresent || stringIndexPresent) { string?importRemoved = null; _threadingService.ExecuteSynchronously(() => { return(_projectAccessor.OpenProjectForWriteAsync(ConfiguredProject, project => { Microsoft.Build.Evaluation.ProjectItem importProjectItem; if (index is string removeImport1) { importProjectItem = project.GetItems(ImportItemTypeName) .First(i => string.Equals(removeImport1, i.EvaluatedInclude, StringComparison.OrdinalIgnoreCase)); } else if (index is int indexInt1) { importProjectItem = project.GetItems(ImportItemTypeName) .OrderBy(i => i.EvaluatedInclude) .ElementAt(indexInt1 - 1); } else { // Cannot reach this point, since index has to be Int or String throw Assumes.NotReachable(); } if (importProjectItem.IsImported) { throw new ArgumentException(string.Format(VSResources.ImportsFromTargetCannotBeDeleted, index.ToString()), nameof(index)); } importRemoved = importProjectItem.EvaluatedInclude; project.RemoveItem(importProjectItem); })); }); Assumes.NotNull(importRemoved); OnImportRemoved(importRemoved); } else if (index is string) { throw new ArgumentException(string.Format("{0} - Namespace is not present ", index), nameof(index)); } else { throw new ArgumentException(string.Format("{0} - index is neither an Int nor a String", index), nameof(index)); } }
public void Setup() { this.clientRpc = new JsonRpc(CreateHandler(Stream.Null)); IJsonRpcMessageHandler CreateHandler(Stream pipe) { return(this.Formatter switch { "JSON" => new HeaderDelimitedMessageHandler(pipe, new JsonMessageFormatter()), "MessagePack" => new LengthHeaderMessageHandler(pipe, pipe, new MessagePackFormatter()), _ => throw Assumes.NotReachable(), }); }
/// <summary> /// Pushes a message pump on the current thread that will execute work scheduled using <see cref="Post(SendOrPostCallback, object)"/>. /// </summary> /// <param name="frame">The frame to represent this message pump, which controls when the message pump ends.</param> public void PushFrame(Frame frame) { Requires.NotNull(frame, nameof(frame)); Verify.Operation(this.ownedThreadId == Environment.CurrentManagedThreadId, Strings.PushFromWrongThread); frame.SetOwner(this); using (this.Apply()) { while (frame.Continue) { Message message; lock (this.messageQueue) { // Check again now that we're holding the lock. if (!frame.Continue) { break; } if (this.messageQueue.Count > 0) { message = this.messageQueue.Dequeue(); } else { Monitor.Wait(this.messageQueue); continue; } } if (message.Context != null) { #if EXECUTIONCONTEXT ExecutionContext.Run( message.Context, new ContextCallback(message.Callback), message.State); #else throw Assumes.NotReachable(); #endif } else { // If this throws, we intentionally let it propagate to our caller. // WPF/WinForms SyncContexts will crash the process (perhaps by throwing from their method like this?). // But anyway, throwing from here instead of crashing is more friendly IMO and more easily tested. message.Callback(message.State); } } } }
public async Task AssociateRenegotiateBitLength() { Protocol protocol = Protocol.V20; // The strategy is to make a simple request of the RP to establish an association, // and to more carefully observe the Provider-side of things to make sure that both // the OP and RP are behaving as expected. int providerAttemptCount = 0; HandleProvider( async(op, request) => { op.SecuritySettings.MaximumHashBitLength = 160; // Force OP to reject HMAC-SHA256 switch (++providerAttemptCount) { case 1: // Receive initial request for an HMAC-SHA256 association. var req = (AutoResponsiveRequest)await op.GetRequestAsync(request); var associateRequest = (AssociateRequest)req.RequestMessage; Assert.That(associateRequest, Is.Not.Null); Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA256, associateRequest.AssociationType); // Ensure that the response is a suggestion that the RP try again with HMAC-SHA1 var renegotiateResponse = (AssociateUnsuccessfulResponse)await req.GetResponseMessageAsyncTestHook(CancellationToken.None); Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, renegotiateResponse.AssociationType); return(await op.PrepareResponseAsync(req)); case 2: // Receive second attempt request for an HMAC-SHA1 association. req = (AutoResponsiveRequest)await op.GetRequestAsync(request); associateRequest = (AssociateRequest)req.RequestMessage; Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, associateRequest.AssociationType); // Ensure that the response is a success response. var successResponse = (AssociateSuccessfulResponse)await req.GetResponseMessageAsyncTestHook(CancellationToken.None); Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, successResponse.AssociationType); return(await op.PrepareResponseAsync(req)); default: throw Assumes.NotReachable(); } }); var rp = this.CreateRelyingParty(); var opDescription = new ProviderEndpointDescription(OPUri, protocol.Version); Association association = await rp.AssociationManager.GetOrCreateAssociationAsync(opDescription, CancellationToken.None); Assert.IsNotNull(association, "Association failed to be created."); Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, association.GetAssociationType(protocol)); }
public override void Write(Utf8JsonWriter writer, TagKind value, JsonSerializerOptions options) { int numericValue = value switch { TagKind.General => 0, TagKind.Artist => 1, TagKind.Copyright => 3, TagKind.Character => 4, TagKind.Metadata => 8, _ => throw Assumes.NotReachable(), }; writer.WriteNumberValue(numericValue); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { switch (this.mode) { case Mode.Live: return(base.SendAsync(request, cancellationToken)); case Mode.Recording: return(this.RecordSendAsync(request, cancellationToken)); case Mode.Playback: return(this.PlaybackSendAsync(request, cancellationToken)); default: throw Assumes.NotReachable(); } }
public async Task ExtensionOnlyFacadeLevel() { Protocol protocol = Protocol.V20; int opStep = 0; HandleProvider( async(op, req) => { switch (++opStep) { case 1: var assocRequest = await op.GetRequestAsync(req); return(await op.PrepareResponseAsync(assocRequest)); case 2: var request = (IAnonymousRequest)await op.GetRequestAsync(req); request.IsApproved = true; Assert.IsNotInstanceOf <CheckIdRequest>(request); return(await op.PrepareResponseAsync(request)); default: throw Assumes.NotReachable(); } }); { var rp = this.CreateRelyingParty(); var request = await rp.CreateRequestAsync(GetMockIdentifier(protocol.ProtocolVersion), RPRealmUri, RPUri); request.IsExtensionOnly = true; var redirectRequest = await request.GetRedirectingResponseAsync(); Uri redirectResponseUrl; this.HostFactories.AllowAutoRedirects = false; using (var httpClient = this.HostFactories.CreateHttpClient()) { using (var redirectResponse = await httpClient.GetAsync(redirectRequest.Headers.Location)) { Assert.That(redirectResponse.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); redirectResponseUrl = redirectResponse.Headers.Location; } } IAuthenticationResponse response = await rp.GetResponseAsync(new HttpRequestMessage(HttpMethod.Get, redirectResponseUrl)); Assert.AreEqual(AuthenticationStatus.ExtensionsOnly, response.Status); } }
public void Setup() { (IDuplexPipe, IDuplexPipe)duplex = FullDuplexStream.CreatePipePair(); this.clientRpc = new JsonRpc(CreateHandler(duplex.Item1)); this.clientRpc.StartListening(); this.serverRpc = new JsonRpc(CreateHandler(duplex.Item2)); this.serverRpc.AddLocalRpcTarget(new Server()); this.serverRpc.StartListening(); IJsonRpcMessageHandler CreateHandler(IDuplexPipe pipe) { return(this.Formatter switch { "JSON" => new HeaderDelimitedMessageHandler(pipe, new JsonMessageFormatter()), "MessagePack" => new LengthHeaderMessageHandler(pipe, new MessagePackFormatter()), _ => throw Assumes.NotReachable(), }); }
/// <summary> /// Issues the <see cref="CancellationToken"/> for use by the next asynchronous operation in the sequence, /// and cancels any prior token. /// </summary> /// <remarks> /// <para>This method does not guarantee that prior operations stop executing before /// it returns. It only guarantees that their <see cref="CancellationToken"/> /// will be cancelled. Operations need to use their tokens in an appropriate manner. /// You may still require additional concurrency protections.</para> /// /// <para>This method is thread-safe.</para> /// </remarks> /// <returns>A <see cref="CancellationToken"/> to be used by the commencing asynchronous operation.</returns> /// <exception cref="OperationCanceledException">This object is disposed.</exception> public CancellationToken Next() { var next = new CancellationTokenSource(); // Make sure to obtain the CancellationToken for the next source before exposing the source, // or another thread could dispose of source before we get a chance to access this property. var nextToken = next.Token; // The following block is identical to Interlocked.Exchange, except no replacement is // made if the current field value is null (latch on null). var prior = Volatile.Read(ref _cancellationTokenSource); while (prior is not null) { var candidate = Interlocked.CompareExchange(ref _cancellationTokenSource, next, prior); if (candidate == prior) { break; } else { prior = candidate; } } // Detect and handle the case where the sequence was already disposed if (prior is null) { next.Cancel(); next.Dispose(); nextToken.ThrowIfCancellationRequested(); throw Assumes.NotReachable(); } prior.Cancel(); prior.Dispose(); return(nextToken); }
public static IUdpProxy CreateProxy(ProxyType type, IPEndPoint local, Socks5CreateOption option) { switch (type) { case ProxyType.Plain: { return(new NoneUdpProxy(local)); } case ProxyType.Socks5: { Requires.NotNull(option, nameof(option)); Requires.Argument(option.Address is not null, nameof(option), @"Proxy server is null"); return(new Socks5UdpProxy(local, option)); } default: { throw Assumes.NotReachable(); } } }
public async Task RPOnlyRenegotiatesOnce() { Protocol protocol = Protocol.V20; int opStep = 0; HandleProvider( async(op, req) => { switch (++opStep) { case 1: // Receive initial request. var request = await op.Channel.ReadFromRequestAsync <AssociateRequest>(req, CancellationToken.None); // Send a renegotiate response var renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1; renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA1; return(await op.Channel.PrepareResponseAsync(renegotiateResponse, CancellationToken.None)); case 2: // Receive second-try request = await op.Channel.ReadFromRequestAsync <AssociateRequest>(req, CancellationToken.None); // Send ANOTHER renegotiate response, at which point the DNOI RP should give up. renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256; return(await op.Channel.PrepareResponseAsync(renegotiateResponse, CancellationToken.None)); default: throw Assumes.NotReachable(); } }); var rp = this.CreateRelyingParty(); var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, protocol.Version), CancellationToken.None); Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); }
/// <summary> /// Gets the block mode for an algorithm. /// </summary> /// <param name="algorithm">The algorithm.</param> /// <returns>The block mode.</returns> public static SymmetricAlgorithmMode GetMode(this SymmetricAlgorithm algorithm) { switch (algorithm) { case SymmetricAlgorithm.AesCbc: case SymmetricAlgorithm.AesCbcPkcs7: case SymmetricAlgorithm.Rc2Cbc: case SymmetricAlgorithm.Rc2CbcPkcs7: case SymmetricAlgorithm.DesCbc: case SymmetricAlgorithm.DesCbcPkcs7: case SymmetricAlgorithm.TripleDesCbc: case SymmetricAlgorithm.TripleDesCbcPkcs7: return(SymmetricAlgorithmMode.Cbc); case SymmetricAlgorithm.AesEcb: case SymmetricAlgorithm.AesEcbPkcs7: case SymmetricAlgorithm.DesEcb: case SymmetricAlgorithm.DesEcbPkcs7: case SymmetricAlgorithm.TripleDesEcb: case SymmetricAlgorithm.TripleDesEcbPkcs7: case SymmetricAlgorithm.Rc2Ecb: case SymmetricAlgorithm.Rc2EcbPkcs7: return(SymmetricAlgorithmMode.Ecb); case SymmetricAlgorithm.AesCcm: return(SymmetricAlgorithmMode.Ccm); case SymmetricAlgorithm.AesGcm: return(SymmetricAlgorithmMode.Gcm); case SymmetricAlgorithm.Rc4: return(SymmetricAlgorithmMode.Streaming); default: throw Assumes.NotReachable(); } }
public async Task CreateConnectionAndInvokeOnce() { for (int i = 0; i < Iterations; i++) { (IDuplexPipe, IDuplexPipe)duplex = FullDuplexStream.CreatePipePair(); using var clientRpc = new JsonRpc(CreateHandler(duplex.Item1)); clientRpc.StartListening(); using var serverRpc = new JsonRpc(CreateHandler(duplex.Item2)); serverRpc.AddLocalRpcTarget(new Server()); serverRpc.StartListening(); await clientRpc.InvokeAsync(nameof(Server.NoOp), Array.Empty <object>()); } IJsonRpcMessageHandler CreateHandler(IDuplexPipe pipe) { return(this.Formatter switch { "JSON" => new HeaderDelimitedMessageHandler(pipe, new JsonMessageFormatter()), "MessagePack" => new LengthHeaderMessageHandler(pipe, new MessagePackFormatter()), _ => throw Assumes.NotReachable(), }); }
public bool Contains(object item) { throw Assumes.NotReachable(); }
private async Task ParameterizedAuthenticationTestAsync(Protocol protocol, bool statelessRP, bool sharedAssociation, bool positive, bool immediate, bool tamper) { Requires.That(!statelessRP || !sharedAssociation, null, "The RP cannot be stateless while sharing an association with the OP."); Requires.That(positive || !tamper, null, "Cannot tamper with a negative response."); var securitySettings = new ProviderSecuritySettings(); var cryptoKeyStore = new MemoryCryptoKeyStore(); var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore); Association association = sharedAssociation ? HmacShaAssociationProvider.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, associationStore, securitySettings) : null; int opStep = 0; HandleProvider( async(op, req) => { if (association != null) { var key = cryptoKeyStore.GetCurrentKey( ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1)); op.CryptoKeyStore.StoreKey( ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value); } switch (++opStep) { case 1: var request = await op.Channel.ReadFromRequestAsync <CheckIdRequest>(req, CancellationToken.None); Assert.IsNotNull(request); IProtocolMessage response; if (positive) { response = new PositiveAssertionResponse(request); } else { response = await NegativeAssertionResponse.CreateAsync(request, CancellationToken.None, op.Channel); } return(await op.Channel.PrepareResponseAsync(response)); case 2: if (positive && (statelessRP || !sharedAssociation)) { var checkauthRequest = await op.Channel.ReadFromRequestAsync <CheckAuthenticationRequest>(req, CancellationToken.None); var checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest); checkauthResponse.IsValid = checkauthRequest.IsValid; return(await op.Channel.PrepareResponseAsync(checkauthResponse)); } throw Assumes.NotReachable(); case 3: if (positive && (statelessRP || !sharedAssociation)) { if (!tamper) { // Respond to the replay attack. var checkauthRequest = await op.Channel.ReadFromRequestAsync <CheckAuthenticationRequest>(req, CancellationToken.None); var checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest); checkauthResponse.IsValid = checkauthRequest.IsValid; return(await op.Channel.PrepareResponseAsync(checkauthResponse)); } } throw Assumes.NotReachable(); default: throw Assumes.NotReachable(); } }); { var rp = this.CreateRelyingParty(statelessRP); if (tamper) { rp.Channel.IncomingMessageFilter = message => { var assertion = message as PositiveAssertionResponse; if (assertion != null) { // Alter the Local Identifier between the Provider and the Relying Party. // If the signature binding element does its job, this should cause the RP // to throw. assertion.LocalIdentifier = "http://victim"; } }; } var request = new CheckIdRequest( protocol.Version, OPUri, immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup); if (association != null) { StoreAssociation(rp, OPUri, association); request.AssociationHandle = association.Handle; } request.ClaimedIdentifier = "http://claimedid"; request.LocalIdentifier = "http://localid"; request.ReturnTo = RPUri; request.Realm = RPUri; var redirectRequest = await rp.Channel.PrepareResponseAsync(request); Uri redirectResponse; this.HostFactories.AllowAutoRedirects = false; using (var httpClient = rp.Channel.HostFactories.CreateHttpClient()) { using (var response = await httpClient.GetAsync(redirectRequest.Headers.Location)) { Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); redirectResponse = response.Headers.Location; } } var assertionMessage = new HttpRequestMessage(HttpMethod.Get, redirectResponse); if (positive) { if (tamper) { try { await rp.Channel.ReadFromRequestAsync <PositiveAssertionResponse>(assertionMessage, CancellationToken.None); Assert.Fail("Expected exception {0} not thrown.", typeof(InvalidSignatureException).Name); } catch (InvalidSignatureException) { TestLogger.InfoFormat( "Caught expected {0} exception after tampering with signed data.", typeof(InvalidSignatureException).Name); } } else { var response = await rp.Channel.ReadFromRequestAsync <PositiveAssertionResponse>(assertionMessage, CancellationToken.None); Assert.IsNotNull(response); Assert.AreEqual(request.ClaimedIdentifier, response.ClaimedIdentifier); Assert.AreEqual(request.LocalIdentifier, response.LocalIdentifier); Assert.AreEqual(request.ReturnTo, response.ReturnTo); // Attempt to replay the message and verify that it fails. // Because in various scenarios and protocol versions different components // notice the replay, we can get one of two exceptions thrown. // When the OP notices the replay we get a generic InvalidSignatureException. // When the RP notices the replay we get a specific ReplayMessageException. try { await rp.Channel.ReadFromRequestAsync <PositiveAssertionResponse>(assertionMessage, CancellationToken.None); Assert.Fail("Expected ProtocolException was not thrown."); } catch (ProtocolException ex) { Assert.IsTrue( ex is ReplayedMessageException || ex is InvalidSignatureException, "A {0} exception was thrown instead of the expected {1} or {2}.", ex.GetType(), typeof(ReplayedMessageException).Name, typeof(InvalidSignatureException).Name); } } } else { var response = await rp.Channel.ReadFromRequestAsync <NegativeAssertionResponse>(assertionMessage, CancellationToken.None); Assert.IsNotNull(response); if (immediate) { // Only 1.1 was required to include user_setup_url if (protocol.Version.Major < 2) { Assert.IsNotNull(response.UserSetupUrl); } } else { Assert.IsNull(response.UserSetupUrl); } } } }
public IEnumerator <object> GetEnumerator() { return(Assumes.NotReachable <IEnumerator <object> >()); }
IEnumerator IEnumerable.GetEnumerator() { return(Assumes.NotReachable <IEnumerator>()); }
private void Write(IImportSatisfiabilityConstraint importConstraint) { using (this.Trace(nameof(IImportSatisfiabilityConstraint))) { ConstraintTypes type; if (importConstraint is ImportMetadataViewConstraint) { type = ConstraintTypes.ImportMetadataViewConstraint; } else if (importConstraint is ExportTypeIdentityConstraint) { type = ConstraintTypes.ExportTypeIdentityConstraint; } else if (importConstraint is PartCreationPolicyConstraint) { type = ConstraintTypes.PartCreationPolicyConstraint; } else if (importConstraint is ExportMetadataValueImportConstraint) { type = ConstraintTypes.ExportMetadataValueImportConstraint; } else { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Strings.ImportConstraintTypeNotSupported, importConstraint.GetType().FullName)); } this.writer !.Write((byte)type); switch (type) { case ConstraintTypes.ImportMetadataViewConstraint: var importMetadataViewConstraint = (ImportMetadataViewConstraint)importConstraint; this.WriteCompressedUInt((uint)importMetadataViewConstraint.Requirements.Count); foreach (var item in importMetadataViewConstraint.Requirements) { this.Write(item.Key); this.Write(item.Value.MetadatumValueTypeRef); this.writer.Write(item.Value.IsMetadataumValueRequired); } break; case ConstraintTypes.ExportTypeIdentityConstraint: var exportTypeIdentityConstraint = (ExportTypeIdentityConstraint)importConstraint; this.Write(exportTypeIdentityConstraint.TypeIdentityName); break; case ConstraintTypes.PartCreationPolicyConstraint: var partCreationPolicyConstraint = (PartCreationPolicyConstraint)importConstraint; this.Write(partCreationPolicyConstraint.RequiredCreationPolicy); break; case ConstraintTypes.ExportMetadataValueImportConstraint: var exportMetadataValueImportConstraint = (ExportMetadataValueImportConstraint)importConstraint; this.Write(exportMetadataValueImportConstraint.Name); this.WriteObject(exportMetadataValueImportConstraint.Value); break; default: throw Assumes.NotReachable(); } } }
public IEnumerator <object> GetEnumerator() { throw Assumes.NotReachable(); }
public bool Remove(object item) { throw Assumes.NotReachable(); }
/// <summary> /// Creates a new <see cref="CancellationToken"/> that is canceled when any of a set of other tokens are canceled. /// </summary> /// <param name="original">The first token.</param> /// <param name="others">The additional tokens.</param> /// <returns>A struct that contains the combined <see cref="CancellationToken"/> and a means to release memory when you're done using it.</returns> public static CombinedCancellationToken CombineWith(this CancellationToken original, params CancellationToken[] others) { Requires.NotNull(others, nameof(others)); if (original.IsCancellationRequested) { return(new CombinedCancellationToken(original)); } int cancelableTokensCount = original.CanBeCanceled ? 1 : 0; foreach (CancellationToken other in others) { if (other.IsCancellationRequested) { return(new CombinedCancellationToken(other)); } if (other.CanBeCanceled) { cancelableTokensCount++; } } switch (cancelableTokensCount) { case 0: return(new CombinedCancellationToken(CancellationToken.None)); case 1: if (original.CanBeCanceled) { return(new CombinedCancellationToken(original)); } foreach (CancellationToken other in others) { if (other.CanBeCanceled) { return(new CombinedCancellationToken(other)); } } throw Assumes.NotReachable(); case 2: CancellationToken first = CancellationToken.None; CancellationToken second = CancellationToken.None; if (original.CanBeCanceled) { first = original; } foreach (CancellationToken other in others) { if (other.CanBeCanceled) { if (first.CanBeCanceled) { second = other; } else { first = other; } } } Assumes.True(first.CanBeCanceled && second.CanBeCanceled); // Call the overload that takes two CancellationTokens explicitly to avoid an array allocation. return(new CombinedCancellationToken(CancellationTokenSource.CreateLinkedTokenSource(first, second))); default: // This is the most expensive path to take since it involves allocating memory and requiring disposal. // Before this point we've checked every condition that would allow us to avoid it. var cancelableTokens = new CancellationToken[cancelableTokensCount]; int i = 0; foreach (CancellationToken other in others) { if (other.CanBeCanceled) { cancelableTokens[i++] = other; } } return(new CombinedCancellationToken(CancellationTokenSource.CreateLinkedTokenSource(cancelableTokens))); } }
private TypeRef(Resolver resolver, Type type, bool shallow = false) { Requires.NotNull(resolver, nameof(resolver)); Requires.NotNull(type, nameof(type)); this.resolver = resolver; this.resolvedType = type; this.AssemblyName = GetNormalizedAssemblyName(type.GetTypeInfo().Assembly.GetName()); this.assemblyId = resolver.GetStrongAssemblyIdentity(type.GetTypeInfo().Assembly, this.AssemblyName); this.TypeFlags |= type.IsArray ? TypeRefFlags.Array : TypeRefFlags.None; this.TypeFlags |= type.GetTypeInfo().IsValueType ? TypeRefFlags.IsValueType : TypeRefFlags.None; this.ElementTypeRef = PartDiscovery.TryGetElementTypeFromMany(type, out var elementType) ? TypeRef.Get(elementType, resolver) : this; var arrayElementType = this.ArrayElementType; Requires.Argument(!arrayElementType.IsGenericParameter, nameof(type), "Generic parameters are not supported."); this.MetadataToken = arrayElementType.GetTypeInfo().MetadataToken; this.FullName = (arrayElementType.GetTypeInfo().IsGenericType ? arrayElementType.GetGenericTypeDefinition() : arrayElementType).FullName ?? throw Assumes.NotReachable(); this.GenericTypeParameterCount = arrayElementType.GetTypeInfo().GenericTypeParameters.Length; this.GenericTypeArguments = arrayElementType.GenericTypeArguments != null && arrayElementType.GenericTypeArguments.Length > 0 ? arrayElementType.GenericTypeArguments.Where(t => !(shallow && t.IsGenericParameter)).Select(t => new TypeRef(resolver, t, shallow: true)).ToImmutableArray() : ImmutableArray <TypeRef> .Empty; if (!shallow) { this.baseTypes = arrayElementType.EnumTypeBaseTypesAndInterfaces().Skip(1).Select(t => new TypeRef(resolver, t, shallow: true)).ToImmutableArray(); } }
public void NotReachableOfT() { Assert.ThrowsAny <Exception>(() => Assumes.NotReachable <int>()); Assert.ThrowsAny <Exception>(() => Assumes.NotReachable <object>()); }
IEnumerator IEnumerable.GetEnumerator() { throw Assumes.NotReachable(); }
public void CopyTo(object[] array, int arrayIndex) { throw Assumes.NotReachable(); }