static void Main(string[] args)
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            TransportClientEndpointBehavior relayCredentials = new TransportClientEndpointBehavior();

            relayCredentials.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "HelloService");

            ServiceHost host = new ServiceHost(typeof(HelloService), address);

            host.Description.Endpoints[0].Behaviors.Add(relayCredentials);
            host.Open();

            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            host.Close();
        }
Exemple #2
0
        private MessageBufferClient GetOrCreateQueue(TransportClientEndpointBehavior sharedSecredServiceBusCredential, Uri queueUri, ref MessageBufferPolicy queuePolicy)
        {
            MessageBufferClient client;

            try
            {
                client = MessageBufferClient.GetMessageBuffer(sharedSecredServiceBusCredential, queueUri);
                MessageBufferPolicy currentQueuePolicy = client.GetPolicy();
                queuePolicy = currentQueuePolicy;
                // Queue already exists.
                return(client);
            }
            //catch (EndpointNotFoundException)
            catch (FaultException)
            {
                // Exception when retrieving the current queue policy.
                // Queue Not found; absorb and make a new queue below.
                // Other exceptions get bubbled up.
            }
            catch (Exception)
            {
            }
            try
            {
                client = MessageBufferClient.CreateMessageBuffer(sharedSecredServiceBusCredential, queueUri, queuePolicy);
            }
            catch (Exception)
            {
                throw;
            }
            //Created new Queue.
            return(client);
        }
Exemple #3
0
        static void Main(string[] args)
        {
            // Replace {service namespace} with your service name space.
            EndpointAddress       address = new EndpointAddress(ServiceBusEnvironment.CreateServiceUri("https", "{service namespace}", "ProcessDataWorkflowService"));
            BasicHttpRelayBinding binding = new BasicHttpRelayBinding();

            // Provide the Service Bus credential.
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

            sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;
            // Replace {issuer name} and {issuer secret} with your credential.
            sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName   = "{issuer name}";
            sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = "{issuer secret}";

            ChannelFactory <IProcessDataWorkflowServiceChannel> factory = new ChannelFactory <IProcessDataWorkflowServiceChannel>(binding, address);

            factory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            factory.Open();
            IProcessDataWorkflowServiceChannel channel = factory.CreateChannel();

            channel.Open();
            Console.WriteLine("Processing 10...");
            Console.WriteLine("Service returned: " + channel.ProcessData(new ProcessDataRequest(0)).@string);
            Console.WriteLine("Processing 30...");
            Console.WriteLine("Service returned: " + channel.ProcessData(new ProcessDataRequest(30)).@string);
            channel.Close();
            factory.Close();
            Console.Read();
        }
Exemple #4
0
        static void Main(string[] args)
        {
            string           connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            NamespaceManager namespaceClient  = NamespaceManager.CreateFromConnectionString(connectionString);
            Uri         address = new Uri(namespaceClient.Address, "Customer");
            ServiceHost host    = new ServiceHost(typeof(CustomerService), address);

            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

            sharedSecretServiceBusCredential.TokenProvider = namespaceClient.Settings.TokenProvider;

            var endpoint = host.AddServiceEndpoint(typeof(ICustomerContract), new NetTcpRelayBinding("default"), address);

            endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

            host.Open();

            checkDatabase();

            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            host.Close();
        }
        static void Main(string[] args)
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your SAS Key Name (e.g., \"RootManageSharedAccessKey\"): ");
            string keyName = Console.ReadLine();

            Console.Write("Your SAS Key: ");
            string key = Console.ReadLine();

            // WebHttpRelayBinding uses transport security by default
            Uri address = ServiceBusEnvironment.CreateServiceUri("https", serviceNamespace, "SyndicationService");

            TransportClientEndpointBehavior clientBehavior = new TransportClientEndpointBehavior();

            clientBehavior.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key);

            WebServiceHost host = new WebServiceHost(typeof(SyndicationService), address);

            host.Description.Endpoints[0].Behaviors.Add(clientBehavior);
            host.Open();

            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            host.Close();
        }
Exemple #6
0
        static void Main(string[] args)
        {
            var host = new ServiceHost(typeof (Calculator));

            var relayBinding = new WebHttpRelayBinding {MaxReceivedMessageSize = int.MaxValue};
            relayBinding.Security.Mode = EndToEndWebHttpSecurityMode.Transport;
            relayBinding.Security.RelayClientAuthenticationType = RelayClientAuthenticationType.RelayAccessToken;

            var sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            if (sdb == null)
            {
                sdb.IncludeExceptionDetailInFaults = true;
                host.Description.Behaviors.Add(sdb);
            }

            var endpoint = host.AddServiceEndpoint(typeof (ICalculator), relayBinding, uri);
            var sharedSecretBehavior = new TransportClientEndpointBehavior
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret)
            };
            endpoint.Behaviors.Add(sharedSecretBehavior);
            endpoint.Behaviors.Add(new WebHttpBehavior());

            host.Open();

            Console.WriteLine("Host opened at {0}", uri);
            Console.Read();
        }
Exemple #7
0
        public override void Run()
        {
            // Retrieve Settings from App.Config
            string servicePath      = ConfigurationManager.AppSettings["ServicePath"];
            string serviceNamespace = ConfigurationManager.AppSettings["ServiceNamespace"];
            string issuerName       = ConfigurationManager.AppSettings["IssuerName"];
            string issuerSecret     = ConfigurationManager.AppSettings["IssuerSecret"];

            // Construct a Service Bus URI
            Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, servicePath);

            // Create a Behavior for the Credentials
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

            sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);


            // Create the Service Host
            host = new ServiceHost(typeof(EchoService), uri);
            ContractDescription contractDescription = ContractDescription.GetContract(typeof(IEchoContract), typeof(EchoService));
            ServiceEndpoint     serviceEndPoint     = new ServiceEndpoint(contractDescription);

            serviceEndPoint.Address = new EndpointAddress(uri);
            serviceEndPoint.Binding = new NetTcpRelayBinding();
            serviceEndPoint.Behaviors.Add(sharedSecretServiceBusCredential);
            host.Description.Endpoints.Add(serviceEndPoint);

            // Open the Host
            host.Open();

            while (true)
            {
                //Do Nothing
            }
        }
      public override void Refresh(ServiceBusNode node,TransportClientEndpointBehavior credential)
      {
         MessageBufferPolicy policy = node.Policy as MessageBufferPolicy;

         int overflowIndex = 0;
         switch(policy.OverflowPolicy)
         {
            case OverflowPolicy.RejectIncomingMessage:
            {
               overflowIndex = 0;
               break;
            }
            default:
            {
               throw new InvalidOperationException("Unrecognized overflow value");
            }
         }
         m_OverflowComboBox.Text = m_OverflowComboBox.Items[overflowIndex] as string;

         m_ExpirationTime.Text = policy.ExpiresAfter.TotalMinutes.ToString();

         m_CountTextBox.Text = policy.MaxMessageCount.ToString();

         base.Refresh(node,credential);
      }
