async Task <ReceivingAmqpLink> CreateLinkAsync(TimeSpan timeout) { FilterSet filterMap = null; MessagingEventSource.Log.AmqpReceiveLinkCreateStart(this.ClientId, false, this.EntityType, this.Path); if (this.isSessionReceiver) { filterMap = new FilterSet { { AmqpClientConstants.SessionFilterName, this.sessionId } }; } AmqpLinkSettings linkSettings = new AmqpLinkSettings { Role = true, TotalLinkCredit = (uint)this.PrefetchCount, AutoSendFlow = this.PrefetchCount > 0, Source = new Source { Address = this.Path, FilterSet = filterMap }, SettleType = (this.ReceiveMode == ReceiveMode.PeekLock) ? SettleMode.SettleOnDispose : SettleMode.SettleOnSend }; linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)this.EntityType); linkSettings.AddProperty(AmqpClientConstants.TimeoutName, (uint)timeout.TotalMilliseconds); AmqpSendReceiveLinkCreator sendReceiveLinkCreator = new AmqpSendReceiveLinkCreator(this.Path, this.ServiceBusConnection, new[] { ClaimConstants.Listen }, this.CbsTokenProvider, linkSettings); ReceivingAmqpLink receivingAmqpLink = (ReceivingAmqpLink)await sendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); MessagingEventSource.Log.AmqpReceiveLinkCreateStop(this.ClientId); return(receivingAmqpLink); }
static AmqpLinkSettings SetLinkSettingsCommonProperties(AmqpLinkSettings linkSettings, TimeSpan timeSpan) { linkSettings.AddProperty(IotHubAmqpProperty.TimeoutName, timeSpan.TotalMilliseconds); linkSettings.AddProperty(IotHubAmqpProperty.ClientVersion, Utils.GetClientVersion()); return(linkSettings); }
protected static AmqpLinkSettings SetLinkSettingsCommonProperties(AmqpLinkSettings linkSettings, TimeSpan timeSpan, ProductInfo productInfo) { linkSettings.AddProperty(IotHubAmqpProperty.TimeoutName, timeSpan.TotalMilliseconds); linkSettings.AddProperty(IotHubAmqpProperty.ClientVersion, productInfo.ToString()); return(linkSettings); }
internal async Task <ActiveClientRequestResponseLink> OpenRequestResponseLinkAsync( string type, string address, MessagingEntityType?entityType, string[] requiredClaims, TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout, true); AmqpSession session = null; try { // Don't need to get token for namespace scope operations, included in request bool isNamespaceScope = address.Equals(AmqpClientConstants.ManagementAddress, StringComparison.OrdinalIgnoreCase); var connection = await this.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()); var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; //sessionSettings.Properties[AmqpClientConstants.BatchFlushIntervalName] = (uint)batchFlushInterval.TotalMilliseconds; session = connection.CreateSession(sessionSettings); await session.OpenAsync(timeoutHelper.RemainingTime()); var linkSettings = new AmqpLinkSettings(); linkSettings.AddProperty(AmqpClientConstants.TimeoutName, (uint)timeoutHelper.RemainingTime().TotalMilliseconds); if (entityType != null) { linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)entityType.Value); } // Create the link var link = new RequestResponseAmqpLink(type, session, address, linkSettings.Properties); var authorizationValidToUtc = DateTime.MaxValue; if (!isNamespaceScope) { // TODO: Get Entity level token here } await link.OpenAsync(timeoutHelper.RemainingTime()); // Redirected scenario requires entityPath as the audience, otherwise we // should always use the full EndpointUri as audience. return(new ActiveClientRequestResponseLink( link, this.ConnectionStringBuilder.Endpoint.AbsoluteUri, // audience this.ConnectionStringBuilder.Endpoint.AbsoluteUri, // endpointUri requiredClaims, false, authorizationValidToUtc)); } catch (Exception) { // Aborting the session will cleanup the link as well. session?.Abort(); throw; } }
internal static async Task <ReceivingAmqpLink> OpenReceivingAmqpLinkAsync( DeviceIdentity deviceIdentity, AmqpSession amqpSession, byte?senderSettleMode, byte?receiverSettleMode, string deviceTemplate, string moduleTemplate, string linkSuffix, string CorrelationId, TimeSpan timeout ) { if (Logging.IsEnabled) { Logging.Enter(typeof(AmqpLinkHelper), deviceIdentity, $"{nameof(OpenReceivingAmqpLinkAsync)}"); } uint prefetchCount = deviceIdentity.AmqpTransportSettings.PrefetchCount; AmqpLinkSettings amqpLinkSettings = new AmqpLinkSettings { LinkName = CommonResources.GetNewStringGuid(linkSuffix), Role = true, TotalLinkCredit = prefetchCount, AutoSendFlow = prefetchCount > 0, Source = new Source() { Address = BuildLinkAddress(deviceIdentity, deviceTemplate, moduleTemplate) }, Target = new Target() { Address = deviceIdentity.IotHubConnectionString.DeviceId } }; amqpLinkSettings.SndSettleMode = senderSettleMode; amqpLinkSettings.RcvSettleMode = receiverSettleMode; amqpLinkSettings.AddProperty(IotHubAmqpProperty.TimeoutName, timeout.TotalMilliseconds); amqpLinkSettings.AddProperty(IotHubAmqpProperty.ClientVersion, deviceIdentity.ProductInfo.ToString()); amqpLinkSettings.AddProperty(IotHubAmqpProperty.ApiVersion, ClientApiVersionHelper.ApiVersionString); if (CorrelationId != null) { amqpLinkSettings.AddProperty(IotHubAmqpProperty.ChannelCorrelationId, CorrelationId); } ReceivingAmqpLink receivingLink = new ReceivingAmqpLink(amqpLinkSettings); receivingLink.AttachTo(amqpSession); await receivingLink.OpenAsync(timeout).ConfigureAwait(false); if (Logging.IsEnabled) { Logging.Exit(typeof(AmqpLinkHelper), deviceIdentity, $"{nameof(OpenReceivingAmqpLinkAsync)}"); } return(receivingLink); }
private static AmqpLinkSettings SetLinkSettingsCommonProperties(AmqpLinkSettings linkSettings, TimeSpan timeSpan) { string clientVersion = Utils.GetClientVersion(); linkSettings.AddProperty(IotHubAmqpProperty.TimeoutName, timeSpan.TotalMilliseconds); linkSettings.AddProperty(IotHubAmqpProperty.ClientVersion, clientVersion); Logging.Info(clientVersion, nameof(SetLinkSettingsCommonProperties)); return(linkSettings); }
private static async Task <AmqpIoTSendingLink> OpenSendingAmqpLinkAsync( DeviceIdentity deviceIdentity, AmqpSession amqpSession, byte?senderSettleMode, byte?receiverSettleMode, string deviceTemplate, string moduleTemplate, string linkSuffix, string CorrelationId, TimeSpan timeout ) { if (Logging.IsEnabled) { Logging.Enter(typeof(AmqpIoTSession), deviceIdentity, $"{nameof(OpenSendingAmqpLinkAsync)}"); } AmqpLinkSettings amqpLinkSettings = new AmqpLinkSettings { LinkName = CommonResources.GetNewStringGuid(linkSuffix), Role = false, InitialDeliveryCount = 0, Target = new Target() { Address = BuildLinkAddress(deviceIdentity, deviceTemplate, moduleTemplate) }, Source = new Source() { Address = deviceIdentity.IotHubConnectionString.DeviceId } }; amqpLinkSettings.SndSettleMode = senderSettleMode; amqpLinkSettings.RcvSettleMode = receiverSettleMode; amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.TimeoutName, timeout.TotalMilliseconds); amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ClientVersion, deviceIdentity.ProductInfo.ToString()); amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ApiVersion, ClientApiVersionHelper.ApiVersionString); if (CorrelationId != null) { amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ChannelCorrelationId, CorrelationId); } SendingAmqpLink sendingLink = new SendingAmqpLink(amqpLinkSettings); sendingLink.AttachTo(amqpSession); await sendingLink.OpenAsync(timeout).ConfigureAwait(false); if (Logging.IsEnabled) { Logging.Exit(typeof(AmqpIoTSession), deviceIdentity, $"{nameof(OpenSendingAmqpLinkAsync)}"); } return(new AmqpIoTSendingLink(sendingLink)); }
protected static AmqpLinkSettings SetLinkSettingsCommonProperties(AmqpLinkSettings linkSettings, TimeSpan timeSpan) { linkSettings.AddProperty(IotHubAmqpProperty.TimeoutName, timeSpan.TotalMilliseconds); #if WINDOWS_UWP // System.Reflection.Assembly.GetExecutingAssembly() does not exist for UWP, therefore use a hard-coded version name // (This string is picked up by the bump_version script, so don't change the line below) var UWPAssemblyVersion = "1.1.4"; linkSettings.AddProperty(IotHubAmqpProperty.ClientVersion, UWPAssemblyVersion); #else linkSettings.AddProperty(IotHubAmqpProperty.ClientVersion, Utils.GetClientVersion()); #endif return(linkSettings); }
public async Task <RequestResponseAmqpLink> CreateRequestResponseLink(string path, TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout); AmqpSession session; if (!this.faultTolerantSession.TryGetOpenedObject(out session)) { session = await this.faultTolerantSession.GetOrCreateAsync(timeoutHelper.RemainingTime()); } var linkAddress = this.connectionString.BuildLinkAddress(path); var linkSettings = new AmqpLinkSettings() { TotalLinkCredit = 0, AutoSendFlow = false, Source = new Source() { Address = linkAddress.AbsoluteUri }, SettleType = SettleMode.SettleOnDispose, LinkName = Guid.NewGuid().ToString("N") // Use a human readable link name to help with debuggin }; linkSettings.AddProperty(IotHubAmqpProperty.TimeoutName, timeoutHelper.RemainingTime().TotalMilliseconds); var link = new RequestResponseAmqpLink(session, linkSettings); await OpenLinkAsync(link, timeoutHelper.RemainingTime()); return(link); }
async Task <SendingAmqpLink> CreateLinkAsync(TimeSpan timeout) { MessagingEventSource.Log.AmqpSendLinkCreateStart(this.ClientId, this.EntityType, this.Path); AmqpLinkSettings linkSettings = new AmqpLinkSettings { Role = false, InitialDeliveryCount = 0, Target = new Target { Address = this.Path }, Source = new Source { Address = this.ClientId }, }; if (this.EntityType != null) { linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)this.EntityType); } AmqpSendReceiveLinkCreator sendReceiveLinkCreator = new AmqpSendReceiveLinkCreator(this.Path, this.ServiceBusConnection, new[] { ClaimConstants.Send }, this.CbsTokenProvider, linkSettings); SendingAmqpLink sendingAmqpLink = (SendingAmqpLink)await sendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); MessagingEventSource.Log.AmqpSendLinkCreateStop(this.ClientId); return(sendingAmqpLink); }
// TODO: Consolidate the link creation paths async Task <RequestResponseAmqpLink> CreateRequestResponseLinkAsync(TimeSpan timeout) { string entityPath = this.Path + '/' + AmqpClientConstants.ManagementAddress; AmqpLinkSettings linkSettings = new AmqpLinkSettings(); linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, AmqpClientConstants.EntityTypeManagement); AmqpRequestResponseLinkCreator requestResponseLinkCreator = new AmqpRequestResponseLinkCreator(entityPath, this.ServiceBusConnection, new[] { ClaimConstants.Manage, ClaimConstants.Listen }, this.CbsTokenProvider, linkSettings); RequestResponseAmqpLink requestResponseAmqpLink = (RequestResponseAmqpLink)await requestResponseLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); return(requestResponseAmqpLink); }
public static AmqpLinkSettings GetLinkSettings(bool forSender, string address, SettleMode settleType, int credit = 0, bool dynamic = false) { AmqpLinkSettings settings = null; // create a setting for sender settings = new AmqpLinkSettings(); settings.LinkName = string.Format("link-{0}", Guid.NewGuid().ToString("N")); settings.Role = !forSender; Target target = new Target(); target.Address = address; Source source = new Source(); source.Address = address; source.DistributionMode = "move"; settings.Source = source; settings.Target = target; settings.SettleType = settleType; if (!forSender) { settings.TotalLinkCredit = (uint)credit; settings.AutoSendFlow = credit > 0; if (dynamic) { source.Address = null; source.Dynamic = true; } } else { settings.InitialDeliveryCount = 0; if (dynamic) { target.Address = null; target.Dynamic = true; } } settings.AddProperty("x-opt-just-testing", "ignore me"); return(settings); }
/// <summary> /// Creates an AMQP link for use with management operations. /// </summary> /// /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use with management operations.</returns> /// protected virtual async Task <RequestResponseAmqpLink> CreateManagementLinkAsync(AmqpConnection connection, TimeSpan timeout, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the link. var linkSettings = new AmqpLinkSettings(); linkSettings.AddProperty(AmqpProperty.Timeout, (uint)timeout.CalculateRemaining(stopWatch.Elapsed).TotalMilliseconds); var link = new RequestResponseAmqpLink(AmqpManagement.LinkType, session, AmqpManagement.Address, linkSettings.Properties); stopWatch.Stop(); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(link); return(link); } catch { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw; } }
public async Task <ReceivingAmqpLink> CreateReceivingLink(string path, TimeSpan timeout, uint prefetchCount) { var timeoutHelper = new TimeoutHelper(timeout); AmqpSession session; if (!this.faultTolerantSession.TryGetOpenedObject(out session)) { session = await this.faultTolerantSession.GetOrCreateAsync(timeoutHelper.RemainingTime()); } var linkAddress = this.connectionString.BuildLinkAddress(path); var linkSettings = new AmqpLinkSettings() { Role = true, TotalLinkCredit = prefetchCount, AutoSendFlow = prefetchCount > 0, Source = new Source() { Address = linkAddress.AbsoluteUri }, SndSettleMode = null, // SenderSettleMode.Unsettled (null as it is the default and to avoid bytes on the wire) RcvSettleMode = (byte)ReceiverSettleMode.Second, LinkName = Guid.NewGuid().ToString("N") // Use a human readable link name to help with debuggin }; linkSettings.AddProperty(IotHubAmqpProperty.TimeoutName, timeoutHelper.RemainingTime().TotalMilliseconds); var link = new ReceivingAmqpLink(linkSettings); link.AttachTo(session); await OpenLinkAsync(link, timeoutHelper.RemainingTime()); return(link); }
public async Task <SendingAmqpLink> CreateSendingLinkAsync(string path, TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout); AmqpSession session; if (!this.faultTolerantSession.TryGetOpenedObject(out session)) { session = await this.faultTolerantSession.GetOrCreateAsync(timeoutHelper.RemainingTime()); } var linkAddress = this.connectionString.BuildLinkAddress(path); var linkSettings = new AmqpLinkSettings() { Role = false, InitialDeliveryCount = 0, Target = new Target() { Address = linkAddress.AbsoluteUri }, SndSettleMode = null, // SenderSettleMode.Unsettled (null as it is the default and to avoid bytes on the wire) RcvSettleMode = null, // (byte)ReceiverSettleMode.First (null as it is the default and to avoid bytes on the wire) LinkName = Guid.NewGuid().ToString("N") // Use a human readable link name to help with debugging }; linkSettings.AddProperty(IotHubAmqpProperty.TimeoutName, timeoutHelper.RemainingTime().TotalMilliseconds); var link = new SendingAmqpLink(linkSettings); link.AttachTo(session); await OpenLinkAsync(link, timeoutHelper.RemainingTime()); return(link); }
private static async Task <AmqpIoTReceivingLink> OpenReceivingAmqpLinkAsync( DeviceIdentity deviceIdentity, AmqpSession amqpSession, byte?senderSettleMode, byte?receiverSettleMode, string deviceTemplate, string moduleTemplate, string linkSuffix, string correlationId, TimeSpan timeout) { if (Logging.IsEnabled) { Logging.Enter(typeof(AmqpIoTSession), deviceIdentity, $"{nameof(OpenReceivingAmqpLinkAsync)}"); } uint prefetchCount = deviceIdentity.AmqpTransportSettings.PrefetchCount; AmqpLinkSettings amqpLinkSettings = new AmqpLinkSettings { LinkName = linkSuffix, Role = true, TotalLinkCredit = prefetchCount, AutoSendFlow = prefetchCount > 0, Source = new Source() { Address = BuildLinkAddress(deviceIdentity, deviceTemplate, moduleTemplate) }, Target = new Target() { Address = deviceIdentity.IotHubConnectionString.DeviceId } }; amqpLinkSettings.SndSettleMode = senderSettleMode; amqpLinkSettings.RcvSettleMode = receiverSettleMode; amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.TimeoutName, timeout.TotalMilliseconds); amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ClientVersion, deviceIdentity.ProductInfo.ToString()); amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ApiVersion, ClientApiVersionHelper.ApiVersionString); if (!deviceIdentity.AmqpTransportSettings.AuthenticationChain.IsNullOrWhiteSpace()) { amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.AuthChain, deviceIdentity.AmqpTransportSettings.AuthenticationChain); } if (correlationId != null) { amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ChannelCorrelationId, correlationId); } try { ReceivingAmqpLink receivingLink = new ReceivingAmqpLink(amqpLinkSettings); receivingLink.AttachTo(amqpSession); await receivingLink.OpenAsync(timeout).ConfigureAwait(false); return(new AmqpIoTReceivingLink(receivingLink)); } catch (Exception e) when(!e.IsFatal()) { Exception ex = AmqpIoTExceptionAdapter.ConvertToIoTHubException(e, amqpSession); if (ReferenceEquals(e, ex)) { throw; } else { if (ex is AmqpIoTResourceException) { amqpSession.SafeClose(); throw new IotHubCommunicationException(ex.Message, ex); } throw ex; } } finally { if (Logging.IsEnabled) { Logging.Exit(typeof(AmqpIoTSession), deviceIdentity, $"{nameof(OpenReceivingAmqpLinkAsync)}"); } } }
protected override IEnumerator <IteratorTask <object> .TaskStep> GetTasks() { ConnectivityMode connectivityMode; object obj = null; bool flag = false; try { object thisLock = this.relay.ThisLock; object obj1 = thisLock; obj = thisLock; Monitor.Enter(obj1, ref flag); if (this.relay.State != AmqpObjectState.OpenReceived && this.relay.State != AmqpObjectState.Opened) { goto Label0; } } finally { if (flag) { Monitor.Exit(obj); } } Microsoft.ServiceBus.Common.TimeoutHelper timeoutHelper = new Microsoft.ServiceBus.Common.TimeoutHelper(this.timeout); string host = this.relay.serviceBusUri.Host; AmqpSettings amqpSetting = AmqpRelay.ConnectTask.CreateAmqpSettings(); connectivityMode = (this.relay.connectivitySettings != null ? this.relay.connectivitySettings.Mode : ServiceBusEnvironment.SystemConnectivity.Mode); ConnectivityMode connectivityMode1 = connectivityMode; if (connectivityMode1 == ConnectivityMode.Tcp) { TcpTransportSettings tcpTransportSetting = new TcpTransportSettings() { Host = host, Port = 5671 }; TlsTransportSettings tlsTransportSetting = new TlsTransportSettings(tcpTransportSetting) { TargetHost = host }; AmqpTransportInitiator amqpTransportInitiator = new AmqpTransportInitiator(amqpSetting, tlsTransportSetting); yield return(base.CallTask(amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer)); } else if (connectivityMode1 == ConnectivityMode.Http || this.relay.httpConnectivitySettings != null) { WebSocketTransportSettings webSocketTransportSetting = new WebSocketTransportSettings(this.relay.serviceBusUri); AmqpTransportInitiator amqpTransportInitiator1 = new AmqpTransportInitiator(amqpSetting, webSocketTransportSetting); yield return(base.CallTask(amqpTransportInitiator1.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer)); } else { TcpTransportSettings tcpTransportSetting1 = new TcpTransportSettings() { Host = host, Port = 5671 }; TlsTransportSettings tlsTransportSetting1 = new TlsTransportSettings(tcpTransportSetting1) { TargetHost = host }; AmqpTransportInitiator amqpTransportInitiator2 = new AmqpTransportInitiator(amqpSetting, tlsTransportSetting1); yield return(base.CallTask(amqpTransportInitiator2.ConnectTaskAsync(Microsoft.ServiceBus.Common.TimeoutHelper.Divide(timeoutHelper.RemainingTime(), 2)), IteratorTask <TResult> .ExceptionPolicy.Continue)); if (base.LastTask.Exception != null) { if (timeoutHelper.RemainingTime() == TimeSpan.Zero) { throw base.LastTask.Exception; } WebSocketTransportSettings webSocketTransportSetting1 = new WebSocketTransportSettings(this.relay.serviceBusUri); AmqpTransportInitiator amqpTransportInitiator3 = new AmqpTransportInitiator(amqpSetting, webSocketTransportSetting1); yield return(base.CallTask(amqpTransportInitiator3.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer)); } } TransportBase transportBase = base.LastTaskResult <TransportBase>(); string[] strArrays = host.Split(new char[] { '.' }); strArrays[0] = string.Concat(strArrays[0], "-relay"); AmqpConnectionSettings amqpConnectionSetting = new AmqpConnectionSettings() { ContainerId = Guid.NewGuid().ToString(), HostName = string.Join(".", strArrays) }; this.relay.connection = new AmqpConnection(transportBase, amqpSetting, amqpConnectionSetting); yield return(base.CallTask(this.relay.connection.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer)); AmqpSessionSettings amqpSessionSetting = new AmqpSessionSettings(); AmqpSession amqpSession = this.relay.connection.CreateSession(amqpSessionSetting); yield return(base.CallTask(amqpSession.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer)); AmqpLinkSettings amqpLinkSetting = new AmqpLinkSettings() { Role = new bool?(false), InitialDeliveryCount = new uint?(0), LinkName = string.Concat("HttpRelayServer_Link_", Guid.NewGuid()), Target = new Target(this.relay.serviceBusUri), Source = new Source(this.relay.serviceBusUri), TotalLinkCredit = 1000, AutoSendFlow = true }; AmqpLinkSettings amqpLinkSetting1 = amqpLinkSetting; if (this.relay.tokenRenewer != null) { amqpLinkSetting1.AddProperty(AmqpConstants.SimpleWebTokenPropertyName, this.relay.tokenRenewer.CurrentToken.Token); } if (!this.relay.TransportSecurityRequired) { amqpLinkSetting1.AddProperty(ClientConstants.TransportSecurityRequiredName, false); } if (!this.relay.RelayClientAuthorizationRequired) { amqpLinkSetting1.AddProperty(ClientConstants.ClientAuthenticationRequiredName, false); } if (this.relay.PublishToRegistry) { amqpLinkSetting1.AddProperty(ClientConstants.RequiresPublicRegistry, true); } if (!string.IsNullOrEmpty(this.relay.ClientAgent)) { amqpLinkSetting1.AddProperty(ClientConstants.ClientAgent, this.relay.ClientAgent); } if (!string.IsNullOrEmpty(this.relay.DisplayName)) { amqpLinkSetting1.AddProperty(ClientConstants.DisplayName, this.relay.DisplayName); } amqpLinkSetting1.AddProperty(ClientConstants.DynamicRelay, this.relay.IsDynamic); amqpLinkSetting1.AddProperty(ClientConstants.ListenerTypeName, this.relay.ListenerType.ToString()); this.relay.link = new DuplexAmqpLink(amqpSession, amqpLinkSetting1); yield return(base.CallTask(this.relay.link.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer)); this.relay.link.SafeAddClosed(this.relay.onAmqpObjectClosed); this.relay.link.RegisterMessageListener((AmqpMessage msg) => this.relay.messageListener(this.relay.link, msg)); this.relay.OnOnline(); Label0: yield break; }
protected override IEnumerator <IteratorAsyncResult <AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult> .AsyncStep> GetAsyncSteps() { string str = "$cbs"; if (base.RemainingTime() > TimeSpan.Zero) { try { AmqpSessionSettings amqpSessionSetting = new AmqpSessionSettings() { Properties = new Fields() }; this.session = new AmqpSession(this.connection, amqpSessionSetting, this); this.connection.AddSession(this.session, null); } catch (InvalidOperationException invalidOperationException1) { InvalidOperationException invalidOperationException = invalidOperationException1; base.Complete(new MessagingException(invalidOperationException.Message, false, invalidOperationException)); goto Label0; } AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult openCbsRequestResponseLinkAsyncResult = this; IteratorAsyncResult <AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult> .BeginCall beginCall = (AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.session.BeginOpen(t, c, s); yield return(openCbsRequestResponseLinkAsyncResult.CallAsync(beginCall, (AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult thisPtr, IAsyncResult r) => thisPtr.session.EndOpen(r), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Continue)); Exception lastAsyncStepException = base.LastAsyncStepException; if (lastAsyncStepException == null) { AmqpLinkSettings amqpLinkSetting = new AmqpLinkSettings(); AmqpLinkSettings amqpLinkSetting1 = amqpLinkSetting; AmqpSymbol timeoutName = ClientConstants.TimeoutName; TimeSpan timeSpan = base.RemainingTime(); amqpLinkSetting1.AddProperty(timeoutName, (uint)timeSpan.TotalMilliseconds); amqpLinkSetting.Target = new Target() { Address = str }; amqpLinkSetting.Source = new Source() { Address = str }; amqpLinkSetting.InitialDeliveryCount = new uint?(0); amqpLinkSetting.TotalLinkCredit = 50; amqpLinkSetting.AutoSendFlow = true; amqpLinkSetting.SettleType = SettleMode.SettleOnSend; this.Link = new RequestResponseAmqpLink(this.session, amqpLinkSetting); AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult openCbsRequestResponseLinkAsyncResult1 = this; IteratorAsyncResult <AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult> .BeginCall beginCall1 = (AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.Link.BeginOpen(t, c, s); yield return(openCbsRequestResponseLinkAsyncResult1.CallAsync(beginCall1, (AmqpCbsLink.OpenCbsRequestResponseLinkAsyncResult thisPtr, IAsyncResult r) => thisPtr.Link.EndOpen(r), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Continue)); lastAsyncStepException = base.LastAsyncStepException; if (lastAsyncStepException == null) { MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteAmqpOpenEntitySucceeded(this.connection, this.Link, this.Link.Name, str)); } else { this.Link = null; MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteAmqpOpenEntityFailed(this.connection, this.Link, this.Link.Name, str, lastAsyncStepException.Message)); this.session.SafeClose(); base.Complete(Microsoft.ServiceBus.Messaging.Amqp.ExceptionHelper.ToMessagingContract(lastAsyncStepException, this.connection.RemoteEndpoint.ToString())); } } else { MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteAmqpOpenEntityFailed(this.connection, this.session, string.Empty, str, lastAsyncStepException.Message)); this.session.Abort(); base.Complete(Microsoft.ServiceBus.Messaging.Amqp.ExceptionHelper.ToMessagingContract(lastAsyncStepException, this.connection.RemoteEndpoint.ToString())); } } else { if (this.session != null) { this.session.SafeClose(); } base.Complete(new TimeoutException(SRAmqp.AmqpTimeout(base.OriginalTimeout, str))); } Label0: yield break; }
/// <summary> /// Creates an AMQP link for use with publishing operations. /// </summary> /// /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="endpoint">The fully qualified endpoint to open the link for.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use for operations related to receiving events.</returns> /// protected virtual async Task <SendingAmqpLink> CreateSendingLinkAsync(AmqpConnection connection, Uri endpoint, TimeSpan timeout, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { // Perform the initial authorization for the link. var authClaims = new[] { EventHubsClaim.Send }; var authExpirationUtc = await RequestAuthorizationUsingCbsAsync(connection, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the link. var linkSettings = new AmqpLinkSettings { Role = false, InitialDeliveryCount = 0, Source = new Source { Address = Guid.NewGuid().ToString() }, Target = new Target { Address = endpoint.AbsolutePath } }; linkSettings.AddProperty(AmqpProperty.Timeout, (uint)timeout.CalculateRemaining(stopWatch.Elapsed).TotalMilliseconds); linkSettings.AddProperty(AmqpProperty.EntityType, (int)AmqpProperty.Entity.EventHub); var link = new SendingAmqpLink(linkSettings); linkSettings.LinkName = $"{ Id };{ connection.Identifier }:{ session.Identifier }:{ link.Identifier }"; link.AttachTo(session); stopWatch.Stop(); // Configure refresh for authorization of the link. var refreshTimer = default(Timer); var refreshHandler = CreateAuthorizationRefreshHandler ( connection, link, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, AuthorizationRefreshTimeout, () => refreshTimer ); refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(link, refreshTimer); return(link); } catch { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw; } }
AmqpLinkSettings SetLinkSettingsCommonPropertiesForTwin(AmqpLinkSettings linkSettings, string corrId) { linkSettings.AddProperty(IotHubAmqpProperty.ApiVersion, ClientApiVersionHelper.ApiVersionString); linkSettings.AddProperty(IotHubAmqpProperty.ChannelCorrelationId, "twin:" + corrId); return(linkSettings); }
/// <summary> /// Creates an AMQP link for use with receiving operations. /// </summary> /// /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="endpoint">The fully qualified endpoint to open the link for.</param> /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested.</param> /// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param> /// <param name="sessionId"></param> /// <param name="isSessionReceiver"></param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use for operations related to receiving events.</returns> /// protected virtual async Task <ReceivingAmqpLink> CreateReceivingLinkAsync( AmqpConnection connection, Uri endpoint, TimeSpan timeout, uint prefetchCount, long?ownerLevel, string sessionId, bool isSessionReceiver, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { // Perform the initial authorization for the link. var authClaims = new[] { ServiceBusClaim.Listen }; var authExpirationUtc = await RequestAuthorizationUsingCbsAsync(connection, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var filters = new FilterSet(); // even if supplied sessionId is null, we need to add the Session filter if it is a session receiver if (isSessionReceiver) { filters.Add(AmqpClientConstants.SessionFilterName, sessionId); } var linkSettings = new AmqpLinkSettings { Role = true, TotalLinkCredit = prefetchCount, AutoSendFlow = prefetchCount > 0, SettleType = SettleMode.SettleOnSend, Source = new Source { Address = endpoint.AbsolutePath, FilterSet = filters }, Target = new Target { Address = Guid.NewGuid().ToString() } }; if (ownerLevel.HasValue) { linkSettings.AddProperty(AmqpProperty.OwnerLevel, ownerLevel.Value); } var link = new ReceivingAmqpLink(linkSettings); linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}:{linkSettings.Source.ToString()}"; link.AttachTo(session); stopWatch.Stop(); // Configure refresh for authorization of the link. var refreshTimer = default(Timer); var refreshHandler = CreateAuthorizationRefreshHandler ( connection, link, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, AuthorizationRefreshTimeout, () => (ActiveLinks.ContainsKey(link) ? refreshTimer : null) ); refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(link, refreshTimer); return(link); } catch { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw; } }
public static AmqpLinkSettings GetLinkSettings(bool forSender, string address, SettleMode settleType, int credit = 0, bool dynamic = false) { AmqpLinkSettings settings = null; // create a setting for sender settings = new AmqpLinkSettings(); settings.LinkName = string.Format("link-{0}", Guid.NewGuid().ToString("N")); settings.Role = !forSender; Target target = new Target(); target.Address = address; Source source = new Source(); source.Address = address; source.DistributionMode = "move"; settings.Source = source; settings.Target = target; settings.SettleType = settleType; if (!forSender) { settings.TotalLinkCredit = (uint)credit; settings.AutoSendFlow = credit > 0; if (dynamic) { source.Address = null; source.Dynamic = true; } } else { settings.InitialDeliveryCount = 0; if (dynamic) { target.Address = null; target.Dynamic = true; } } settings.AddProperty("x-opt-just-testing", "ignore me"); return settings; }
/// <summary> /// Creates an AMQP link for use with publishing operations. /// </summary> /// <param name="entityPath"></param> /// <param name="viaEntityPath">The entity path to route the message through. Useful when using transactions.</param> /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use for operations related to receiving events.</returns> /// protected virtual async Task <SendingAmqpLink> CreateSendingLinkAsync( string entityPath, string viaEntityPath, AmqpConnection connection, TimeSpan timeout, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { string[] audience; Uri destinationEndpoint = null; // if there is a via entityPath, include that in the audience if (!string.IsNullOrEmpty(viaEntityPath)) { destinationEndpoint = new Uri(ServiceEndpoint, viaEntityPath); var finalDestinationEndpoint = new Uri(ServiceEndpoint, entityPath); audience = new string[] { finalDestinationEndpoint.AbsoluteUri, destinationEndpoint.AbsoluteUri }; } else { destinationEndpoint = new Uri(ServiceEndpoint, entityPath); audience = new string[] { destinationEndpoint.AbsoluteUri }; } // Perform the initial authorization for the link. var authClaims = new[] { ServiceBusClaim.Send }; DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync( connection, TokenProvider, destinationEndpoint, audience, authClaims, timeout.CalculateRemaining(stopWatch.Elapsed)) .ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the link. var linkSettings = new AmqpLinkSettings { Role = false, InitialDeliveryCount = 0, Source = new Source { Address = Guid.NewGuid().ToString() }, Target = new Target { Address = destinationEndpoint.AbsolutePath } }; if (!string.IsNullOrEmpty(viaEntityPath)) { linkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, entityPath); } linkSettings.AddProperty(AmqpProperty.Timeout, (uint)timeout.CalculateRemaining(stopWatch.Elapsed).TotalMilliseconds); var link = new SendingAmqpLink(linkSettings); linkSettings.LinkName = $"{ Id };{ connection.Identifier }:{ session.Identifier }:{ link.Identifier }"; link.AttachTo(session); stopWatch.Stop(); // Configure refresh for authorization of the link. var refreshTimer = default(Timer); TimerCallback refreshHandler = CreateAuthorizationRefreshHandler ( entityPath, connection, link, TokenProvider, destinationEndpoint, audience, authClaims, AuthorizationRefreshTimeout, () => refreshTimer ); refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(entityPath, link, refreshTimer); return(link); } catch (Exception exception) { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw AmqpExceptionHelper.TranslateException( exception, null, session.GetInnerException(), connection.IsClosing()); } }
/// <summary> /// Creates an AMQP link for use with receiving operations. /// </summary> /// /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="endpoint">The fully qualified endpoint to open the link for.</param> /// <param name="eventPosition">The position of the event in the partition where the link should be filtered to.</param> /// <param name="consumerOptions">The set of active options for the consumer that will make use of the link.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use for operations related to receiving events.</returns> /// protected virtual async Task <ReceivingAmqpLink> CreateReceivingLinkAsync(AmqpConnection connection, Uri endpoint, EventPosition eventPosition, EventHubConsumerOptions consumerOptions, TimeSpan timeout, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { // Perform the initial authorization for the link. var authClaims = new[] { EventHubsClaim.Listen }; var authExpirationUtc = await RequestAuthorizationUsingCbsAsync(connection, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the link. var filters = new FilterSet(); filters.Add(AmqpFilter.ConsumerFilterName, AmqpFilter.CreateConsumerFilter(AmqpFilter.BuildFilterExpression(eventPosition))); var linkSettings = new AmqpLinkSettings { Role = true, TotalLinkCredit = (uint)consumerOptions.PrefetchCount, AutoSendFlow = consumerOptions.PrefetchCount > 0, SettleType = SettleMode.SettleOnSend, Source = new Source { Address = endpoint.AbsolutePath, FilterSet = filters }, Target = new Target { Address = Guid.NewGuid().ToString() } }; linkSettings.AddProperty(AmqpProperty.EntityType, (int)AmqpProperty.Entity.ConsumerGroup); if (!string.IsNullOrEmpty(consumerOptions.Identifier)) { linkSettings.AddProperty(AmqpProperty.ConsumerIdentifier, consumerOptions.Identifier); } if (consumerOptions.OwnerLevel.HasValue) { linkSettings.AddProperty(AmqpProperty.OwnerLevel, consumerOptions.OwnerLevel.Value); } if (consumerOptions.TrackLastEnqueuedEventInformation) { linkSettings.DesiredCapabilities = new Multiple <AmqpSymbol>(new List <AmqpSymbol> { AmqpProperty.TrackLastEnqueuedEventInformation }); } var link = new ReceivingAmqpLink(linkSettings); linkSettings.LinkName = $"{ Id };{ connection.Identifier };{ session.Identifier };{ link.Identifier }"; link.AttachTo(session); stopWatch.Stop(); // Configure refresh for authorization of the link. var refreshTimer = default(Timer); var refreshHandler = CreateAuthorizationRefreshHandler ( connection, link, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, AuthorizationRefreshTimeout, () => refreshTimer ); refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(link, refreshTimer); return(link); } catch { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw; } }
/// <summary> /// Creates an AMQP link for use with management operations. /// </summary> /// <param name="entityPath"></param> /// /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use with management operations.</returns> /// protected virtual async Task <RequestResponseAmqpLink> CreateManagementLinkAsync( string entityPath, AmqpConnection connection, TimeSpan timeout, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the link. var linkSettings = new AmqpLinkSettings(); linkSettings.AddProperty(AmqpProperty.Timeout, (uint)timeout.CalculateRemaining(stopWatch.Elapsed).TotalMilliseconds); linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, AmqpClientConstants.EntityTypeManagement); entityPath += '/' + AmqpClientConstants.ManagementAddress; // Perform the initial authorization for the link. string[] claims = { ServiceBusClaim.Manage, ServiceBusClaim.Listen, ServiceBusClaim.Send }; var endpoint = new Uri(ServiceEndpoint, entityPath); var audience = new[] { endpoint.AbsoluteUri }; DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync( connection, TokenProvider, ServiceEndpoint, audience, claims, timeout.CalculateRemaining(stopWatch.Elapsed)) .ConfigureAwait(false); var link = new RequestResponseAmqpLink( AmqpClientConstants.EntityTypeManagement, session, entityPath, linkSettings.Properties); linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}"; stopWatch.Stop(); // Track the link before returning it, so that it can be managed with the scope. var refreshTimer = default(Timer); TimerCallback refreshHandler = CreateAuthorizationRefreshHandler ( entityPath, connection, link, TokenProvider, ServiceEndpoint, audience, claims, AuthorizationRefreshTimeout, () => (ActiveLinks.ContainsKey(link) ? refreshTimer : null) ); refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(entityPath, link, refreshTimer); return(link); } catch (Exception exception) { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw AmqpExceptionHelper.TranslateException( exception, null, session.GetInnerException(), connection.IsClosing()); } }
private static async Task <AmqpIoTSendingLink> OpenSendingAmqpLinkAsync( DeviceIdentity deviceIdentity, AmqpSession amqpSession, byte?senderSettleMode, byte?receiverSettleMode, string deviceTemplate, string moduleTemplate, string linkSuffix, string correlationId, TimeSpan timeout ) { if (Logging.IsEnabled) { Logging.Enter(typeof(AmqpIoTSession), deviceIdentity, $"{nameof(OpenSendingAmqpLinkAsync)}"); } AmqpLinkSettings amqpLinkSettings = new AmqpLinkSettings { LinkName = linkSuffix, Role = false, InitialDeliveryCount = 0, Target = new Target() { Address = BuildLinkAddress(deviceIdentity, deviceTemplate, moduleTemplate) }, Source = new Source() { Address = deviceIdentity.IotHubConnectionString.DeviceId } }; amqpLinkSettings.SndSettleMode = senderSettleMode; amqpLinkSettings.RcvSettleMode = receiverSettleMode; amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.TimeoutName, timeout.TotalMilliseconds); amqpLinkSettings.AddProperty(AmqpIoTConstants.ClientVersion, deviceIdentity.ProductInfo.ToString()); if (correlationId != null) { amqpLinkSettings.AddProperty(AmqpIoTConstants.ChannelCorrelationId, correlationId); } if (!deviceIdentity.AmqpTransportSettings.AuthenticationChain.IsNullOrWhiteSpace()) { amqpLinkSettings.AddProperty(AmqpIoTConstants.AuthChain, deviceIdentity.AmqpTransportSettings.AuthenticationChain); } // This check is added to enable the device or module client to available plug and play features. For devices or modules that pass in the model Id, // the SDK will enable plug and play features by setting the modelId to Amqp link settings. if (!string.IsNullOrWhiteSpace(deviceIdentity.Options?.ModelId)) { amqpLinkSettings.AddProperty(AmqpIoTConstants.ModelId, deviceIdentity.Options.ModelId); } amqpLinkSettings.AddProperty(AmqpIoTConstants.ApiVersion, ClientApiVersionHelper.ApiVersionString); try { var sendingLink = new SendingAmqpLink(amqpLinkSettings); sendingLink.AttachTo(amqpSession); await sendingLink.OpenAsync(timeout).ConfigureAwait(false); return(new AmqpIoTSendingLink(sendingLink)); } catch (Exception e) when(!e.IsFatal()) { Exception ex = AmqpIoTExceptionAdapter.ConvertToIoTHubException(e, amqpSession); if (ReferenceEquals(e, ex)) { throw; } else { if (ex is AmqpIoTResourceException) { amqpSession.SafeClose(); throw new IotHubCommunicationException(ex.Message, ex); } throw ex; } } finally { if (Logging.IsEnabled) { Logging.Exit(typeof(AmqpIoTSession), deviceIdentity, $"{nameof(OpenSendingAmqpLinkAsync)}"); } } }
private async Task <SendingAmqpLink> CreateLinkAsync(TimeSpan timeout) { var amqpEventHubClient = ((AmqpEventHubClient)EventHubClient); var timeoutHelper = new TimeoutHelper(timeout); AmqpConnection connection = await amqpEventHubClient.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); // Authenticate over CBS AmqpCbsLink cbsLink = connection.Extensions.Find <AmqpCbsLink>(); ICbsTokenProvider cbsTokenProvider = amqpEventHubClient.CbsTokenProvider; Uri address = new Uri(amqpEventHubClient.ConnectionStringBuilder.Endpoint, Path); string audience = address.AbsoluteUri; string resource = address.AbsoluteUri; DateTime expiresAt = await cbsLink.SendTokenAsync( cbsTokenProvider, address, audience, resource, new[] { ClaimConstants.Send }, timeoutHelper.RemainingTime()).ConfigureAwait(false); AmqpSession session = null; try { // Create our Session var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); // Create our Link var linkSettings = new AmqpLinkSettings(); linkSettings.AddProperty(AmqpClientConstants.TimeoutName, (uint)timeoutHelper.RemainingTime().TotalMilliseconds); linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)MessagingEntityType.EventHub); linkSettings.Role = false; linkSettings.InitialDeliveryCount = 0; linkSettings.Target = new Target { Address = address.AbsolutePath }; linkSettings.Source = new Source { Address = ClientId }; var link = new SendingAmqpLink(linkSettings); linkSettings.LinkName = $"{amqpEventHubClient.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}"; link.AttachTo(session); await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); var activeClientLink = new ActiveClientLink( link, audience, // audience EventHubClient.ConnectionStringBuilder.Endpoint.AbsoluteUri, // endpointUri new[] { ClaimConstants.Send }, true, expiresAt); MaxMessageSize = (long)activeClientLink.Link.Settings.MaxMessageSize(); _clientLinkManager.SetActiveLink(activeClientLink); _linkCreated = true; return(link); } catch { // Cleanup any session (and thus link) in case of exception. session?.Abort(); throw; } }
async Task <ReceivingAmqpLink> CreateLinkAsync(TimeSpan timeout) { var amqpEventHubClient = ((AmqpEventHubClient)this.EventHubClient); var timeoutHelper = new TimeoutHelper(timeout); AmqpConnection connection = await amqpEventHubClient.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); // Authenticate over CBS var cbsLink = connection.Extensions.Find <AmqpCbsLink>(); ICbsTokenProvider cbsTokenProvider = amqpEventHubClient.CbsTokenProvider; Uri address = new Uri(amqpEventHubClient.ConnectionStringBuilder.Endpoint, this.Path); string audience = address.AbsoluteUri; string resource = address.AbsoluteUri; var expiresAt = await cbsLink.SendTokenAsync(cbsTokenProvider, address, audience, resource, new[] { ClaimConstants.Listen }, timeoutHelper.RemainingTime()).ConfigureAwait(false); AmqpSession session = null; try { // Create our Session var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); FilterSet filterMap = null; var filters = this.CreateFilters(); if (filters != null && filters.Count > 0) { filterMap = new FilterSet(); foreach (var filter in filters) { filterMap.Add(filter.DescriptorName, filter); } } // Create our Link var linkSettings = new AmqpLinkSettings { Role = true, TotalLinkCredit = (uint)this.PrefetchCount, AutoSendFlow = this.PrefetchCount > 0 }; linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)MessagingEntityType.ConsumerGroup); linkSettings.Source = new Source { Address = address.AbsolutePath, FilterSet = filterMap }; linkSettings.Target = new Target { Address = this.ClientId }; linkSettings.SettleType = SettleMode.SettleOnSend; // Receiver metrics enabled? if (this.ReceiverRuntimeMetricEnabled) { linkSettings.DesiredCapabilities = new Multiple <AmqpSymbol>(new List <AmqpSymbol> { AmqpClientConstants.EnableReceiverRuntimeMetricName }); } if (this.Epoch.HasValue) { linkSettings.AddProperty(AmqpClientConstants.AttachEpoch, this.Epoch.Value); } if (!string.IsNullOrWhiteSpace(this.Identifier)) { linkSettings.AddProperty(AmqpClientConstants.ReceiverIdentifierName, this.Identifier); } var link = new ReceivingAmqpLink(linkSettings); linkSettings.LinkName = $"{amqpEventHubClient.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}"; link.AttachTo(session); await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); var activeClientLink = new ActiveClientLink( link, audience, // audience this.EventHubClient.ConnectionStringBuilder.Endpoint.AbsoluteUri, // endpointUri new[] { ClaimConstants.Listen }, true, expiresAt); this.clientLinkManager.SetActiveLink(activeClientLink); return(link); } catch { // Cleanup any session (and thus link) in case of exception. session?.SafeClose(); throw; } }
private static async Task <AmqpIoTSendingLink> OpenSendingAmqpLinkAsync( DeviceIdentity deviceIdentity, AmqpSession amqpSession, byte?senderSettleMode, byte?receiverSettleMode, string deviceTemplate, string moduleTemplate, string linkSuffix, string CorrelationId, TimeSpan timeout ) { if (Logging.IsEnabled) { Logging.Enter(typeof(AmqpIoTSession), deviceIdentity, $"{nameof(OpenSendingAmqpLinkAsync)}"); } AmqpLinkSettings amqpLinkSettings = new AmqpLinkSettings { LinkName = linkSuffix, Role = false, InitialDeliveryCount = 0, Target = new Target() { Address = BuildLinkAddress(deviceIdentity, deviceTemplate, moduleTemplate) }, Source = new Source() { Address = deviceIdentity.IotHubConnectionString.DeviceId } }; amqpLinkSettings.SndSettleMode = senderSettleMode; amqpLinkSettings.RcvSettleMode = receiverSettleMode; amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.TimeoutName, timeout.TotalMilliseconds); amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ClientVersion, deviceIdentity.ProductInfo.ToString()); amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ApiVersion, ClientApiVersionHelper.ApiVersionString); if (CorrelationId != null) { amqpLinkSettings.AddProperty(AmqpIoTErrorAdapter.ChannelCorrelationId, CorrelationId); } try { SendingAmqpLink sendingLink = new SendingAmqpLink(amqpLinkSettings); sendingLink.AttachTo(amqpSession); await sendingLink.OpenAsync(timeout).ConfigureAwait(false); return(new AmqpIoTSendingLink(sendingLink)); } catch (Exception e) when(!e.IsFatal()) { Exception ex = AmqpIoTExceptionAdapter.ConvertToIoTHubException(e, amqpSession); if (ReferenceEquals(e, ex)) { throw; } else { if (ex is AmqpIoTResourceException) { amqpSession.SafeClose(); } throw new IotHubCommunicationException(ex.Message, ex); } } finally { if (Logging.IsEnabled) { Logging.Exit(typeof(AmqpIoTSession), deviceIdentity, $"{nameof(OpenSendingAmqpLinkAsync)}"); } } }
protected static AmqpLinkSettings SetLinkSettingsCommonPropertiesForMethod(AmqpLinkSettings linkSettings, string corrId) { linkSettings.AddProperty(IotHubAmqpProperty.ApiVersion, ClientApiVersionHelper.ApiVersionString); linkSettings.AddProperty(IotHubAmqpProperty.ChannelCorrelationId, "methods:" + corrId); return(linkSettings); }