private static void ShowGraph(Fx fx) { for (int x = 0; x < 10; x++) { Console.WriteLine(fx(x)); } }
public GoodsTransferSearchController(GoodsCache goodsCache, Fx.Domain.Base.IService.ISiteSearch<GoodsTransferInfo> transferGoodsSearch, Fx.Domain.Base.IService.IGoodsSearch<GoodsTransferInfo> goodsSearch) { this.goodsCache = goodsCache; this.transferGoodsSearch = transferGoodsSearch; this.goodsSearch = goodsSearch; }
public HouseTransferSearchController(HouseCache houseCache, Fx.Domain.Base.IService.ISiteSearch<HouseTransferInfo> transferHouseSearch, Fx.Domain.Base.IService.IHouseSearch<HouseTransferInfo> houseSearch) { this.houseCache = houseCache; this.transferHouseSearch = transferHouseSearch; this.houseSearch = houseSearch; }
/// <summary> /// 默认构造函数 /// </summary> /// <param name="goodsCache">物品缓存</param> /// <param name="siteGoodsSearch">大频道帖子关键字查询接口</param> /// <param name="goodsSearch">物品交易检索接口</param> public GoodsBuySearchController(GoodsCache goodsCache, Fx.Domain.Base.IService.ISiteSearch<GoodsBuyInfo> siteGoodsSearch, Fx.Domain.Base.IService.IGoodsSearch<GoodsBuyInfo> goodsSearch) { this.goodsCache = goodsCache; this.siteGoodsSearch = siteGoodsSearch; this.goodsSearch = goodsSearch; }
/// <summary> /// 默认构造函数 /// </summary> /// <param name="carCache">车辆缓存</param> /// <param name="siteCarSearch">车辆帖子关键字查询接口</param> /// <param name="carSearch">车辆交易检索接口</param> public CarTransferSearchController(CarCache carCache, Fx.Domain.Base.IService.ISiteSearch<CarTransferInfo> siteCarSearch, Fx.Domain.Base.IService.ICarSearch<CarTransferInfo> carSearch) { this.carCache = carCache; this.siteCarSearch = siteCarSearch; this.carSearch = carSearch; }
void CreatePhong(Fx.ColladaPhong phong, H1.Tags.shader_transparent_chicago_group shader) { if (shader.Maps.Count > 0 && !shader.Maps[0].Map.Datum.IsNull) { phong.Diffuse.Color = null; phong.Diffuse.Texture = CreateTexture(shader.Maps[0].Map.Datum, 0); } }
/// <summary> /// 默认构造函数 /// </summary> /// <param name="houseCache">房屋缓存</param> /// <param name="siteHouseSearch">大频道帖子关键字查询接口</param> /// <param name="houseSearch">房屋交易检索接口</param> public HouseBuySearchController(HouseCache houseCache, Fx.Domain.Base.IService.ISiteSearch<HouseBuyInfo> siteHouseSearch, Fx.Domain.Base.IService.IHouseSearch<HouseBuyInfo> houseSearch) { this.houseCache = houseCache; this.siteHouseSearch = siteHouseSearch; this.houseSearch = houseSearch; }
public CarBuySearchController(CarCache carCache, Fx.Domain.Base.IService.ISiteSearch<CarBuyInfo> BuyCarSearch, Fx.Domain.Base.IService.ICarSearch<CarBuyInfo> carSearch, SiteCache siteCache) { this.carCache = carCache; this.BuyCarSearch = BuyCarSearch; this.carSearch = carSearch; }
void CreatePhong(Fx.ColladaPhong phong, H1.Tags.shader_model_group shader) { if (shader.BaseMap.Datum != DatumIndex.Null) { phong.Diffuse.Color = null; phong.Diffuse.Texture = CreateTexture(shader.BaseMap.Datum, 0); } phong.Specular.Color.SetColor(shader.PerpendicularTintColor, 1); }
void CreatePhong(Fx.ColladaPhong phong, H1.Tags.shader_transparent_chicago_extended_group shader) { DatumIndex bitmap_datum = DatumIndex.Null; if (shader._4StageMaps.Count > 0) bitmap_datum = shader._4StageMaps[0].Map.Datum; else if (shader._2StageMaps.Count > 0) bitmap_datum = shader._2StageMaps[0].Map.Datum; if (bitmap_datum != DatumIndex.Null) { phong.Diffuse.Color = null; phong.Diffuse.Texture = CreateTexture(bitmap_datum, 0); } }
void CreatePhong(Fx.ColladaPhong phong, H1.Tags.shader_environment_group shader) { if (shader.BaseMap.Datum == DatumIndex.Null) phong.Diffuse.Color.SetColor(shader.MaterialColor, 1); else { phong.Diffuse.Color = null; phong.Diffuse.Texture = CreateTexture(shader.BaseMap.Datum, 0); } if (shader.Flags.Test(1) && (shader.BumpMap.Datum != DatumIndex.Null)) { phong.Transparent.Color = null; phong.Transparent.Texture = CreateTexture(shader.BumpMap.Datum, 0); phong.Transparent.Opaque = Enums.ColladaFXOpaqueEnum.A_ONE; } phong.Specular.Color.SetColor(shader.PerpendicularColor, 1); }
// Process Welcome message from the neighbor public void Welcome(IPeerNeighbor neighbor, WelcomeInfo welcomeInfo) { // Don't bother processing the message if Connector has closed if (this.state != State.Opened) { return; } PeerCloseReason closeReason = PeerCloseReason.None; // Welcome message should only be received when neighbor is the initiator // and is in connecting state --we accept in closed state to account for // timeouts. if (!neighbor.IsInitiator || !welcomeInfo.HasBody() || (neighbor.State != PeerNeighborState.Connecting && neighbor.State != PeerNeighborState.Closed)) { closeReason = PeerCloseReason.InvalidNeighbor; } // Remove the entry from timer table for this neighbor. If entry is still present, // RemoveTimer returns true. Otherwise, neighbor is already being closed and // welcome message will be ignored. else if (RemoveTimer(neighbor)) { // It is allowed for a node to have more than MaxNeighbours when processing a welcome message // Determine if neighbor should be accepted. PeerCloseReason closeReason2; IPeerNeighbor neighborToClose; string action = PeerStrings.RefuseAction; ValidateNeighbor(neighbor, welcomeInfo.NodeId, out neighborToClose, out closeReason2, out action); if (neighbor != neighborToClose) { // Neighbor should be accepted AddReferrals validates the referrals, // if they are valid then the neighbor is accepted. if (this.maintainer.AddReferrals(welcomeInfo.Referrals, neighbor)) { if (!neighbor.TrySetState(PeerNeighborState.Connected)) { if (!(neighbor.State >= PeerNeighborState.Faulted)) { throw Fx.AssertAndThrow("Neighbor state expected to be >= Faulted; it is " + neighbor.State.ToString()); } } if (neighborToClose != null) { // The other neighbor should be closed SendTerminatingMessage(neighborToClose, action, closeReason2); this.neighborManager.CloseNeighbor(neighborToClose, closeReason2, PeerCloseInitiator.LocalNode); } } else { // Referrals were invalid this node is suspicous closeReason = PeerCloseReason.InvalidNeighbor; } } else { closeReason = closeReason2; } } if (closeReason != PeerCloseReason.None) { SendTerminatingMessage(neighbor, PeerStrings.DisconnectAction, closeReason); this.neighborManager.CloseNeighbor(neighbor, closeReason, PeerCloseInitiator.LocalNode); } }
public TokenProviderAdapter(AmqpEventHubClient eventHubClient) { Fx.Assert(eventHubClient != null, "tokenProvider cannot be null"); this.eventHubClient = eventHubClient; }
private void AddSupportingTokenAuthenticators(SupportingTokenParameters supportingTokenParameters, bool isOptional, IList <SupportingTokenAuthenticatorSpecification> authenticatorSpecList) { for (int i = 0; i < supportingTokenParameters.Endorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Endorsing[i], SecurityTokenAttachmentMode.Endorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Endorsing, supportingTokenParameters.Endorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEndorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEndorsing[i], SecurityTokenAttachmentMode.SignedEndorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEndorsing, supportingTokenParameters.SignedEndorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEncrypted.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEncrypted[i], SecurityTokenAttachmentMode.SignedEncrypted); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEncrypted, supportingTokenParameters.SignedEncrypted[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.Signed.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Signed[i], SecurityTokenAttachmentMode.Signed); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Signed, supportingTokenParameters.Signed[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } }
protected override void Execute(NativeActivityContext context) { Fx.Assert(this.Trigger != null, "We validate that the trigger is not null in Pick.CacheMetadata"); context.ScheduleActivity(this.Trigger, new CompletionCallback(OnTriggerCompleted)); }
AsyncCompletionResult WriteAsync(WriteAsyncState state) { Fx.Assert(state != null && state.Arguments != null, "Invalid WriteAsyncState parameter."); if (state.Arguments.Count == 0) { return(AsyncCompletionResult.Completed); } byte[] buffer = state.Arguments.Buffer; int offset = state.Arguments.Offset; int count = state.Arguments.Count; ByteBuffer currentBuffer = this.GetCurrentBuffer(); while (count > 0) { if (currentBuffer == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.WriteAsyncWithoutFreeBuffer))); } int freeBytes = currentBuffer.FreeBytes; // space left in the CurrentBuffer if (freeBytes > 0) { if (freeBytes > count) { freeBytes = count; } currentBuffer.CopyData(buffer, offset, freeBytes); offset += freeBytes; count -= freeBytes; } if (currentBuffer.FreeBytes == 0) { this.DequeueAndFlush(currentBuffer, onAsyncFlushComplete); // We might need to increase the number of buffers available // if there is more data to be written or no buffer is available. if (count > 0 || this.buffers.Count == 0) { this.AdjustBufferSize(); } } //Update state for any pending writes. state.Arguments.Offset = offset; state.Arguments.Count = count; // We can complete synchronously only // if there a buffer available for writes. currentBuffer = this.GetCurrentBuffer(); if (currentBuffer == null) { if (this.buffers.TryUnlock()) { return(AsyncCompletionResult.Queued); } currentBuffer = this.GetCurrentBuffer(); } } return(AsyncCompletionResult.Completed); }
public AuthenticationSchemesBindingParameter(AuthenticationSchemes authenticationSchemes) { Fx.Assert(authenticationSchemes != AuthenticationSchemes.None, "AuthenticationSchemesBindingParameter should not be added for AuthenticationSchemes.None."); AuthenticationSchemes = authenticationSchemes; }
public async Task CQRS_ShouldBe_NormalAsync() { var commandbus = Fx.Resolve <ICommandBus>(); await commandbus.SendAsync(new SetVersionCmd(1)); }
async Task ExecuteAsync( HttpMethod httpMethod, Uri requestUri, Func <HttpRequestMessage, CancellationToken, Task> modifyRequestMessageAsync, Func <HttpResponseMessage, bool> isSuccessful, Func <HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync, IDictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > > errorMappingOverrides, CancellationToken cancellationToken) { IDictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > > mergedErrorMapping = this.MergeErrorMapping(errorMappingOverrides); using (var msg = new HttpRequestMessage(httpMethod, requestUri)) { if (!this.usingX509ClientCert) { msg.Headers.Add(HttpRequestHeader.Authorization.ToString(), this.authenticationHeaderProvider.GetAuthorizationHeader()); } #if !WINDOWS_UWP && !PCL msg.Headers.UserAgent.ParseAdd(Utils.GetClientVersion()); #endif if (modifyRequestMessageAsync != null) { await modifyRequestMessageAsync(msg, cancellationToken); } // TODO: pradeepc - find out the list of exceptions that HttpClient can throw. HttpResponseMessage responseMsg; try { responseMsg = await this.httpClientObj.SendAsync(msg, cancellationToken); if (responseMsg == null) { throw new InvalidOperationException("The response message was null when executing operation {0}.".FormatInvariant(httpMethod)); } if (isSuccessful(responseMsg)) { if (processResponseMessageAsync != null) { await processResponseMessageAsync(responseMsg, cancellationToken); } } } catch (AggregateException ex) { var innerExceptions = ex.Flatten().InnerExceptions; if (innerExceptions.Any(Fx.IsFatal)) { throw; } // Apparently HttpClient throws AggregateException when a timeout occurs. // TODO: pradeepc - need to confirm this with ASP.NET team if (innerExceptions.Any(e => e is TimeoutException)) { throw new IotHubCommunicationException(ex.Message, ex); } throw new IotHubException(ex.Message, ex); } catch (TimeoutException ex) { throw new IotHubCommunicationException(ex.Message, ex); } catch (IOException ex) { throw new IotHubCommunicationException(ex.Message, ex); } catch (HttpRequestException ex) { throw new IotHubCommunicationException(ex.Message, ex); } catch (TaskCanceledException ex) { // Unfortunately TaskCanceledException is thrown when HttpClient times out. if (cancellationToken.IsCancellationRequested) { throw new IotHubException(ex.Message, ex); } throw new IotHubCommunicationException(string.Format(CultureInfo.InvariantCulture, "The {0} operation timed out.", httpMethod), ex); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw new IotHubException(ex.Message, ex); } if (!isSuccessful(responseMsg)) { Exception mappedEx = await MapToExceptionAsync(responseMsg, mergedErrorMapping); throw mappedEx; } } }
public void MockRepository_ShouldBe_Resolved() => Assert.NotNull(Fx.Resolve <IMockRepository>());
public void FaultToleranceProcessor_ShouldBe_Resolved() => Assert.NotNull(Fx.Resolve <IFaultToleranceProcessor>());
public void Downloader_ShouldBe_Resolved() => Assert.NotNull(Fx.Resolve <IDownloader>());
public async Task Alarmer_ShouldBe_ResolvedAsync() { var alarmer = Fx.Resolve <IAlarmer>(); await alarmer.AlarmAdminUsingWechatAsync("内存爆炸", "告警"); }
public void ObjectIdGenerator_ShouldBe_Resolved() => Assert.NotNull(Fx.Resolve <IObjectIdGenerator>());
public void IterateStateReferences() { Address address = Fx.Address1; string stateKey = address.ToHex().ToLowerInvariant(); var addresses = new[] { address }.ToImmutableHashSet(); IImmutableSet <string> stateKeys = addresses .Select(a => a.ToHex().ToLowerInvariant()) .ToImmutableHashSet(); Block <DumbAction> block1 = Fx.Block1; Block <DumbAction> block2 = Fx.Block2; Block <DumbAction> block3 = Fx.Block3; Transaction <DumbAction> tx4 = Fx.MakeTransaction( new[] { new DumbAction(address, "foo") } ); Block <DumbAction> block4 = TestUtils.MineNext(block3, new[] { tx4 }); Transaction <DumbAction> tx5 = Fx.MakeTransaction( new[] { new DumbAction(address, "bar") } ); Block <DumbAction> block5 = TestUtils.MineNext(block4, new[] { tx5 }); Assert.Empty(Fx.Store.IterateStateReferences(Fx.StoreChainId, stateKey)); Fx.Store.StoreStateReference( Fx.StoreChainId, stateKeys, block4.Hash, block4.Index ); Assert.Equal( new[] { Tuple.Create(block4.Hash, block4.Index) }, Fx.Store.IterateStateReferences(Fx.StoreChainId, stateKey) ); Fx.Store.StoreStateReference( Fx.StoreChainId, stateKeys, block5.Hash, block5.Index ); Assert.Equal( new[] { Tuple.Create(block5.Hash, block5.Index), Tuple.Create(block4.Hash, block4.Index), }, Fx.Store.IterateStateReferences(Fx.StoreChainId, stateKey) ); Fx.Store.StoreStateReference(Fx.StoreChainId, stateKeys, block3.Hash, block3.Index); Fx.Store.StoreStateReference(Fx.StoreChainId, stateKeys, block2.Hash, block2.Index); Fx.Store.StoreStateReference(Fx.StoreChainId, stateKeys, block1.Hash, block1.Index); Assert.Equal( new[] { Tuple.Create(block5.Hash, block5.Index), Tuple.Create(block4.Hash, block4.Index), Tuple.Create(block3.Hash, block3.Index), Tuple.Create(block2.Hash, block2.Index), Tuple.Create(block1.Hash, block1.Index), }, Fx.Store.IterateStateReferences(Fx.StoreChainId, stateKey) ); Assert.Equal( new[] { Tuple.Create(block5.Hash, block5.Index), Tuple.Create(block4.Hash, block4.Index), }, Fx.Store.IterateStateReferences( Fx.StoreChainId, stateKey, lowestIndex: block4.Index ) ); Assert.Equal( new[] { Tuple.Create(block2.Hash, block2.Index), Tuple.Create(block1.Hash, block1.Index), }, Fx.Store.IterateStateReferences( Fx.StoreChainId, stateKey, highestIndex: block2.Index) ); Assert.Equal( new[] { Tuple.Create(block3.Hash, block3.Index), Tuple.Create(block2.Hash, block2.Index), }, Fx.Store.IterateStateReferences( Fx.StoreChainId, stateKey, highestIndex: block3.Index, limit: 2) ); Assert.Throws <ArgumentException>(() => { Fx.Store.IterateStateReferences( Fx.StoreChainId, stateKey, highestIndex: block2.Index, lowestIndex: block3.Index); }); }
public DataProviderEntry(Func <string> dataProvider) { Fx.Assert(dataProvider != null, "dataProvider required"); this.dataProvider = dataProvider; this.resolvedData = null; }
public void ForkStateReferences(int branchPointIndex) { Address address1 = Fx.Address1; Address address2 = Fx.Address2; string stateKey1 = address1.ToHex().ToLowerInvariant(); string stateKey2 = address2.ToHex().ToLowerInvariant(); Block <DumbAction> prevBlock = Fx.Block3; Guid targetChainId = Guid.NewGuid(); Transaction <DumbAction> tx1 = Fx.MakeTransaction( new List <DumbAction>(), new HashSet <Address> { address1 }.ToImmutableHashSet()); Transaction <DumbAction> tx2 = Fx.MakeTransaction( new List <DumbAction>(), new HashSet <Address> { address2 }.ToImmutableHashSet()); var txs1 = new[] { tx1 }; var blocks = new List <Block <DumbAction> > { TestUtils.MineNext(prevBlock, txs1), }; blocks.Add(TestUtils.MineNext(blocks[0], txs1)); blocks.Add(TestUtils.MineNext(blocks[1], txs1)); HashSet <Address> updatedAddresses; foreach (Block <DumbAction> block in blocks) { updatedAddresses = new HashSet <Address> { address1 }; Fx.Store.StoreStateReference( Fx.StoreChainId, updatedAddresses.Select(a => a.ToHex().ToLowerInvariant()).ToImmutableHashSet(), block.Hash, block.Index ); } var txs2 = new[] { tx2 }; blocks.Add(TestUtils.MineNext(blocks[2], txs2)); updatedAddresses = new HashSet <Address> { address2 }; Fx.Store.StoreStateReference( Fx.StoreChainId, updatedAddresses.Select(a => a.ToHex().ToLowerInvariant()).ToImmutableHashSet(), blocks[3].Hash, blocks[3].Index ); var branchPoint = blocks[branchPointIndex]; Fx.Store.ForkStateReferences( Fx.StoreChainId, targetChainId, branchPoint); var actual = Fx.Store.LookupStateReference( Fx.StoreChainId, stateKey1, blocks[3]); Assert.Equal( Tuple.Create(blocks[2].Hash, blocks[2].Index), Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey1, blocks[3])); Assert.Equal( Tuple.Create(blocks[3].Hash, blocks[3].Index), Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey2, blocks[3])); Assert.Equal( Tuple.Create(blocks[branchPointIndex].Hash, blocks[branchPointIndex].Index), Fx.Store.LookupStateReference(targetChainId, stateKey1, blocks[3])); Assert.Null( Fx.Store.LookupStateReference(targetChainId, stateKey2, blocks[3])); }
public ContextAndGenerationKey(UniqueId contextId, UniqueId generation) { Fx.Assert(contextId != null && generation != null, ""); ContextId = contextId; Generation = generation; }
private async Task <WebSocketContext> AcceptWebSocketAsync(HttpContext context, CancellationToken token) { //if (TD.WebSocketConnectionAcceptStartIsEnabled()) //{ // TD.WebSocketConnectionAcceptStart(this.httpRequestContext.EventTraceActivity); //} if (!context.WebSockets.IsWebSocketRequest) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Features.Get <IHttpResponseFeature>().ReasonPhrase = SR.WebSocketEndpointOnlySupportWebSocketError; return(null); } try { using (token.Register(() => { context.Abort(); })) { string negotiatedProtocol = null; // match client protocols vs server protocol foreach (string protocol in context.WebSockets.WebSocketRequestedProtocols) { if (string.Compare(protocol, _httpSettings.WebSocketSettings.SubProtocol, StringComparison.OrdinalIgnoreCase) == 0) { negotiatedProtocol = protocol; break; } } if (negotiatedProtocol == null) { string errorMessage = SR.Format(SR.WebSocketInvalidProtocolNotInClientList, _httpSettings.WebSocketSettings.SubProtocol, string.Join(", ", context.WebSockets.WebSocketRequestedProtocols)); Fx.Exception.AsWarning(new WebException(errorMessage)); context.Response.StatusCode = (int)HttpStatusCode.UpgradeRequired; context.Features.Get <IHttpResponseFeature>().ReasonPhrase = SR.WebSocketEndpointOnlySupportWebSocketError; return(null); } WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(negotiatedProtocol); return(new AspNetCoreWebSocketContext(context, webSocket)); } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } if (token.IsCancellationRequested) { throw Fx.Exception.AsError(new TimeoutException(SR.AcceptWebSocketTimedOutError)); } WebSocketHelper.ThrowCorrectException(ex); throw; } }
private Collection <XmlElement> NormalizeAdditionalParameters(Collection <XmlElement> additionalParameters, TrustDriver driver, bool clientSideClaimTypeRequirementsSpecified) { // Ensure STS trust version is one of the currently supported versions: Feb 05 / Trust 1.3 Fx.Assert(((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) || (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)), "Unsupported trust version specified for the STS."); // We have a mismatch. Make a local copy of additionalParameters for making any potential modifications // as part of normalization Collection <XmlElement> tmpCollection = new Collection <XmlElement>(); foreach (XmlElement e in additionalParameters) { tmpCollection.Add(e); } // 1. For Trust 1.3 EncryptionAlgorithm, CanonicalizationAlgorithm and KeyWrapAlgorithm should not be // specified as top-level element if "SecondaryParameters" element already specifies this. if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13) { Fx.Assert(driver.GetType() == typeof(WSTrustDec2005.DriverDec2005), "Invalid Trust Driver specified for Trust 1.3."); XmlElement encryptionAlgorithmElement = null; XmlElement canonicalizationAlgorithmElement = null; XmlElement keyWrapAlgorithmElement = null; XmlElement secondaryParameter = null; for (int i = 0; i < tmpCollection.Count; ++i) { string algorithm; if (driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithm)) { encryptionAlgorithmElement = tmpCollection[i]; } else if (driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithm)) { canonicalizationAlgorithmElement = tmpCollection[i]; } else if (driver.IsKeyWrapAlgorithmElement(tmpCollection[i], out algorithm)) { keyWrapAlgorithmElement = tmpCollection[i]; } else if (((WSTrustDec2005.DriverDec2005)driver).IsSecondaryParametersElement(tmpCollection[i])) { secondaryParameter = tmpCollection[i]; } } if (secondaryParameter != null) { foreach (XmlNode node in secondaryParameter.ChildNodes) { XmlElement child = node as XmlElement; if (child != null) { string algorithm = null; if (driver.IsEncryptionAlgorithmElement(child, out algorithm) && (encryptionAlgorithmElement != null)) { tmpCollection.Remove(encryptionAlgorithmElement); } else if (driver.IsCanonicalizationAlgorithmElement(child, out algorithm) && (canonicalizationAlgorithmElement != null)) { tmpCollection.Remove(canonicalizationAlgorithmElement); } else if (driver.IsKeyWrapAlgorithmElement(child, out algorithm) && (keyWrapAlgorithmElement != null)) { tmpCollection.Remove(keyWrapAlgorithmElement); } } } } } // 2. Check for Mismatch. // a. Trust Feb 2005 -> Trust 1.3. do the following, // (i) Copy EncryptionAlgorithm and CanonicalizationAlgorithm as the top-level elements. // Note, this is in contradiction to step 1. But we don't have a choice here as we cannot say from the // Additional Parameters section in the config what came from the service and what came from the client. // (ii) Convert SignWith and EncryptWith elements to Trust 1.3 namespace. // b. For Trust 1.3 -> Trust Feb 2005, do the following, // (i) Find EncryptionAlgorithm, CanonicalizationAlgorithm from inside the "SecondaryParameters" element. // If found, then promote these as the top-level elements replacing the existing values. // (ii) Convert the SignWith and EncryptWith elements to the Trust Feb 2005 namespace and drop the KeyWrapAlgorithm // element. // make an optimistic check to detect mismatched trust-versions between STS and RP bool mismatch = (((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) && !CollectionContainsElementsWithTrustNamespace(additionalParameters, TrustFeb2005Strings.Namespace)) || ((driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13) && !CollectionContainsElementsWithTrustNamespace(additionalParameters, TrustDec2005Strings.Namespace))); // if no mismatch, return unmodified collection if (!mismatch) { return(tmpCollection); } // 2.a // If we are talking to a Trust 1.3 STS, replace any Feb '05 algorithm parameters with their Trust 1.3 counterparts if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13) { SecurityStandardsManager trustFeb2005StandardsManager = SecurityStandardsManager.DefaultInstance; // the following cast is guaranteed to succeed WSTrustFeb2005.DriverFeb2005 trustFeb2005Driver = (WSTrustFeb2005.DriverFeb2005)trustFeb2005StandardsManager.TrustDriver; for (int i = 0; i < tmpCollection.Count; i++) { string algorithmParameter = string.Empty; if (trustFeb2005Driver.IsSignWithElement(tmpCollection[i], out algorithmParameter)) { tmpCollection[i] = driver.CreateSignWithElement(algorithmParameter); } else if (trustFeb2005Driver.IsEncryptWithElement(tmpCollection[i], out algorithmParameter)) { tmpCollection[i] = driver.CreateEncryptWithElement(algorithmParameter); } else if (trustFeb2005Driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithmParameter)) { tmpCollection[i] = driver.CreateEncryptionAlgorithmElement(algorithmParameter); } else if (trustFeb2005Driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithmParameter)) { tmpCollection[i] = driver.CreateCanonicalizationAlgorithmElement(algorithmParameter); } } } else { // 2.b // We are talking to a Feb 05 STS. Filter out any SecondaryParameters element. Collection <XmlElement> childrenToPromote = null; WSSecurityTokenSerializer trust13Serializer = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11, TrustVersion.WSTrust13, SecureConversationVersion.WSSecureConversation13, true, null, null, null); SecurityStandardsManager trust13StandardsManager = new SecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, trust13Serializer); // the following cast is guaranteed to succeed WSTrustDec2005.DriverDec2005 trust13Driver = (WSTrustDec2005.DriverDec2005)trust13StandardsManager.TrustDriver; foreach (XmlElement parameter in tmpCollection) { // check if SecondaryParameters is present if (trust13Driver.IsSecondaryParametersElement(parameter)) { childrenToPromote = new Collection <XmlElement>(); // walk SecondaryParameters and collect any 'non-standard' children foreach (XmlNode innerNode in parameter.ChildNodes) { XmlElement innerElement = innerNode as XmlElement; if ((innerElement != null) && CanPromoteToRoot(innerElement, trust13Driver, clientSideClaimTypeRequirementsSpecified)) { childrenToPromote.Add(innerElement); } } // remove SecondaryParameters element tmpCollection.Remove(parameter); // we are done - break out of the loop break; } } // Probe of standard Trust elements and remember them. if ((childrenToPromote != null) && (childrenToPromote.Count > 0)) { XmlElement encryptionElement = null; string encryptionAlgorithm = String.Empty; XmlElement canonicalizationElement = null; string canonicalizationAlgoritm = String.Empty; XmlElement requiredClaimsElement = null; Collection <XmlElement> requiredClaims = null; Collection <XmlElement> processedElements = new Collection <XmlElement>(); foreach (XmlElement e in childrenToPromote) { if ((encryptionElement == null) && trust13Driver.IsEncryptionAlgorithmElement(e, out encryptionAlgorithm)) { encryptionElement = driver.CreateEncryptionAlgorithmElement(encryptionAlgorithm); processedElements.Add(e); } else if ((canonicalizationElement == null) && trust13Driver.IsCanonicalizationAlgorithmElement(e, out canonicalizationAlgoritm)) { canonicalizationElement = driver.CreateCanonicalizationAlgorithmElement(canonicalizationAlgoritm); processedElements.Add(e); } else if ((requiredClaimsElement == null) && trust13Driver.TryParseRequiredClaimsElement(e, out requiredClaims)) { requiredClaimsElement = driver.CreateRequiredClaimsElement(requiredClaims); processedElements.Add(e); } } for (int i = 0; i < processedElements.Count; ++i) { childrenToPromote.Remove(processedElements[i]); } XmlElement keyWrapAlgorithmElement = null; // Replace the appropriate elements. for (int i = 0; i < tmpCollection.Count; ++i) { string algorithmParameter; Collection <XmlElement> reqClaims; if (trust13Driver.IsSignWithElement(tmpCollection[i], out algorithmParameter)) { tmpCollection[i] = driver.CreateSignWithElement(algorithmParameter); } else if (trust13Driver.IsEncryptWithElement(tmpCollection[i], out algorithmParameter)) { tmpCollection[i] = driver.CreateEncryptWithElement(algorithmParameter); } else if (trust13Driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithmParameter) && (encryptionElement != null)) { tmpCollection[i] = encryptionElement; encryptionElement = null; } else if (trust13Driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithmParameter) && (canonicalizationElement != null)) { tmpCollection[i] = canonicalizationElement; canonicalizationElement = null; } else if (trust13Driver.IsKeyWrapAlgorithmElement(tmpCollection[i], out algorithmParameter) && (keyWrapAlgorithmElement == null)) { keyWrapAlgorithmElement = tmpCollection[i]; } else if (trust13Driver.TryParseRequiredClaimsElement(tmpCollection[i], out reqClaims) && (requiredClaimsElement != null)) { tmpCollection[i] = requiredClaimsElement; requiredClaimsElement = null; } } if (keyWrapAlgorithmElement != null) { // Remove KeyWrapAlgorithmElement as this is not define in Trust Feb 2005. tmpCollection.Remove(keyWrapAlgorithmElement); } // Add the remaining elements to the additionaParameters list to the end. if (encryptionElement != null) { tmpCollection.Add(encryptionElement); } if (canonicalizationElement != null) { tmpCollection.Add(canonicalizationElement); } if (requiredClaimsElement != null) { tmpCollection.Add(requiredClaimsElement); } if (childrenToPromote.Count > 0) { // There are some non-standard elements. Just bump them to the top-level element. for (int i = 0; i < childrenToPromote.Count; ++i) { tmpCollection.Add(childrenToPromote[i]); } } } } return(tmpCollection); }
public HybridCollection(T initialItem) { Fx.Assert(initialItem != null, "null is used as a sentinal value and is not a valid item value for a hybrid collection"); _singleItem = initialItem; }
public async Task <Message> ReceiveAsync(TimeoutHelper timeoutHelper) { byte[] buffer = Fx.AllocateByteArray(Connection.AsyncReadBufferSize); if (_size > 0) { Buffer.BlockCopy(Connection.AsyncReadBuffer, _offset, buffer, _offset, _size); } for (; ;) { if (DecodeBytes(buffer, ref _offset, ref _size, ref _isAtEof)) { break; } if (_isAtEof) { DoneReceiving(true, timeoutHelper.RemainingTime()); return(null); } if (_size == 0) { _offset = 0; _size = await Connection.ReadAsync(buffer, 0, buffer.Length, timeoutHelper.RemainingTime()); if (_size == 0) { DoneReceiving(true, timeoutHelper.RemainingTime()); return(null); } } } // we're ready to read a message IConnection singletonConnection = Connection; if (_size > 0) { byte[] initialData = Fx.AllocateByteArray(_size); Buffer.BlockCopy(buffer, _offset, initialData, 0, _size); singletonConnection = new PreReadConnection(singletonConnection, initialData); } Stream connectionStream = new SingletonInputConnectionStream(this, singletonConnection, _transportSettings); _inputStream = new MaxMessageSizeStream(connectionStream, _transportSettings.MaxReceivedMessageSize); using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity(true) : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityProcessingMessage, TraceUtility.RetrieveMessageNumber()), ActivityType.ProcessMessage); } Message message = null; try { message = await _transportSettings.MessageEncoderFactory.Encoder.ReadMessageAsync( _inputStream, _transportSettings.MaxBufferSize, ContentType); } catch (XmlException xmlException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.MessageXmlProtocolError), xmlException)); } if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.TransferFromTransport(message); } PrepareMessage(message); return(message); } }
public FatalException(string message, Exception innerException) : base(message, innerException) { // This can't throw something like ArgumentException because that would be worse than // throwing the fatal exception that was requested. Fx.Assert(innerException == null || !Fx.IsFatal(innerException), "FatalException can't be used to wrap fatal exceptions."); }
public static bool CanCreateInstanceUsingDefaultConstructor(Type type) { Fx.Assert(type != null, "type could not be null"); return(type.IsValueType || (!type.IsAbstract && type.GetConstructor(Type.EmptyTypes) != null)); }
public bool BufferReceive(OperationContext operationContext, ReceiveContext receiveContext, string bookmarkName, BufferedReceiveState state, bool retry) { bool flag = false; BufferedReceiveMessageProperty property = null; if (BufferedReceiveMessageProperty.TryGet(operationContext.IncomingMessageProperties, out property)) { CorrelationMessageProperty property = null; if (!CorrelationMessageProperty.TryGet(operationContext.IncomingMessageProperties, out property)) { return(flag); } EventHandler handler = null; InstanceKey instanceKey = property.CorrelationKey; int channelKey = operationContext.Channel.GetHashCode(); if (!this.throttle.Acquire(channelKey)) { return(flag); } try { if (!this.UpdateProperty(property, receiveContext, channelKey, bookmarkName, state)) { return(flag); } if (handler == null) { handler = delegate(object sender, EventArgs e) { lock (this.thisLock) { if (this.bufferedProperties.ContainsKey(instanceKey) && this.bufferedProperties[instanceKey].Remove(property)) { try { property.RequestContext.DelayClose(false); property.RequestContext.Abort(); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } } this.throttle.Release(channelKey); } } }; } receiveContext.Faulted += handler; lock (this.thisLock) { if (receiveContext.State != ReceiveContextState.Received) { return(flag); } bool flag2 = false; if (retry) { property.RequestContext.DelayClose(true); property.RegisterForReplay(operationContext); property.ReplayRequest(); property.Notification.NotifyInvokeReceived(property.RequestContext.InnerRequestContext); flag2 = true; } else { ReadOnlyCollection <BookmarkInfo> bookmarksForInstance = this.host.DurableInstanceManager.PersistenceProviderDirectory.GetBookmarksForInstance(instanceKey); if (bookmarksForInstance != null) { for (int i = 0; i < bookmarksForInstance.Count; i++) { BookmarkInfo info = bookmarksForInstance[i]; if (info.BookmarkName == bookmarkName) { property.RequestContext.DelayClose(true); property.RegisterForReplay(operationContext); property.ReplayRequest(); property.Notification.NotifyInvokeReceived(property.RequestContext.InnerRequestContext); flag2 = true; break; } } } } if (!flag2) { List <BufferedReceiveMessageProperty> list; if (!this.bufferedProperties.TryGetValue(instanceKey, out list)) { list = new List <BufferedReceiveMessageProperty>(); this.bufferedProperties.Add(instanceKey, list); } property.RequestContext.DelayClose(true); property.RegisterForReplay(operationContext); list.Add(property); } else { this.throttle.Release(channelKey); } return(true); } } finally { if (!flag) { this.throttle.Release(channelKey); } } } return(flag); }
public void ListAllStateReferences() { Address address1 = Fx.Address1; Address address2 = Fx.Address2; Address address3 = Fx.Address3; string stateKey1 = address1.ToHex().ToLowerInvariant(); string stateKey2 = address2.ToHex().ToLowerInvariant(); string stateKey3 = address3.ToHex().ToLowerInvariant(); var store = Fx.Store; var chain = TestUtils.MakeBlockChain(new NullPolicy <DumbAction>(), store); var block1 = TestUtils.MineNext(chain.Genesis); var block2 = TestUtils.MineNext(block1); var block3 = TestUtils.MineNext(block2); Transaction <DumbAction> tx4 = Fx.MakeTransaction( new[] { new DumbAction(address1, "foo1"), new DumbAction(address2, "foo2"), } ); Block <DumbAction> block4 = TestUtils.MineNext( block3, new[] { tx4 }, blockInterval: TimeSpan.FromSeconds(10)); Transaction <DumbAction> tx5 = Fx.MakeTransaction( new[] { new DumbAction(address1, "bar1"), new DumbAction(address3, "bar3"), } ); Block <DumbAction> block5 = TestUtils.MineNext( block4, new[] { tx5 }, blockInterval: TimeSpan.FromSeconds(10)); Block <DumbAction> block6 = TestUtils.MineNext( block5, blockInterval: TimeSpan.FromSeconds(10)); chain.Append(block1); chain.Append(block2); chain.Append(block3); chain.Append(block4); chain.Append(block5); chain.Append(block6); Guid chainId = chain.Id; IImmutableDictionary <string, IImmutableList <HashDigest <SHA256> > > refs; refs = store.ListAllStateReferences(chainId); Assert.Equal( new HashSet <string> { stateKey1, stateKey2, stateKey3 }, refs.Keys.ToHashSet() ); Assert.Equal(new[] { block4.Hash, block5.Hash }, refs[stateKey1]); Assert.Equal(new[] { block4.Hash }, refs[stateKey2]); Assert.Equal(new[] { block5.Hash }, refs[stateKey3]); refs = store.ListAllStateReferences(chainId, lowestIndex: block4.Index + 1); Assert.Equal(new HashSet <string> { stateKey1, stateKey3 }, refs.Keys.ToHashSet()); Assert.Equal(new[] { block5.Hash }, refs[stateKey1]); Assert.Equal(new[] { block5.Hash }, refs[stateKey3]); refs = store.ListAllStateReferences(chainId, highestIndex: block4.Index); Assert.Equal(new HashSet <string> { stateKey1, stateKey2, }, refs.Keys.ToHashSet()); Assert.Equal(new[] { block4.Hash }, refs[stateKey1]); Assert.Equal(new[] { block4.Hash }, refs[stateKey2]); }
internal BookmarkScope(long temporaryId) { Fx.Assert(temporaryId != default(long), "Should never call this constructor with the default value."); this.temporaryId = temporaryId; }
public void LookupStateReference() { Address address = Fx.Address1; string stateKey = address.ToHex().ToLowerInvariant(); Transaction <DumbAction> tx4 = Fx.MakeTransaction( new DumbAction[] { new DumbAction(address, "foo") } ); Block <DumbAction> block4 = TestUtils.MineNext(Fx.Block3, new[] { tx4 }); Transaction <DumbAction> tx5 = Fx.MakeTransaction( new DumbAction[] { new DumbAction(address, "bar") } ); Block <DumbAction> block5 = TestUtils.MineNext(block4, new[] { tx5 }); Block <DumbAction> block6 = TestUtils.MineNext(block5, new Transaction <DumbAction> [0]); Assert.Null(Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, Fx.Block3)); Assert.Null(Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block4)); Assert.Null(Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block5)); Assert.Null(Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block6)); Fx.Store.StoreStateReference( Fx.StoreChainId, tx4.UpdatedAddresses.Select(a => a.ToHex().ToLowerInvariant()).ToImmutableHashSet(), block4.Hash, block4.Index ); Assert.Null(Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, Fx.Block3)); Assert.Equal( Tuple.Create(block4.Hash, block4.Index), Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block4) ); Assert.Equal( Tuple.Create(block4.Hash, block4.Index), Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block5) ); Assert.Equal( Tuple.Create(block4.Hash, block4.Index), Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block6) ); Fx.Store.StoreStateReference( Fx.StoreChainId, tx5.UpdatedAddresses.Select(a => a.ToHex().ToLowerInvariant()).ToImmutableHashSet(), block5.Hash, block5.Index ); Assert.Null(Fx.Store.LookupStateReference( Fx.StoreChainId, stateKey, Fx.Block3)); Assert.Equal( Tuple.Create(block4.Hash, block4.Index), Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block4) ); Assert.Equal( Tuple.Create(block5.Hash, block5.Index), Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block5) ); Assert.Equal( Tuple.Create(block5.Hash, block5.Index), Fx.Store.LookupStateReference(Fx.StoreChainId, stateKey, block6) ); }
void CreatePhong(Fx.ColladaPhong phong, H1.Tags.shader_transparent_glass_group shader) { if (shader.DiffuseMap.Datum != DatumIndex.Null) { phong.Diffuse.Color = null; phong.Diffuse.Texture = CreateTexture(shader.DiffuseMap.Datum, 0); } }
private BasicHttpSecurity(BasicHttpSecurityMode mode, HttpTransportSecurity transportSecurity) { Fx.Assert(BasicHttpSecurityModeHelper.IsDefined(mode), string.Format("Invalid BasicHttpSecurityMode value: {0}.", mode.ToString())); this.Mode = mode; _transportSecurity = transportSecurity == null ? new HttpTransportSecurity() : transportSecurity; }
public HttpContextBackedProperty(HttpContext httpContext) { Fx.Assert(httpContext != null, "The 'httpResponseMessage' property should never be null."); HttpContext = httpContext; }
private XmlSerializerOperationBehavior(Reflector.OperationReflector reflector, bool builtInOperationBehavior) { Fx.Assert(reflector != null, ""); _reflector = reflector; _builtInOperationBehavior = builtInOperationBehavior; }