Exemple #9
0
        //The same as two, but different style creating environments
        private static void WS2007HttpRelayClientOne()
        {
            Console.WriteLine("Please enter any key to contact server...");
            Console.ReadLine();

            // Configure the credentials through an endpoint behavior.
            TransportClientEndpointBehavior relayCredentials = new TransportClientEndpointBehavior();
            relayCredentials.TokenProvider =
              TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", "fBLL/4/+rEsCOiTQPNPS6DJQybykqE2HdVBsILrzMLY=");

            // Get the service address.
            // Use the https scheme because by default the binding uses SSL for transport security.
            Uri address = ServiceBusEnvironment.CreateServiceUri("https", "johnsonwangnz", "MyService");

            // Create the binding with default settings.
            WS2007HttpRelayBinding binding = new WS2007HttpRelayBinding();

            // Create a channel factory for the specified channel type.
            // This channel factory is used to create client channels to the service.
            // Each client channel the channel factory creates is configured to use the
            // WS2007HttpRelayBinding that is passed to the constructor of the channel.
            var channelFactory = new ChannelFactory<IEchoContract>(
                binding, new EndpointAddress(address));

            channelFactory.Endpoint.Behaviors.Add(relayCredentials);

            // Create and open the client channel.
            IEchoContract echoService = channelFactory.CreateChannel();

            var result = echoService.Echo("HelloWorld!");

            Console.WriteLine(result);

            Console.ReadLine();
        }
        public Consumer()
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            // Configure queue settings.
            this.queueDescription = new QueueDescription(MyQueuePath);
            // Setting Max Size and TTL for demonstration purpose
            // but can be changed per user discretion to suite their system needs.
            // Refer service bus documentation to understand the limitations.
            // Setting Queue max size to 1GB where as default Max Size is 5GB.
            this.queueDescription.MaxSizeInMegabytes = 1024;
            // Setting message TTL to 5 days where as default TTL is 14 days.
            this.queueDescription.DefaultMessageTimeToLive = TimeSpan.FromDays(5);

            // Create management credentials.
            this.credential = new TransportClientEndpointBehavior()
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret)
            };

            // Create the URI for the queue.
            this.namespaceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, String.Empty);
            Console.WriteLine("Service Bus Namespace Uri address '{0}'", this.namespaceUri.AbsoluteUri);
        }
        public async Task Run(string namespaceAddress, string queueName, string receiveToken)
        {
            try
            {
                // Create MessageReceiver for queue which requires session
                Console.WriteLine("Ready to receive messages from {0}...",queueName);

                // Creating the service host object as defined in config
                using (var serviceHost = new ServiceHost(typeof (SequenceProcessingService), new Uri(new Uri(namespaceAddress), queueName)))
                {
                    var authBehavior = new TransportClientEndpointBehavior(TokenProvider.CreateSharedAccessSignatureTokenProvider(receiveToken));
                    serviceHost.Description.Behaviors.Add(new ErrorServiceBehavior());
                    foreach (var ep in serviceHost.Description.Endpoints) { ep.EndpointBehaviors.Add(authBehavior);}

                    // Subscribe to the faulted event.
                    serviceHost.Faulted += serviceHost_Faulted;

                    // Start service
                    serviceHost.Open();

                    Console.WriteLine("\nPress [Enter] to close ServiceHost.");
                    Console.ReadLine();

                    // Close the service
                    serviceHost.Close();
                }
            }
            catch (Exception exception)
            {
               Console.WriteLine("Exception occurred: {0}", exception);
                Console.WriteLine("\nPress [Enter] to exit.");
                Console.ReadLine();
            }
        }
        private void InitBindingInCode(string solutionName, string solutionPassword, string servicePath, ConnectivityMode onewayConnectivityMode, Type serviceType)
        {
            //ServiceBusEnvironment.OnewayConnectivity.Mode = onewayConnectivityMode;



            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", solutionName, servicePath);

            ServiceUri = address.ToString();
            Host       = new ServiceHost(serviceType, address);

            ContractDescription contractDescription = ContractDescription.GetContract(typeof(IOnewayEnergyServiceOperations), typeof(OnewayEnergyServiceOperations));
            ServiceEndpoint     serviceEndPoint     = new ServiceEndpoint(contractDescription);

            serviceEndPoint.Address = new EndpointAddress(ServiceUri);
            serviceEndPoint.Binding = new NetOnewayRelayBinding();

            TransportClientEndpointBehavior behavior = ServiceBusHelper.GetUsernamePasswordBehavior(solutionName, solutionPassword);

            serviceEndPoint.Behaviors.Add(behavior);
            Host.Description.Endpoints.Add(serviceEndPoint);

            ServiceRegistrySettings settings = new ServiceRegistrySettings();

            settings.DiscoveryMode = DiscoveryType.Public;
            settings.DisplayName   = address.ToString();
            foreach (ServiceEndpoint se in Host.Description.Endpoints)
            {
                se.Behaviors.Add(settings);
            }

            Host.Open();
        }
        //typeof(OnewayEnergyServiceOperations)
        private void InitService(string serviceNamespace, string issuerName, string issuerKey, string servicePath, ConnectivityMode onewayConnectivityMode, Type serviceType, bool usePassword)
        {
            ServiceBusEnvironment.SystemConnectivity.Mode = onewayConnectivityMode;

            // Host = new ServiceHost(serviceType, address);
            Host = new ServiceHost(serviceType);
            if (usePassword)
            {
                TransportClientEndpointBehavior behavior = ServiceBusHelper.GetUsernamePasswordBehavior(issuerName, issuerKey);
                Host.Description.Endpoints[0].Behaviors.Add(behavior);
            }

            ServiceUri = Host.Description.Endpoints[0].ListenUri.ToString();
            ServiceRegistrySettings settings = new ServiceRegistrySettings();

            settings.DiscoveryMode = DiscoveryType.Public;
            settings.DisplayName   = ServiceUri;
            foreach (ServiceEndpoint se in Host.Description.Endpoints)
            {
                se.Behaviors.Add(settings);
            }


            Host.Open();
        }
Exemple #14
0
        private void InitNetEventRelayClient()
        {
            string issuerName             = tsSolutionName.Text;
            string issuerKey              = tsSolutionPassword.Text;
            string serviceNamespaceDomain = tsSolutionToConnect.Text;

            try
            {
                TransportClientEndpointBehavior behavior = new TransportClientEndpointBehavior();
                string token = SharedSecretTokenProvider.ComputeSimpleWebTokenString(issuerName, issuerKey);
                behavior.TokenProvider = SimpleWebTokenProvider.CreateSimpleWebTokenProvider(token);
                Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "Gateway/MulticastService/");

                // netEventRelayChannelFactory = new ChannelFactory<IMulticastGatewayChannel>("RelayMulticastEndpoint", new EndpointAddress(serviceUri));
                netEventRelayChannelFactory = new ChannelFactory <IMulticastGatewayChannel>("RelayMulticastEndpoint");
                netEventRelayChannelFactory.Endpoint.Behaviors.Add(behavior);
                netEventRelayChannel = netEventRelayChannelFactory.CreateChannel();
                netEventRelayChannel.Open();

                SendONLINEValue();
                AddLog("Connected to " + netEventRelayChannelFactory.Endpoint.Address.Uri.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #15
0
        public override void Refresh(ServiceBusNode node, TransportClientEndpointBehavior credential)
        {
            MessageBufferPolicy policy = node.Policy as MessageBufferPolicy;

            int overflowIndex = 0;

            switch (policy.OverflowPolicy)
            {
            case OverflowPolicy.RejectIncomingMessage:
            {
                overflowIndex = 0;
                break;
            }

            default:
            {
                throw new InvalidOperationException("Unrecognized overflow value");
            }
            }
            m_OverflowComboBox.Text = m_OverflowComboBox.Items[overflowIndex] as string;

            m_ExpirationTime.Text = policy.ExpiresAfter.TotalMinutes.ToString();

            m_CountTextBox.Text = policy.MaxMessageCount.ToString();

            base.Refresh(node, credential);
        }
        void EnableDiscovery()
        {
            Debug.Assert(State != CommunicationState.Opened);

            IEndpointBehavior registryBehavior = new ServiceRegistrySettings(DiscoveryType.Public);

            foreach (ServiceEndpoint endpoint in Description.Endpoints)
            {
                endpoint.Behaviors.Add(registryBehavior);
            }


            //Launch the service to monitor discovery requests

            DiscoveryRequestService discoveryService = new DiscoveryRequestService(Description.Endpoints.ToArray());

            discoveryService.DiscoveryResponseBinding = DiscoveryResponseBinding;

            m_DiscoveryHost = new ServiceHost(discoveryService);

            m_DiscoveryHost.AddServiceEndpoint(typeof(IServiceBusDiscovery), DiscoveryRequestBinding, DiscoveryAddress.AbsoluteUri);

            TransportClientEndpointBehavior credentials = (this as IServiceBusProperties).Credential;

            m_DiscoveryHost.Description.Endpoints[0].Behaviors.Add(credentials);

            m_DiscoveryHost.Description.Endpoints[0].Behaviors.Add(registryBehavior);

            m_DiscoveryHost.Open();
        }
        static void Main(string[] args)
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();
            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();
            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            TransportClientEndpointBehavior relayCredentials = new TransportClientEndpointBehavior();
            relayCredentials.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "CalculatorService");

            //ServiceHost host = new ServiceHost(typeof(CalculatorService));
            ServiceHost host = new ServiceHost(typeof(CalculatorService), address);
            host.Description.Endpoints[0].Behaviors.Add(relayCredentials);
            host.Open();

            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            host.Close();
        }
