public static int VerifyListen(string connectionString, string path, Binding binding, ConnectivityMode connectivityMode, string response, ServiceThrottlingBehavior throttlingBehavior) { RelayTraceSource.TraceInfo($"Open relay listener using {binding.GetType().Name}, ConnectivityMode.{connectivityMode}..."); ServiceHost serviceHost = null; try { var connectionStringBuilder = new ServiceBusConnectionStringBuilder(connectionString); var tp = TokenProvider.CreateSharedAccessSignatureTokenProvider(connectionStringBuilder.SharedAccessKeyName, connectionStringBuilder.SharedAccessKey); string relayNamespace = connectionStringBuilder.Endpoints.First().Host; ServiceBusEnvironment.SystemConnectivity.Mode = connectivityMode; EchoService.DefaultResponse = response; if (!(binding is WebHttpRelayBinding)) { serviceHost = new ServiceHost(typeof(EchoService)); } else { serviceHost = new WebServiceHost(typeof(EchoService)); } Type contractType = IsOneWay(binding) ? typeof(ITestOneway) : typeof(IEcho); ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(contractType, binding, new Uri($"{binding.Scheme}://{relayNamespace}/{path}")); var listenerActivityId = Guid.NewGuid(); RelayTraceSource.TraceVerbose($"Listener ActivityId:{listenerActivityId}"); endpoint.EndpointBehaviors.Add(new TransportClientEndpointBehavior(tp) { ActivityId = listenerActivityId }); serviceHost.Description.Behaviors.Add(throttlingBehavior); // Trace status changes var connectionStatus = new ConnectionStatusBehavior(); connectionStatus.Connecting += (s, e) => RelayTraceSource.TraceException(connectionStatus.LastError, TraceEventType.Warning, "Relay listener Re-Connecting"); connectionStatus.Online += (s, e) => RelayTraceSource.Instance.TraceEvent(TraceEventType.Information, (int)ConsoleColor.Green, "Relay Listener is online"); EventHandler offlineHandler = (s, e) => RelayTraceSource.TraceException(connectionStatus.LastError, "Relay Listener is OFFLINE"); connectionStatus.Offline += offlineHandler; endpoint.EndpointBehaviors.Add(connectionStatus); serviceHost.Faulted += (s, e) => RelayTraceSource.TraceException(connectionStatus.LastError, "Relay listener ServiceHost Faulted"); serviceHost.Open(); RelayTraceSource.TraceInfo("Relay listener \"" + endpoint.Address.Uri + "\" is open"); RelayTraceSource.TraceInfo("Press <ENTER> to close the listener "); Console.ReadLine(); RelayTraceSource.TraceInfo("Closing Connection..."); connectionStatus.Offline -= offlineHandler; // Avoid a spurious trace on expected shutdown. serviceHost.Close(); RelayTraceSource.TraceInfo("Closed"); return(0); } catch (Exception) { serviceHost?.Abort(); throw; } }
//--- 1 public QueueWriter(IQueueConfig queueConfig) { #region AzureServiceBusAMQP CreateConnection /// <summary> /// Attempt to connect with a valid connection string /// </summary> /// <param name="UserName">AppSettings.Get("mq.user")</param> /// <param name="Password">AppSettings.Get("mq.pass")</param> /// <param name="RequestedHeartbeat">30</param> /// <param name="Handle<BrokerUnreachableException>()"></param> /// <param name="Retry(tries)">5</param> /// <returns></returns> try { connectionString = queueConfig.PrimaryConnectionString; password = queueConfig.Password; userName = queueConfig.UserName; queueName = queueConfig.QueueName; queueNameNew = queueConfig.QueueNameNew; queueNameDel = queueConfig.QueueNameDel; Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", userName, string.Empty); // Create management credentials //---TokenProvider credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(sasKeyName, sasKeyValue); //---Microsoft.ServiceBus.TokenProvider tokenProvider = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider(nameKey, password); Microsoft.ServiceBus.TokenProvider credentials = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", password); Microsoft.ServiceBus.TokenProvider tokenProvider = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", password); NamespaceManager namespaceManager = new NamespaceManager(uri, tokenProvider); // Create if not exists new one if (namespaceManager.QueueExists(queueName)) { queueClient = new Microsoft.Azure.ServiceBus.QueueClient(connectionString, queueName, Microsoft.Azure.ServiceBus.ReceiveMode.PeekLock); Debug.WriteLine($"{DateTime.Now.TimeOfDay} : Queue opened successfully.", queueConfig.QueueName); //IQueueClient queueClient = new Microsoft.Azure.ServiceBus.QueueClient(connectionString, queueConfig.QueueName, Microsoft.Azure.ServiceBus.ReceiveMode.PeekLock); //Debug.WriteLine(" Queue opened successfully.", queueConfig.QueueName); } else { //namespaceManager.CreateQueue(queueNameNew); // Configure queue settings. var queueDescription = new QueueDescription(queueNameNew); queueDescription.MaxSizeInMegabytes = 1024; // Setting message TTL to 7 days where as default TTL is 14 days. queueDescription.DefaultMessageTimeToLive = TimeSpan.FromDays(7); //--- https://stackoverflow.com/questions/44720880/cant-create-queue namespaceManager.CreateQueue(new QueueDescription(queueNameNew) { DefaultMessageTimeToLive = TimeSpan.FromDays(7), LockDuration = TimeSpan.FromSeconds(30), EnablePartitioning = true, AutoDeleteOnIdle = TimeSpan.FromDays(1), MaxSizeInMegabytes = 1024 }); Debug.WriteLine($"{DateTime.Now.TimeOfDay} : Queue Created successfully. ", queueNameNew); } //--- ReceiveMessagesAsync().GetAwaiter().GetResult(); } catch (Exception ex) { logger.Error($"Tries happened {maxTrials} times. Throwing the exception.{ex}"); throw; } #endregion }
//--- 7 public void DeleteQueue(List <string> queueNameList) { //var index = 0; // using (var connection = factory.CreateConnection()) // { // using (var channel = connection.CreateModel()) // { // for (; index < queueNameList.Count; index++) // { // var queueName = queueNameList[index]; // channel.QueueDelete(queueName); // } // } // } /* * * * // Configure queue settings. * this.queueDescription = new QueueDescription(MyQueuePath); * this.queueDescription.MaxSizeInMegabytes = 1024; * // Setting message TTL to 5 days where as default TTL is 14 days. * this.queueDescription.DefaultMessageTimeToLive = TimeSpan.FromDays(7); * * // Create management credentials. * this.credential = new TransportClientEndpointBehavior() * { * TokenProvider = Microsoft.ServiceBus.TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret) * //TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(issuerName, issuerSecret) * }; * * // Create the URI for the queue. * this.namespaceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, String.Empty); * Debug.WriteLine("Service Bus Namespace Uri address '{0}'", this.namespaceUri.AbsoluteUri); * * var settings = new NamespaceManagerSettings() { TokenProvider = credential.TokenProvider }; * var namespaceClient = new Microsoft.ServiceBus.NamespaceManager(namespaceUri, settings); */ //--- //--- https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-create-queues //string name = "RootManageSharedAccessKey"; //string nameKey = "RootManageSharedAccessKey"; //var password = queueConfig.Password; //var userName = queueConfig.UserName; //var queueNameDel = queueConfig.QueueNameDel; //Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", "dacgroup-phoenix-test", string.Empty); Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", userName, string.Empty); // Create management credentials //---TokenProvider credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(sasKeyName, sasKeyValue); //---Microsoft.ServiceBus.TokenProvider tokenProvider = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider(nameKey, password); Microsoft.ServiceBus.TokenProvider credentials = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", password); Microsoft.ServiceBus.TokenProvider tokenProvider = Microsoft.ServiceBus.TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", password); NamespaceManager namespaceManager = new NamespaceManager(uri, tokenProvider); //namespaceManager.CreateQueue("DACQueue4"); try { //--- Delete if exists if (namespaceManager.QueueExists(queueNameDel)) { namespaceManager.DeleteQueue(queueNameDel); Debug.WriteLine("Queue deleted successfully.", queueNameDel); } } catch (FaultException e) { Debug.WriteLine("Exception when deleting queue..", e); logger.Trace($"Exception when deleting queue.. {0}: {e}"); throw; } }
public WebSocketConnectionInitiator(TokenProvider tokenProvider, int bufferSize) { this.tokenProvider = tokenProvider; this.bufferSize = bufferSize; }
public RelayHttpTransportChannelFactory(BindingContext context, IChannelFactory <IRequestChannel> innerChannelFactory) : base(context.Binding, innerChannelFactory) { this.innerChannelFactory = innerChannelFactory; this.tokenProvider = TokenProviderUtility.CreateTokenProvider(context); }
static int VerifySendCore <TChannel>( string request, string relayNamespace, string path, int number, Binding binding, bool noClientAuth, ConnectivityMode connectivityMode, string keyName, string keyValue, TimeSpan requestDelay) where TChannel : class, IClientChannel { ChannelFactory <TChannel> channelFactory = null; TChannel channel = null; try { ServiceBusEnvironment.SystemConnectivity.Mode = connectivityMode; Uri address = new Uri($"{binding.Scheme}://{relayNamespace}/{path}"); if (binding is WebHttpRelayBinding) { channelFactory = new WebChannelFactory <TChannel>(binding, address); } else { channelFactory = new ChannelFactory <TChannel>(binding, new EndpointAddress(address)); } var tp = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, keyValue); if (!noClientAuth) { channelFactory.Endpoint.EndpointBehaviors.Add(new TransportClientEndpointBehavior(tp)); } RelayTraceSource.TraceVerbose("Sender opening channel factory"); var stopwatch = new Stopwatch(); stopwatch.Restart(); channelFactory.Open(); RelayTraceSource.TraceVerbose($"Sender opened channel factory in {stopwatch.ElapsedMilliseconds} ms"); channel = channelFactory.CreateChannel(); RelayTraceSource.TraceInfo("Sender opening channel"); using (new OperationContextScope(channel)) { Guid trackingId = Guid.NewGuid(); RelayTraceSource.TraceVerbose($"Channel TrackingId:{trackingId}"); if (binding.MessageVersion.Addressing != AddressingVersion.None) { OperationContext.Current.OutgoingMessageHeaders.MessageId = new UniqueId(trackingId); } stopwatch.Restart(); channel.Open(); RelayTraceSource.TraceVerbose($"Sender opened channel in {stopwatch.ElapsedMilliseconds} ms"); RelayTraceSource.TraceVerbose($"Channel SessionId:{channel.SessionId}"); } for (int i = 0; i < number; i++) { using (new OperationContextScope(channel)) { var messageId = Guid.NewGuid(); RelayTraceSource.TraceVerbose($"Sending MessageId:{messageId}"); if (binding.MessageVersion.Addressing != AddressingVersion.None) { OperationContext.Current.OutgoingMessageHeaders.MessageId = new UniqueId(messageId); } stopwatch.Restart(); if (channel is IEchoClient echoChannel) { string response = echoChannel.Echo(DateTime.UtcNow, request, requestDelay); RelayTraceSource.TraceInfo($"Sender received response: {response} ({stopwatch.ElapsedMilliseconds} ms)"); } else if (channel is ITestOnewayClient onewayClient) { onewayClient.Operation(DateTime.UtcNow, request); RelayTraceSource.TraceInfo($"Sender sent oneway request: {request} ({stopwatch.ElapsedMilliseconds} ms)"); } else { throw new NotSupportedException($"Contract {typeof(TChannel)} is not supported"); } } } RelayTraceSource.TraceInfo("Sender closing channel"); stopwatch.Restart(); channel.Close(); RelayTraceSource.TraceVerbose($"Sender closed channel in {stopwatch.ElapsedMilliseconds} ms"); channel = null; RelayTraceSource.TraceVerbose("Sender closing channel factory"); stopwatch.Restart(); channelFactory.Close(); RelayTraceSource.TraceVerbose($"Sender closed channel factory in {stopwatch.ElapsedMilliseconds} ms"); channelFactory = null; return(0); } finally { channel?.Abort(); channelFactory?.Abort(); } }
public RelayedSocketElement(BindingContext context, NameSettings nameSettings, TokenProvider tokenProvider, SocketSecurityRole socketSecurityMode) { this.context = context; this.nameSettings = nameSettings; this.tokenProvider = tokenProvider; this.socketSecurityMode = socketSecurityMode; ConnectivitySettingsEndpointBehavior connectivitySettingsEndpointBehavior = null; ConnectivitySettings connectivitySetting = this.context.BindingParameters.Find <ConnectivitySettings>(); HttpConnectivitySettings httpConnectivitySetting = this.context.BindingParameters.Find <HttpConnectivitySettings>(); if (connectivitySetting != null || httpConnectivitySetting != null) { connectivitySettingsEndpointBehavior = new ConnectivitySettingsEndpointBehavior(connectivitySetting, httpConnectivitySetting); } this.connectionListener = new RelayedSocketListener(this.tokenProvider, this.nameSettings, this.socketSecurityMode, connectivitySettingsEndpointBehavior); }
public HybridConnectionInitiator(BindingContext context, TcpRelayTransportBindingElement transportBindingElement, int bufferSize, TokenProvider tokenProvider, RelayTransportProtectionMode transportProtection) { this.bufferSize = bufferSize; NameSettings nameSetting = new NameSettings(); nameSetting.ServiceSettings.TransportProtection = transportProtection; nameSetting.ServiceSettings.ListenerType = ListenerType.HybridConnection; IConnectionElement relayedSocketElement = new RelayedSocketElement(context, nameSetting, tokenProvider, SocketSecurityRole.None); this.relayedSocketInitiator = (new DemuxSocketElement(relayedSocketElement, "relayed")).CreateInitiator(bufferSize); IConnectionElement demuxSocketElement = new DemuxSocketElement(relayedSocketElement, "direct"); Binding binding = HybridConnectionElement.CreateDirectControlBindingElement(context, transportBindingElement, demuxSocketElement); this.directSocketInitiator = new DirectSocketInitiator(bufferSize, binding); this.connectionId = Guid.NewGuid(); }