Exemple #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("CloudTrace Console");
            Console.WriteLine("Connecting ...");

            //Retrieve Settings from App.Config
            string servicePath = ConfigurationManager.AppSettings["CloudTraceServicePath"];
            string serviceNamespace = ConfigurationManager.AppSettings["CloudTraceServiceNamespace"];
            string issuerName = ConfigurationManager.AppSettings["CloudTraceIssuerName"];
            string issuerSecret = ConfigurationManager.AppSettings["CloudTraceIssuerSecret"];

            //Construct a Service Bus URI
            Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, servicePath);

            //Create a Behavior for the Credentials
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
            sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;
            sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName;
            sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecret;

            //Create the Service Host
            ServiceHost host = new ServiceHost(typeof(TraceService), uri);
            ServiceEndpoint serviceEndPoint = host.AddServiceEndpoint(typeof(ITraceContract), new NetEventRelayBinding(), String.Empty);
            serviceEndPoint.Behaviors.Add(sharedSecretServiceBusCredential);

            //Open the Host
            host.Open();
            Console.WriteLine("Connected To: " + uri.ToString());
            Console.WriteLine("Hit [Enter] to exit");

            //Wait Until the Enter Key is Pressed and Close the Host
            Console.ReadLine();
            host.Close();
        }
Exemple #19
0
        private static void Three()
        {
            Console.WriteLine("Starting service...");

            // Configure the credentials through an endpoint behavior.
            TransportClientEndpointBehavior relayCredentials = new TransportClientEndpointBehavior();
            relayCredentials.TokenProvider =
              TokenProvider.CreateSharedAccessSignatureTokenProvider("ListenAccessKeyMyService", "3VXc5wQwu479N/w2MaLtsk9fA7WWJsamsxtWcr8zbCY=");

            // Create the binding with default settings.
            WS2007HttpRelayBinding binding = new WS2007HttpRelayBinding();

            // it must be false to use previously generated relay endpoint and its special credentials
            binding.IsDynamic = false;
            //binding.Security.Mode = EndToEndSecurityMode.Message;
            // Get the service address.
            // Use the https scheme because by default the binding uses SSL for transport security.
            Uri address = ServiceBusEnvironment.CreateServiceUri("https", "johnsonwangnz", "MyService");

            // Create the service host.
            ServiceHost host = new ServiceHost(typeof(EchoService), address);
            // Add the service endpoint with the WS2007HttpRelayBinding.
            host.AddServiceEndpoint(typeof(IEchoContract), binding, address);

            // Add the credentials through the endpoint behavior.
            host.Description.Endpoints[0].Behaviors.Add(relayCredentials);

            // Start the service.
            host.Open();

            Console.WriteLine("Listening...");

            Console.ReadLine();
            host.Close();
        }
Exemple #20
0
        private MessageBufferClient GetMessageBufferClient()
        {
            TransportClientEndpointBehavior behavior = GetACSSecurity(txtIssuerName.Text, txtIssuerKey.Text);
            Uri messageBufferUri = GetMessageBufferUri();

            return(MessageBufferClient.GetMessageBuffer(behavior, messageBufferUri));
        }
Exemple #21
0
        public AzureProxyHandler(Uri requestUrl, Uri responseUrl)
        {
            _credentials = new TransportClientEndpointBehavior {
                CredentialType = TransportClientCredentialType.SharedSecret
            };
            _credentials.Credentials.SharedSecret.IssuerName   = Manager.Configuration.Azure.IssuerName;
            _credentials.Credentials.SharedSecret.IssuerSecret = Manager.Configuration.Azure.IssuerSecret;

            Init(requestUrl, responseUrl);

            ServicePointManager.DefaultConnectionLimit = 50;

            _requestBinding = new BasicHttpRelayBinding(EndToEndBasicHttpSecurityMode.None, RelayClientAuthenticationType.None);
            _requestBinding.MaxReceivedMessageSize              = int.MaxValue;
            _requestBinding.TransferMode                        = TransferMode.Streamed;
            _requestBinding.AllowCookies                        = false;
            _requestBinding.ReceiveTimeout                      = TimeSpan.MaxValue;
            _requestBinding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            _requestBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            _requestBinding.MaxReceivedMessageSize              = int.MaxValue;
            _requestBinding.MaxBufferSize                       = 4 * 1024 * 1024;
            _requestBinding.MaxBufferPoolSize                   = 32 * 4 * 1024 * 1024;

            WebMessageEncodingBindingElement encoderBindingElement = new WebMessageEncodingBindingElement();

            encoderBindingElement.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            encoderBindingElement.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            encoderBindingElement.ReaderQuotas.MaxDepth        = 128;
            encoderBindingElement.ReaderQuotas.MaxBytesPerRead = 65536;
            encoderBindingElement.ContentTypeMapper            = new RawContentTypeMapper();
            _webEncoder = encoderBindingElement.CreateMessageEncoderFactory().Encoder;
        }
        static void Main(string[] args)
        {
            string issuerName = "owner";
            string issuerSecret = "y+4vWY/Ryoen5avmC4CPAYTHj/OpkUQ7eykVhxNjr2w=";
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
            sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            // Cria o URI do serviço baseado no namespace do serviço
            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", "spf-nspace", "EchoService");
            // Cria o serviço host
            ServiceHost host = new ServiceHost(typeof(EchoService), address);
            //Cria o comportamento para o endpoint
            IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

            //Adiciona as credenciais do Service Bus a todos os endpoints configurados na configuração
            foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
            {
                endpoint.Behaviors.Add(serviceRegistrySettings);
                endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            }

            // Abre o serviço.
            host.Open();
            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            // Fecha o serviço.
            host.Close();
        }
Exemple #23
0
        private static void MessageOnly()
        {
            var transportClientEndpointBehavior = new TransportClientEndpointBehavior
            {
                TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sendKeyName, sendKeyValue)
            };

            var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, _queueName);

            var netMessagingBinding = new NetMessagingBinding
            {
                PrefetchCount = 10,
                TransportSettings = new NetMessagingTransportSettings
                {
                    BatchFlushInterval = TimeSpan.FromSeconds(0)
                }
            };

            var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IRequest)),
                                                        netMessagingBinding,
                                                        new EndpointAddress(serviceUri));
            serviceEndpoint.Behaviors.Add(transportClientEndpointBehavior);
            var channelFactory = new ChannelFactory<IRequest>(serviceEndpoint);
            var channel = channelFactory.CreateChannel();
            Console.WriteLine("Press any key to send message...");
            Console.ReadKey();
            channel.SendMessage("Hello from wcf client");
            Console.WriteLine("Message sent");
            Console.ReadKey();
        }
        public AzureProxyHandler(Uri requestUrl, Uri responseUrl)
        {
            _credentials = new TransportClientEndpointBehavior {
                CredentialType = TransportClientCredentialType.SharedSecret
            };
            _credentials.Credentials.SharedSecret.IssuerName = Manager.Configuration.Azure.IssuerName;
            _credentials.Credentials.SharedSecret.IssuerSecret = Manager.Configuration.Azure.IssuerSecret;

            Init(requestUrl, responseUrl);

            ServicePointManager.DefaultConnectionLimit = 50;

            _requestBinding = new BasicHttpRelayBinding(EndToEndBasicHttpSecurityMode.None, RelayClientAuthenticationType.None);
            _requestBinding.MaxReceivedMessageSize = int.MaxValue;
            _requestBinding.TransferMode = TransferMode.Streamed;
            _requestBinding.AllowCookies = false;
            _requestBinding.ReceiveTimeout = TimeSpan.MaxValue;
            _requestBinding.ReaderQuotas.MaxArrayLength = int.MaxValue;
            _requestBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            _requestBinding.MaxReceivedMessageSize = int.MaxValue;
            _requestBinding.MaxBufferSize = 4 * 1024 * 1024;
            _requestBinding.MaxBufferPoolSize = 32 * 4 * 1024 * 1024;

            WebMessageEncodingBindingElement encoderBindingElement = new WebMessageEncodingBindingElement();
            encoderBindingElement.ReaderQuotas.MaxArrayLength = int.MaxValue;
            encoderBindingElement.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            encoderBindingElement.ReaderQuotas.MaxDepth = 128;
            encoderBindingElement.ReaderQuotas.MaxBytesPerRead = 65536;
            encoderBindingElement.ContentTypeMapper = new RawContentTypeMapper();
            _webEncoder = encoderBindingElement.CreateMessageEncoderFactory().Encoder;
        }
        static void Main(string[] args)
        {
            #region With Local End Point
            //ChannelFactory<INorthService> proxy = new ChannelFactory<INorthService>("tcpep");
            //INorthService obj = proxy.CreateChannel();
            //foreach (var item in obj.GetCategories())
            //{
            //    Console.WriteLine(item);
            //}
            #endregion

            #region With Service Bus EndPoint
            TransportClientEndpointBehavior tcep = new TransportClientEndpointBehavior();
            NamespaceManager nm = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"].ToString());
            tcep.TokenProvider = nm.Settings.TokenProvider;

            ChannelFactory <INorthService> proxy = new ChannelFactory <INorthService>("tcpsbep");
            proxy.Endpoint.EndpointBehaviors.Add(tcep);
            INorthService obj = proxy.CreateChannel();
            //foreach (var item in obj.GetProductsByCategory(2))
            //{
            //    Console.WriteLine(item);
            //}
            foreach (var item in obj.GetProducts())
            {
                Console.WriteLine(item);
            }
            #endregion
        }
Exemple #26
0
        public Consumer()
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            // Create the policy for the message buffer.
            this.policy = new MessageBufferPolicy();
            this.policy.Authorization   = AuthorizationPolicy.Required;
            this.policy.MaxMessageCount = 10;
            // Messages in the message buffer expire after 5 minutes.
            this.policy.ExpiresAfter        = TimeSpan.FromMinutes(5);
            this.policy.OverflowPolicy      = OverflowPolicy.RejectIncomingMessage;
            this.policy.TransportProtection = TransportProtectionPolicy.AllPaths;

            // Create the credentials object for the endpoint.
            this.credential = new TransportClientEndpointBehavior();
            this.credential.CredentialType = TransportClientCredentialType.SharedSecret;
            this.credential.Credentials.SharedSecret.IssuerName   = issuerName;
            this.credential.Credentials.SharedSecret.IssuerSecret = issuerSecret;

            // Create the URI for the message buffer.
            this.uri = ServiceBusEnvironment.CreateServiceUri(Uri.UriSchemeHttps, serviceNamespace, "MessageBuffer");
            Console.WriteLine("Message buffer address '{0}'", this.uri.AbsoluteUri);
        }
Exemple #27
0
        public async Task Run(string connectionString)
        {
            var sbb = new ServiceBusConnectionStringBuilder(connectionString);

            // Create MessageReceiver for queue which requires session
            Console.WriteLine("Ready to receive messages from {0}...", SessionQueueName);

            // Creating the service host object as defined in config
            using (var serviceHost = new ServiceHost(typeof(SequenceProcessingService), new Uri(sbb.GetAbsoluteRuntimeEndpoints()[0], SessionQueueName)))
            {
                var authBehavior = new TransportClientEndpointBehavior(TokenProvider.CreateSharedAccessSignatureTokenProvider(sbb.SharedAccessKeyName, sbb.SharedAccessKey));
                serviceHost.Description.Behaviors.Add(new ErrorServiceBehavior());
                foreach (var ep in serviceHost.Description.Endpoints)
                {
                    ep.EndpointBehaviors.Add(authBehavior);
                }

                // Subscribe to the faulted event.
                serviceHost.Faulted += serviceHost_Faulted;

                // Start service
                serviceHost.Open();

                Console.WriteLine("\nPress [Enter] to close ServiceHost.");
                await Task.WhenAny(
                    Task.Run(() => Console.ReadKey()),
                    Task.Delay(TimeSpan.FromSeconds(10))
                    );

                // Close the service
                serviceHost.Close();
            }
        }
Exemple #28
0
        static void Main(string[] args)
        {
            // 将{service namespace}替换为你的服务命名空间.
            EndpointAddress       address = new EndpointAddress(ServiceBusEnvironment.CreateServiceUri("https", "{service namespace}", "ProcessDataWorkflowService"));
            BasicHttpRelayBinding binding = new BasicHttpRelayBinding();

            // 提供Service Bus证书.
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

            sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;
            // 将{issuer name}和{issuer secret}替换为你的证书.
            sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName   = "{issuer name}";
            sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = "{issuer secret}";

            ChannelFactory <IProcessDataWorkflowServiceChannel> factory = new ChannelFactory <IProcessDataWorkflowServiceChannel>(binding, address);

            factory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            factory.Open();
            IProcessDataWorkflowServiceChannel channel = factory.CreateChannel();

            channel.Open();
            Console.WriteLine("正在处理 10...");
            Console.WriteLine("服务返回: " + channel.ProcessData(new ProcessDataRequest(0)).@string);
            Console.WriteLine("正在处理 30...");
            Console.WriteLine("服务返回: " + channel.ProcessData(new ProcessDataRequest(30)).@string);
            channel.Close();
            factory.Close();
            Console.Read();
        }
        static void Main(string[] args)
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SimpleWebTokenAuthenticationService");

            TransportClientEndpointBehavior behavior = new TransportClientEndpointBehavior();

            behavior.TokenProvider = TokenProvider.CreateSimpleWebTokenProvider(
                ComputeSimpleWebTokenString(issuerName, issuerSecret));

            ServiceHost host = new ServiceHost(typeof(EchoService), address);

            host.Description.Endpoints[0].Behaviors.Add(behavior);
            host.Open();

            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            host.Close();
        }
        static void Main(string[] args)
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();

            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "PingService");

            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

            sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            ServiceHost host = new ServiceHost(typeof(PingService), address);

            foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
            {
                endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            }

            host.Open();

            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();

            host.Close();
        }
        public async Task<RelayConnection> ConnectAsync()
        {
            var tb = new TransportClientEndpointBehavior(tokenProvider);
            var bindingElement = new TcpRelayTransportBindingElement(
                RelayClientAuthenticationType.RelayAccessToken)
            {
                TransferMode = TransferMode.Buffered,
                ConnectionMode = TcpRelayConnectionMode.Relayed,
                ManualAddressing = true
            };
            bindingElement.GetType()
                .GetProperty("TransportProtectionEnabled",
                    BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(bindingElement, true);

            var rt = new CustomBinding(
                new BinaryMessageEncodingBindingElement(),
                bindingElement);

            var cf = rt.BuildChannelFactory<IDuplexSessionChannel>(tb);
            await Task.Factory.FromAsync(cf.BeginOpen, cf.EndOpen, null);
            var ch = cf.CreateChannel(new EndpointAddress(address));
            await Task.Factory.FromAsync(ch.BeginOpen, ch.EndOpen, null);
            return new RelayConnection(ch)
            {
                WriteTimeout = (int) rt.SendTimeout.TotalMilliseconds,
                ReadTimeout = (int) rt.ReceiveTimeout.TotalMilliseconds
            };
        }
Exemple #32
0
        private static void Two()
        {
            Console.WriteLine("Starting service...");

            // Configure the credentials through an endpoint behavior.
            TransportClientEndpointBehavior relayCredentials = new TransportClientEndpointBehavior();
            relayCredentials.TokenProvider =
              TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", "fBLL/4/+rEsCOiTQPNPS6DJQybykqE2HdVBsILrzMLY=");

            // Create the binding with default settings.
            WebHttpRelayBinding binding = new WebHttpRelayBinding();

            binding.Security.RelayClientAuthenticationType = RelayClientAuthenticationType.None;
            // Get the service address.
            // Use the https scheme because by default the binding uses SSL for transport security.
            Uri address = ServiceBusEnvironment.CreateServiceUri("https", "johnsonwangnz", "Rest");

            // Create the web service host.
            WebServiceHost host = new WebServiceHost(typeof(EchoRestService), address);
            // Add the service endpoint with the WS2007HttpRelayBinding.
            host.AddServiceEndpoint(typeof(IEchoRestContract), binding, address);

            // Add the credentials through the endpoint behavior.
            host.Description.Endpoints[0].Behaviors.Add(relayCredentials);

            // Start the service.
            host.Open();

            Console.WriteLine("Listening...");

            Console.ReadLine();
            host.Close();
        }
Exemple #33
0
        public Task Run(string serviceBusHostName, string token)
        {
            Console.Write("Enter your nick:");
            var chatNickname = Console.ReadLine();

            Console.Write("Enter room name:");
            var session = Console.ReadLine();

            var serviceAddress       = new UriBuilder("sb", serviceBusHostName, -1, "/chat/" + session).ToString();
            var netEventRelayBinding = new NetEventRelayBinding();
            var tokenBehavior        = new TransportClientEndpointBehavior(TokenProvider.CreateSharedAccessSignatureTokenProvider(token));

            using (var host = new ServiceHost(this))
            {
                host.AddServiceEndpoint(typeof(IChat), netEventRelayBinding, serviceAddress)
                .EndpointBehaviors.Add(tokenBehavior);
                host.Open();

                using (var channelFactory = new ChannelFactory <IChat>(netEventRelayBinding, serviceAddress))
                {
                    channelFactory.Endpoint.Behaviors.Add(tokenBehavior);
                    var channel = channelFactory.CreateChannel();

                    this.RunChat(channel, chatNickname);

                    channelFactory.Close();
                }
                host.Close();
            }
            return(Task.FromResult(true));
        }
        static void Main(string[] args)
        {
            Console.WriteLine("CloudTrace Console");
            Console.WriteLine("Connecting ...");

            //Retrieve Settings from App.Config
            string servicePath      = ConfigurationManager.AppSettings["CloudTraceServicePath"];
            string serviceNamespace = ConfigurationManager.AppSettings["CloudTraceServiceNamespace"];
            string issuerName       = ConfigurationManager.AppSettings["CloudTraceIssuerName"];
            string issuerSecret     = ConfigurationManager.AppSettings["CloudTraceIssuerSecret"];

            //Construct a Service Bus URI
            Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, servicePath);

            //Create a Behavior for the Credentials
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

            sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            //Create the Service Host
            ServiceHost     host            = new ServiceHost(typeof(TraceService), uri);
            ServiceEndpoint serviceEndPoint = host.AddServiceEndpoint(typeof(ITraceContract), new NetEventRelayBinding(), String.Empty);

            serviceEndPoint.Behaviors.Add(sharedSecretServiceBusCredential);

            //Open the Host
            host.Open();
            Console.WriteLine("Connected To: " + uri.ToString());
            Console.WriteLine("Hit [Enter] to exit");

            //Wait Until the Enter Key is Pressed and Close the Host
            Console.ReadLine();
            host.Close();
        }
Exemple #35
0
        /// <summary>
        /// Initializes a new instance of the reliable Windows Azure Service Bus Message Buffer client connected to the specified message buffer
        /// located on the specified Service Bus endpoint and utilizing the specified custom retry policy.
        /// </summary>
        /// <param name="queueName">The name of the target message buffer (queue).</param>
        /// <param name="sbEndpointInfo">The endpoint details.</param>
        /// <param name="retryPolicy">The custom retry policy that will ensure reliable access to the underlying HTTP/REST-based infrastructure.</param>
        public ReliableServiceBusQueue(string queueName, ServiceBusEndpointInfo sbEndpointInfo, RetryPolicy retryPolicy)
        {
            Guard.ArgumentNotNullOrEmptyString(queueName, "queueName");
            Guard.ArgumentNotNull(sbEndpointInfo, "sbEndpointInfo");
            Guard.ArgumentNotNull(retryPolicy, "retryPolicy");

            this.sbEndpointInfo = sbEndpointInfo;
            this.retryPolicy    = retryPolicy;

            this.queuePolicy = new MessageBufferPolicy
            {
                ExpiresAfter    = TimeSpan.FromMinutes(120),
                MaxMessageCount = 100000,
                OverflowPolicy  = OverflowPolicy.RejectIncomingMessage
            };

            var address = ServiceBusEnvironment.CreateServiceUri(WellKnownProtocolScheme.SecureHttp, sbEndpointInfo.ServiceNamespace, String.Concat(sbEndpointInfo.ServicePath, !sbEndpointInfo.ServicePath.EndsWith("/") ? "/" : "", queueName));
            var credentialsBehaviour = new TransportClientEndpointBehavior();

            credentialsBehaviour.CredentialType = TransportClientCredentialType.SharedSecret;
            credentialsBehaviour.Credentials.SharedSecret.IssuerName   = sbEndpointInfo.IssuerName;
            credentialsBehaviour.Credentials.SharedSecret.IssuerSecret = sbEndpointInfo.IssuerSecret;

            MessageBufferClient msgBufferClient = null;

            this.retryPolicy.ExecuteAction(() =>
            {
                msgBufferClient = MessageBufferClient.CreateMessageBuffer(credentialsBehaviour, address, this.queuePolicy, DefaultQueueMessageVersion);
            });

            this.queueClient = msgBufferClient;
        }
Exemple #36
0
        private static ChannelFactory <T> CreateServiceBusClientChannelFactory <T>(string serviceNamespace, string servicePath, string issuerName, string issuerSecret, Binding binding)
        {
            Guard.ArgumentNotNullOrEmptyString(serviceNamespace, "serviceNamespace");
            Guard.ArgumentNotNullOrEmptyString(servicePath, "servicePath");
            Guard.ArgumentNotNullOrEmptyString(issuerName, "issuerName");
            Guard.ArgumentNotNullOrEmptyString(issuerSecret, "issuerSecret");
            Guard.ArgumentNotNull(binding, "binding");

            var callToken = TraceManager.DebugComponent.TraceIn(serviceNamespace, servicePath, binding.Name);

            var address = ServiceBusEnvironment.CreateServiceUri(WellKnownProtocolScheme.ServiceBus, serviceNamespace, servicePath);

            var credentialsBehaviour = new TransportClientEndpointBehavior();

            credentialsBehaviour.CredentialType = TransportClientCredentialType.SharedSecret;
            credentialsBehaviour.Credentials.SharedSecret.IssuerName   = issuerName;
            credentialsBehaviour.Credentials.SharedSecret.IssuerSecret = issuerSecret;

            var endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), binding, new EndpointAddress(address));

            endpoint.Behaviors.Add(credentialsBehaviour);

            // Apply default endpoint configuration.
            ServiceEndpointConfiguration.ConfigureDefaults(endpoint);

            ChannelFactory <T> clientChannelFactory = new ChannelFactory <T>(endpoint);

            TraceManager.DebugComponent.TraceOut(callToken, endpoint.Address.Uri);

            return(clientChannelFactory);
        }
Exemple #37
0
        public async Task <RelayConnection> ConnectAsync()
        {
            var tb             = new TransportClientEndpointBehavior(tokenProvider);
            var bindingElement = new TcpRelayTransportBindingElement(
                RelayClientAuthenticationType.RelayAccessToken)
            {
                TransferMode     = TransferMode.Buffered,
                ConnectionMode   = TcpRelayConnectionMode.Relayed,
                ManualAddressing = true
            };

            bindingElement.GetType()
            .GetProperty("TransportProtectionEnabled",
                         BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic)
            .SetValue(bindingElement, true);

            var rt = new CustomBinding(
                new BinaryMessageEncodingBindingElement(),
                bindingElement);

            var cf = rt.BuildChannelFactory <IDuplexSessionChannel>(tb);
            await Task.Factory.FromAsync(cf.BeginOpen, cf.EndOpen, null);

            var ch = cf.CreateChannel(new EndpointAddress(address));
            await Task.Factory.FromAsync(ch.BeginOpen, ch.EndOpen, null);

            return(new RelayConnection(ch)
            {
                WriteTimeout = (int)rt.SendTimeout.TotalMilliseconds,
                ReadTimeout = (int)rt.ReceiveTimeout.TotalMilliseconds
            });
        }
Exemple #38
0
        void DeleteBuffers(ServiceBusTreeNode treeNode)
        {
            if (treeNode.ServiceBusNode != null)
            {
                if (treeNode.ServiceBusNode.Policy != null)
                {
                    if (treeNode.ServiceBusNode.Policy is MessageBufferPolicy)
                    {
                        string nodeAddress = treeNode.ServiceBusNode.Address;
                        nodeAddress = nodeAddress.Replace(@"sb://", @"https://");

                        TransportClientEndpointBehavior credential = Graphs[ServiceNamespace.ToLower()].Credential;
                        Uri address = new Uri(nodeAddress);
                        try
                        {
                            MessageBufferClient.GetMessageBuffer(credential, address).DeleteMessageBuffer();
                        }
                        catch
                        {}
                    }
                }
            }
            foreach (TreeNode node in treeNode.Nodes)
            {
                DeleteBuffers(node as ServiceBusTreeNode);
            }
        }
Exemple #39
0
        static void Main(string[] args)
        {
            #region With Local End Point
            //ServiceHost host = new ServiceHost(typeof(NorthSVC));
            //host.Open();
            //Console.WriteLine("Service is running, press any key to exist!!");
            //Console.ReadKey(true);
            //host.Close();
            #endregion

            #region With ServiceBus EndPoint
            TransportClientEndpointBehavior tcep = new TransportClientEndpointBehavior();
            NamespaceManager nm = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"].ToString());
            tcep.TokenProvider = nm.Settings.TokenProvider;

            ServiceHost host = new ServiceHost(typeof(NorthSVC));
            foreach (ServiceEndpoint item in host.Description.Endpoints)
            {
                item.EndpointBehaviors.Add(tcep);
            }
            host.Open();
            Console.WriteLine("Service Bus Service is running, press any key to stop!!");
            Console.ReadKey(true);
            host.Close();
            #endregion
        }
Exemple #40
0
        /// <summary>
        /// Start the two way listener running as a service host, listening for requests on the Azure Service Bus.
        /// </summary>
        public void Start()
        {
            try
            {
                var SBaccessKey = _listenerConfig.ServiceBusSASKey;
                var serviceHost = new ServiceHost(_messageProcessor);
                MessageProcessingService.Host = serviceHost;

                Log($"Starting TwoWay Listener on {_listenerConfig.ServiceBusEndpoint} with access policy {_listenerConfig.SharedAccessKeyName}");

                var tokenProvider =
                    TokenProvider.CreateSharedAccessSignatureTokenProvider(_listenerConfig.SharedAccessKeyName,
                                                                           SBaccessKey);
                // accessKeyTask.Result);
                var transportClient = new TransportClientEndpointBehavior(tokenProvider);

                serviceHost.AddServiceEndpoint(typeof(ITwoWayServiceEndpointPlugin),
                                               new WS2007HttpRelayBinding(),
                                               _listenerConfig.ServiceBusEndpoint).Behaviors.Add(transportClient);

                serviceHost.Open();

                Log($"listening ... on {serviceHost.Description.Endpoints[0].Address}");
            }
            catch (Exception ex)
            {
                Log(ex.ToString());
                throw;
            }
        }
        private static void RunService()
        {
            Console.WriteLine("Server");

            ServiceRegistrySettings registryBehavior = new ServiceRegistrySettings()
            {
                DiscoveryMode = DiscoveryType.Public,
                DisplayName = "Temperature Service"
            };

            TransportClientEndpointBehavior credentialBehavior = new TransportClientEndpointBehavior();
            credentialBehavior.CredentialType = TransportClientCredentialType.SharedSecret;
            credentialBehavior.Credentials.SharedSecret.IssuerName = issuerName;
            credentialBehavior.Credentials.SharedSecret.IssuerSecret = issuerKey;

            Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, serviceName);
            using (ServiceHost serviceHost = new ServiceHost(typeof(TemperatureService), serviceUri))
            {
                NetTcpRelayBinding binding = new NetTcpRelayBinding();

                serviceHost.AddServiceEndpoint(typeof(ITemperatureContract), binding, serviceUri);
                serviceHost.Description.Endpoints[0].Behaviors.Add(credentialBehavior);
                serviceHost.Description.Endpoints[0].Behaviors.Add(registryBehavior);

                serviceHost.Open();
                Console.WriteLine("Press Enter to exit.");
                Console.ReadLine();
            }
        }
        public Consumer()
        {
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();
            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();
            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            // Configure queue settings.
            this.queueDescription = new QueueDescription(MyQueuePath);
            // Setting Max Size and TTL for demonstration purpose
            // but can be changed per user discretion to suite their system needs.
            // Refer service bus documentation to understand the limitations.
            // Setting Queue max size to 1GB where as default Max Size is 5GB.
            this.queueDescription.MaxSizeInMegabytes = 1024;
            // Setting message TTL to 5 days where as default TTL is 14 days.
            this.queueDescription.DefaultMessageTimeToLive = TimeSpan.FromDays(5);
            
            // Create management credentials.
            this.credential = new TransportClientEndpointBehavior() 
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret)
            };
 
            // Create the URI for the queue.
            this.namespaceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, String.Empty);
            Console.WriteLine("Service Bus Namespace Uri address '{0}'", this.namespaceUri.AbsoluteUri);
        }
Exemple #43
0
        static void SetServiceBusCredentials(IEnumerable <ServiceEndpoint> endpoints, string issuer, string secret)
        {
            TransportClientEndpointBehavior behavior = new TransportClientEndpointBehavior();
            TokenProvider tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuer, secret);

            SetServiceBusCredentials(endpoints, tokenProvider);
        }
      public static void VerifyBuffer(string bufferAddress,string issuer,string secret)
      {
         TransportClientEndpointBehavior creds = new TransportClientEndpointBehavior();
         creds.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuer,secret);

         VerifyBuffer(bufferAddress,creds);
      }
        public ReverseWebProxy(Uri upstreamUri, Uri downstreamUri, TransportClientEndpointBehavior credentials)
        {
            this.upstreamUri = upstreamUri;
            this.downstreamUri = downstreamUri;

            this.upstreamBasePath = this.upstreamUri.PathAndQuery;
            if (this.upstreamBasePath.EndsWith("/"))
            {
                this.upstreamBasePath = this.upstreamBasePath.Substring(0, this.upstreamBasePath.Length - 1);
            }

            ServicePointManager.DefaultConnectionLimit = 50;

            WebHttpRelayBinding relayBinding = new WebHttpRelayBinding(EndToEndWebHttpSecurityMode.None, RelayClientAuthenticationType.None);
            relayBinding.MaxReceivedMessageSize = int.MaxValue;
            relayBinding.TransferMode = TransferMode.Streamed;
            relayBinding.AllowCookies = false;
            relayBinding.ReceiveTimeout = TimeSpan.MaxValue;
            relayBinding.ReaderQuotas.MaxArrayLength = int.MaxValue;
            relayBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            this.upstreamBinding = relayBinding;

            WebMessageEncodingBindingElement encoderBindingElement = new WebMessageEncodingBindingElement();
            encoderBindingElement.ReaderQuotas.MaxArrayLength = int.MaxValue;
            encoderBindingElement.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            encoderBindingElement.ContentTypeMapper = new RawContentTypeMapper();
            encoder = encoderBindingElement.CreateMessageEncoderFactory().Encoder;

            this.credentials = credentials;
        }
        private static void RunClient()
        {
            Console.WriteLine("Client");

            TransportClientEndpointBehavior credentialBehavior = new TransportClientEndpointBehavior();
            credentialBehavior.CredentialType = TransportClientCredentialType.SharedSecret;
            credentialBehavior.Credentials.SharedSecret.IssuerName = issuerName;
            credentialBehavior.Credentials.SharedSecret.IssuerSecret = issuerKey;

            NetTcpRelayBinding binding = new NetTcpRelayBinding();

            Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, serviceName);
            EndpointAddress endpointAddress = new EndpointAddress(serviceUri);

            using (ChannelFactory<ITemperatureContract> channelFactory = new ChannelFactory<ITemperatureContract>(binding, endpointAddress))
            {
                channelFactory.Endpoint.Behaviors.Add(credentialBehavior);

                ITemperatureContract channel = channelFactory.CreateChannel();
                ((ICommunicationObject)channel).Open();

                Double boilingPointCelsius = channel.ToCelsius(212);
                Double boilingPointFahrenheit = channel.ToFahrenheit(boilingPointCelsius);

                Console.WriteLine("212 Fahrenheit is {0} Celsius", boilingPointCelsius);
                Console.WriteLine("{0} Celsius is {1} Fahrenheit", boilingPointCelsius, boilingPointFahrenheit);

                ((ICommunicationObject)channel).Close();

                Console.WriteLine("Press Enter to exit.");
                Console.ReadLine();
            }
        }
Exemple #47
0
        private bool startRelay1()
        {
            try
            {
                ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;

                Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ConfigurationManager.AppSettings["serviceNamespace"], "BridgeService");

                TransportClientEndpointBehavior sasCredential = new TransportClientEndpointBehavior();
                sasCredential.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", ConfigurationManager.AppSettings["sasKey"]);

                channelFactory = new ChannelFactory <IBridgeChannel>("RelayEndpoint", new EndpointAddress(serviceUri));
                channelFactory.Endpoint.Behaviors.Add(sasCredential);

                channel = channelFactory.CreateChannel();
                channel.Open();
                g("BridgeService Channel opened");
                return(true);
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                ex("The BridgeService endpoint was not found");
                return(false);
            }
            catch (Exception ex1)
            {
                ex(System.Reflection.MethodBase.GetCurrentMethod().Name + " " + ex1.ToString());
                return(false);
            }
        }
        public Task Run(string serviceBusHostName, string token)
        {
            Console.Write("Enter your nick:");
            var chatNickname = Console.ReadLine();
            Console.Write("Enter room name:");
            var session = Console.ReadLine();

            var serviceAddress = new UriBuilder("sb", serviceBusHostName, -1, "/chat/" + session).ToString();
            var netEventRelayBinding = new NetEventRelayBinding();
            var tokenBehavior = new TransportClientEndpointBehavior(TokenProvider.CreateSharedAccessSignatureTokenProvider(token));

            using (var host = new ServiceHost(this))
            {
                host.AddServiceEndpoint(typeof(IChat), netEventRelayBinding, serviceAddress)
                    .EndpointBehaviors.Add(tokenBehavior);
                host.Open();

                using (var channelFactory = new ChannelFactory<IChat>(netEventRelayBinding, serviceAddress))
                {
                    channelFactory.Endpoint.Behaviors.Add(tokenBehavior);
                    var channel = channelFactory.CreateChannel();

                    this.RunChat(channel, chatNickname);

                    channelFactory.Close();
                }
                host.Close();
            }
            return Task.FromResult(true);
        }
 private static TransportClientEndpointBehavior GetCredentials()
 {
     TransportClientEndpointBehavior credentialBehavior = new TransportClientEndpointBehavior();
     credentialBehavior.CredentialType = TransportClientCredentialType.SharedSecret;
     credentialBehavior.Credentials.SharedSecret.IssuerName = issuerName;
     credentialBehavior.Credentials.SharedSecret.IssuerSecret = issuerKey;
     return credentialBehavior;
 }
        public static void VerifyBuffer(string bufferAddress,string issuer,string secret)
        {
            TransportClientEndpointBehavior credential = new TransportClientEndpointBehavior();
             credential.CredentialType = TransportClientCredentialType.SharedSecret;
             credential.Credentials.SharedSecret.IssuerName = issuer;
             credential.Credentials.SharedSecret.IssuerSecret = secret;

             VerifyBuffer(bufferAddress,credential);
        }
        public static void PurgeBuffer(Uri bufferAddress,TransportClientEndpointBehavior credential)
        {
            Debug.Assert(BufferExists(bufferAddress,credential));

             MessageBufferClient client = MessageBufferClient.GetMessageBuffer(credential,bufferAddress);
             MessageBufferPolicy policy = client.GetPolicy();
             client.DeleteMessageBuffer();
             MessageBufferClient.CreateMessageBuffer(credential,bufferAddress,policy);
        }
        static void Main(string[] args)
        {
            // HACK: 3 constantes adicionais, para se poderem alterar 'a vontade
            const string serviceSheme = "sb";
            // HACK: linha seguinte descomentada, para nao se estar sempre a escrever
            const string serviceNamespace = "cmfservicebusnamespace"; // "catiavaz";
            const string servicePath = "EchoService";

            // HACK: declaracao de 2 constantes, para nao se estar sempre a escrever
            string issuerName = "owner"; // "owner";
            string issuerSecret = "CZzrHKiB2QjRCJjBC5kFwXVrWV4w5qpBphpwpt43Tmw="; // "MYKEY";

            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;
            Console.Write("Your Service Namespace: ");
            //string serviceNamespace = Console.ReadLine(); // HACK: linha comentada, para nao se estar sempre a escrever
            Console.Write("Your Issuer Name: ");
            //string issuerName = Console.ReadLine(); // HACK: linha comentada, para nao se estar sempre a escrever
            Console.Write("Your Issuer Secret: ");
            //string issuerSecret = Console.ReadLine(); // HACK: linha comentada, para nao se estar sempre a escrever

            Uri serviceUri = ServiceBusEnvironment.CreateServiceUri(serviceSheme, serviceNamespace, servicePath);

            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new
                TransportClientEndpointBehavior();
            sharedSecretServiceBusCredential.TokenProvider =
                TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            ChannelFactory<IEchoChannel> channelFactory =
                new ChannelFactory<IEchoChannel>("RelayEndpoint", new EndpointAddress(serviceUri));

            channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

            IEchoChannel channel = channelFactory.CreateChannel();
            channel.Open();

            Console.WriteLine("Enter text to echo (or [Enter] to exit):");

            string input = Console.ReadLine();
            while (input != String.Empty)
            {
                try
                {
                    Console.WriteLine("Server echoed: {0}", channel.Echo(input));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: " + e.Message);
                }
                input = Console.ReadLine();
            }

            channel.Close();
            channelFactory.Close();
        }
      public ServiceBusTreeNode(ExplorerForm form,ServiceBusNode serviceBusNode,string text,int imageIndex) : base(text,imageIndex,imageIndex)
      {
         Form = form;
         ServiceBusNode = serviceBusNode;

         if(serviceBusNode != null)
         {
            string serviceNamespace = ExtractNamespace(new Uri(serviceBusNode.Address));
            Credential = form.Graphs[serviceNamespace.ToLower()].Credential;
         }
      }
        public NamedPipeClientConnectionForwarder(string serviceNamespace, string issuerName, string issuerSecret, string targetHost, string localPipe, string toPipe, bool useHybrid)
        {
            this.toPipe = toPipe;
            this.localPipe = localPipe;

            this.connections = new Dictionary<int, MultiplexedPipeConnection>();
            this.endpointVia = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, string.Format("/PortBridge/{0}", targetHost));
            this.streamBinding = CreateClientBinding(useHybrid);

            this.relayCreds = new TransportClientEndpointBehavior();
            this.relayCreds.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);
        }
        private static void GetChannelFactory()
        {
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            NamespaceManager namespaceClient = NamespaceManager.CreateFromConnectionString(connectionString);
            Uri serviceUri = new Uri(namespaceClient.Address, "Customer");

            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
            sharedSecretServiceBusCredential.TokenProvider = namespaceClient.Settings.TokenProvider;

            channelFactory = new ChannelFactory<ICustomerChannel>("RelayEndpoint", new EndpointAddress(serviceUri));
            channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
        }
Exemple #56
0
      public virtual void Refresh(ServiceBusNode node,TransportClientEndpointBehavior credential)
      {
         Node = node;
         Credential = credential;
         Address = GetRealAddress(node.Address).AbsoluteUri;

         m_ItemNameLabel.Text = node.Name;
         m_AddressLabel.Text = GetRealAddress(node.Address).AbsoluteUri;

         TrimLable(m_ItemNameLabel,34);
         TrimLable(m_AddressLabel,69);
      }
      public override void Refresh(ServiceBusNode node,TransportClientEndpointBehavior credential)
      {
         base.Refresh(node,credential);

         m_Address = Address;

         //The feed does not show correct transport - always http/https, so remove all transports 
         m_Address = m_Address.Replace(@"sb://",@"[transport]://");

         m_AddressLabel.Text = m_Address;
         TrimLable(m_AddressLabel,69);
      }
 static void SetBehavior(IEnumerable<ServiceEndpoint> endpoints,TransportClientEndpointBehavior credential)
 {
    foreach(ServiceEndpoint endpoint in endpoints)
    {
       if(endpoint.Binding is NetTcpRelayBinding   ||
          endpoint.Binding is WSHttpRelayBinding   ||
          endpoint.Binding is NetOnewayRelayBinding)
       {
          endpoint.Behaviors.Add(credential);
       }
    }
 }
Exemple #59
0
        static void Main(string[] args)
        {
            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();
            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();

            // The issuer secret is the Service Bus namespace management key.
            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

            // Create the service URI based on the service namespace.
            Uri address = ServiceBusEnvironment.CreateServiceUri(Uri.UriSchemeHttps, serviceNamespace, "RemoteService");
            Console.WriteLine("Service address: " + address);

            // Create the credentials object for the endpoint.
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior() 
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret)
            };
            
            // Create the binding object.
            WS2007HttpRelayBinding binding = new WS2007HttpRelayBinding();
            binding.Security.Mode = EndToEndSecurityMode.Transport;

            // Create the service host reading the configuration.
            ServiceHost host = new ServiceHost(typeof(RemoteService));
            host.AddServiceEndpoint(typeof(IServiceEndpointPlugin), binding, address);

            // Create the ServiceRegistrySettings behavior for the endpoint.
            IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

            // Add the Service Bus credentials to all endpoints specified in configuration.
            foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
            {
                endpoint.Behaviors.Add(serviceRegistrySettings);
                endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            }

            // Open the service.
            host.Open();

            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            // Close the service.
            Console.Write("Closing the service host...");
            host.Close();
            Console.WriteLine(" done.");
        }
Exemple #60
0
        static void Listen()
        {
            string serviceNamespace;
            string serviceIdentityName;
            string serviceIdentityKey;

            Console.WriteLine("Service Namespace:");
            serviceNamespace = Console.ReadLine();

            Console.WriteLine("Service Identity:");
            serviceIdentityName = Console.ReadLine();
            Console.WriteLine("Service Identity Key:");
            serviceIdentityKey = Console.ReadLine();

            TransportClientEndpointBehavior behavior = new TransportClientEndpointBehavior();
            behavior.TokenProvider = SharedSecretTokenProvider.CreateSharedSecretTokenProvider(serviceIdentityName, serviceIdentityKey);

            var address = ServiceBusEnvironment.CreateServiceUri(Uri.UriSchemeHttps, serviceNamespace, "Demo/OneWayListener");

            // binding
            var binding = new WS2007HttpRelayBinding();
            binding.Security.Mode = EndToEndSecurityMode.Transport;

            var host = new ServiceHost(typeof (CRMOnlineOneWayListenerService));

            var endPoint = host.AddServiceEndpoint(typeof (IServiceEndpointPlugin), binding, address);

            var serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Private);

            endPoint.Behaviors.Add(serviceRegistrySettings);
            endPoint.Behaviors.Add(behavior);

            try
            {
                // Open the service.
                host.Open();
                Console.WriteLine("Host Open. Listening on endpoint Address: " + address);
            }
            catch (TimeoutException timeout)
            {
                Console.WriteLine("Opening the service timed out, details below:");
                Console.WriteLine(timeout.Message);
            }

            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            // Close the service.
            Console.Write("Closing the service host...");
            host.Close();
            Console.WriteLine(" done.");
        }