public void RelayWithAuthorization()
        {
            string relayName = "RelayWithAuthorization";
            var    ns        = NamespaceManager.CreateFromConnectionString(TestServiceBus.relayConnectionString);

            try
            {
                var relayDescription = new RelayDescription(relayName, RelayType.Http)
                {
                    RequiresClientAuthorization = true,
                    RequiresTransportSecurity   = true
                };

                var sendKey       = SharedAccessAuthorizationRule.GenerateRandomKey();
                var sendKeyName   = "SendAccessKey";
                var listenKey     = SharedAccessAuthorizationRule.GenerateRandomKey();
                var listenKeyName = "ListenAccessKey";

                relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(listenKeyName, listenKey,
                                                                                     new List <AccessRights> {
                    AccessRights.Listen
                }));
                relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(sendKeyName, sendKey,
                                                                                     new List <AccessRights> {
                    AccessRights.Send
                }));

                ns.CreateRelay(relayDescription);
                Assert.IsTrue(ns.RelayExists(relayName));
            }
            finally
            {
                ns.DeleteRelay(relayName);
            }
        }
예제 #2
0
        public HandleRelayControl(WriteToLogDelegate writeToLog, ServiceBusHelper serviceBusHelper, RelayDescription relayDescription, string path)
        {
            this.writeToLog       = writeToLog;
            this.serviceBusHelper = serviceBusHelper;
            this.relayDescription = relayDescription;
            this.path             = path;

            InitializeComponent();
            InitializeControls();
        }
예제 #3
0
 public void RefreshData(RelayDescription relayService)
 {
     try
     {
         relayDescription = relayService;
         InitializeData();
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }
예제 #4
0
        /// <summary>
        /// Creates shared access signature authorization for the service bus entity. This authorization works on
        /// public Microsoft Azure environments and Windows Azure Pack on prim as well.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="entityName">The fully qualified service bus entity name</param>
        /// <param name="entityType">The service bus entity type (e.g. Queue)</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        /// <param name="primaryKey">The SAS primary key. It'll be generated if empty</param>
        /// <param name="secondaryKey">The SAS secondary key</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Shared Access Signature authorization rule</returns>
        public virtual ExtendedAuthorizationRule CreateSharedAccessAuthorization(
            string namespaceName,
            string entityName,
            ServiceBusEntityType entityType,
            string ruleName,
            string primaryKey,
            string secondaryKey,
            params AccessRights[] permissions)
        {
            // Create the SAS authorization rule
            SharedAccessAuthorizationRule rule = new SharedAccessAuthorizationRule(
                ruleName,
                string.IsNullOrEmpty(primaryKey) ? SharedAccessAuthorizationRule.GenerateRandomKey() : primaryKey,
                secondaryKey,
                permissions);

            // Create namespace manager
            NamespaceManager namespaceManager = CreateNamespaceManager(namespaceName);

            // Add the SAS rule and update the entity
            switch (entityType)
            {
            case ServiceBusEntityType.Queue:
                QueueDescription queue = namespaceManager.GetQueue(entityName);
                queue.Authorization.Add(rule);
                namespaceManager.UpdateQueue(queue);
                break;

            case ServiceBusEntityType.Topic:
                TopicDescription topic = namespaceManager.GetTopic(entityName);
                topic.Authorization.Add(rule);
                namespaceManager.UpdateTopic(topic);
                break;

            case ServiceBusEntityType.Relay:
                RelayDescription relay = namespaceManager.GetRelayAsync(entityName).Result;
                relay.Authorization.Add(rule);
                namespaceManager.UpdateRelayAsync(relay).Wait();
                break;

            case ServiceBusEntityType.NotificationHub:
                NotificationHubDescription notificationHub = namespaceManager.GetNotificationHub(entityName);
                notificationHub.Authorization.Add(rule);
                namespaceManager.UpdateNotificationHub(notificationHub);
                break;

            default:
                throw new Exception(string.Format(Resources.ServiceBusEntityTypeNotFound, entityType.ToString()));
            }

            return(CreateExtendedAuthorizationRule(rule, namespaceName, entityName, entityType));
        }
예제 #5
0
        /// <summary>
        /// Removed shared access signature authorization for the service bus entity.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="entityName">The fully qualified service bus entity name</param>
        /// <param name="entityType">The service bus entity type (e.g. Queue)</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        public virtual void RemoveAuthorizationRule(
            string namespaceName,
            string entityName,
            ServiceBusEntityType entityType,
            string ruleName)
        {
            bool removed = false;
            SharedAccessAuthorizationRule rule = (SharedAccessAuthorizationRule)GetAuthorizationRule(
                namespaceName,
                entityName,
                entityType,
                ruleName).Rule;

            // Create namespace manager
            NamespaceManager namespaceManager = CreateNamespaceManager(namespaceName);

            // Add the SAS rule and update the entity
            switch (entityType)
            {
            case ServiceBusEntityType.Queue:
                QueueDescription queue = namespaceManager.GetQueue(entityName);
                removed = queue.Authorization.Remove(rule);
                Debug.Assert(removed);
                namespaceManager.UpdateQueue(queue);
                break;

            case ServiceBusEntityType.Topic:
                TopicDescription topic = namespaceManager.GetTopic(entityName);
                removed = topic.Authorization.Remove(rule);
                Debug.Assert(removed);
                namespaceManager.UpdateTopic(topic);
                break;

            case ServiceBusEntityType.Relay:
                RelayDescription relay = namespaceManager.GetRelayAsync(entityName).Result;
                removed = relay.Authorization.Remove(rule);
                Debug.Assert(removed);
                namespaceManager.UpdateRelayAsync(relay).Wait();
                break;

            case ServiceBusEntityType.NotificationHub:
                NotificationHubDescription notificationHub = namespaceManager.GetNotificationHub(entityName);
                removed = notificationHub.Authorization.Remove(rule);
                Debug.Assert(removed);
                namespaceManager.UpdateNotificationHub(notificationHub);
                break;

            default:
                throw new Exception(string.Format(Resources.ServiceBusEntityTypeNotFound, entityType.ToString()));
            }
        }
        public void RelayTcpCreation()
        {
            string relayName = "RelayTcpCreation";
            var    ns        = NamespaceManager.CreateFromConnectionString(TestServiceBus.relayConnectionString);

            try
            {
                RelayDescription initialDesc = ns.CreateRelay(relayName, RelayType.NetTcp);
            }
            finally
            {
                ns.DeleteRelay(relayName);
            }
        }
        public void GetRelay()
        {
            string RelayName = "GetRelay".ToLower() + Guid.NewGuid().ToString().Substring(0, 5);
            var    ns        = NamespaceManager.CreateFromConnectionString(TestServiceBus.relayConnectionString);

            try
            {
                RelayDescription initialDesc = ns.CreateRelay(RelayName, RelayType.Http);
                RelayDescription getDesc     = ns.GetRelay(RelayName);
                Assert.IsTrue(getDesc.RequiresTransportSecurity == initialDesc.RequiresTransportSecurity);
            }
            finally
            {
                ns.DeleteRelay(RelayName);
            }
        }
        public ContainerForm(ServiceBusHelper serviceBusHelper, MainForm mainForm, RelayDescription relayDescription)
        {
            try
            {
                InitializeComponent();
                Task.Factory.StartNew(AsyncWriteToLog).ContinueWith(t =>
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        WriteToLog(t.Exception.Message);
                    }
                });
                this.mainForm        = mainForm;
                mainSplitterDistance = mainSplitContainer.SplitterDistance;
                SuspendLayout();
                panelMain.SuspendDrawing();
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;

                testRelayControl = new TestRelayControl(mainForm, WriteToLog, StopLog, StartLog, relayDescription, new ServiceBusHelper(WriteToLog, serviceBusHelper))
                {
                    Location = new Point(1, panelMain.HeaderHeight + 1),
                    Size     = new Size(panelMain.Size.Width - 3, panelMain.Size.Height - 26),
                    Anchor   = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                };

                Text = string.Format(TestRelayFormat, relayDescription.Path);

                testRelayControl.btnCancel.Text   = CloseLabel;
                testRelayControl.btnCancel.Click -= testRelayControl.btnCancel_Click;
                testRelayControl.btnCancel.Click += BtnCancelOnClick;
                testRelayControl.Focus();

                panelMain.HeaderText = string.Format(HeaderTextTestRelayFormat, relayDescription.Path);

                panelMain.Controls.Add(testRelayControl);
                SetStyle(ControlStyles.ResizeRedraw, true);
            }
            finally
            {
                panelMain.ResumeDrawing();
                ResumeLayout();
            }
        }
예제 #9
0
        static void ConfigureWcfCreateCommand(CommandLineApplication wcfCommand)
        {
            wcfCommand.RelayCommand("create", (createCmd) =>
            {
                createCmd.Description = "Create a WcfRelay";

                var pathArgument             = createCmd.Argument("path", "WcfRelay path");
                var connectionStringArgument = createCmd.Argument("connectionString", "Relay ConnectionString");

                var relayTypeOption = createCmd.Option(
                    "-t|--relaytype <relaytype>", "The RelayType (nettcp|http)", CommandOptionType.SingleValue);
                var requireClientAuthOption = createCmd.Option(
                    CommandStrings.RequiresClientAuthTemplate, CommandStrings.RequiresClientAuthDescription, CommandOptionType.SingleValue);
                var protocolOption = createCmd.AddSecurityProtocolOption();

                createCmd.OnExecute(async() =>
                {
                    ConfigureSecurityProtocol(protocolOption);
                    string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument);
                    if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(pathArgument.Value))
                    {
                        TraceMissingArgument(string.IsNullOrEmpty(connectionString) ? connectionStringArgument.Name : pathArgument.Name);
                        createCmd.ShowHelp();
                        return(1);
                    }

                    var connectionStringBuilder = new ServiceBusConnectionStringBuilder(connectionString);
                    RelayTraceSource.TraceInfo($"Creating WcfRelay '{pathArgument.Value}' in {connectionStringBuilder.Endpoints.First().Host}...");
                    var relayDescription = new RelayDescription(pathArgument.Value, GetRelayType(relayTypeOption));
                    relayDescription.RequiresClientAuthorization = GetBoolOption(requireClientAuthOption, true);
                    var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
                    await namespaceManager.CreateRelayAsync(relayDescription);
                    RelayTraceSource.TraceInfo($"Creating WcfRelay '{pathArgument.Value}' in {connectionStringBuilder.Endpoints.First().Host} succeeded");
                    return(0);
                });
            });
        }
예제 #10
0
        // ReSharper disable once FunctionComplexityOverflow
        private async void btnCreateDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceBusHelper == null)
                {
                    return;
                }
                if (btnCreateDelete.Text == DeleteText)
                {
                    using (var deleteForm = new DeleteForm(relayDescription.Path, RelayEntity.ToLower()))
                    {
                        if (deleteForm.ShowDialog() == DialogResult.OK)
                        {
                            await serviceBusHelper.NamespaceManager.DeleteRelayAsync(relayDescription.Path);

                            //serviceBusHelper.DeleteRelay(relayDescription.Path);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(txtPath.Text))
                    {
                        writeToLog(PathCannotBeNull);
                        return;
                    }
                    var description = new RelayDescription(txtPath.Text, (RelayType)Enum.Parse(typeof(RelayType), cboRelayType.Text, true))
                    {
                        UserMetadata = txtUserMetadata.Text,
                        RequiresClientAuthorization = checkedListBox.GetItemChecked(RequiresClientAuthorizationIndex),
                        RequiresTransportSecurity   = checkedListBox.GetItemChecked(RequiresTransportSecurityIndex)
                    };

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList <AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List <AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rightList));
                                }
                                else
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rule.SecondaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rightList));
                                }
                            }
                            else
                            {
                                description.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                            rule.ClaimType,
                                                                            rule.ClaimValue,
                                                                            rightList));
                            }
                        }
                    }
                    relayDescription = serviceBusHelper.CreateRelay(description);
                    InitializeControls();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
 public HandleRelayControl(WriteToLogDelegate writeToLog, ServiceBusHelper serviceBusHelper, RelayDescription relayDescription, string path)
 {
     this.writeToLog = writeToLog;
     this.serviceBusHelper = serviceBusHelper;
     this.relayDescription = relayDescription;
     this.path = path;
     dataPointBindingList = new BindingList<MetricDataPoint>
     {
         AllowNew = true,
         AllowEdit = true,
         AllowRemove = true
     };
     InitializeComponent();
     InitializeControls();
 } 
 public void RefreshData(RelayDescription relayService)
 {
     try
     {
         relayDescription = relayService;
         InitializeData();
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }
예제 #13
0
        /// <summary>
        /// Updates shared access signature authorization for the service bus entity. This authorization works on
        /// public Windows Azure environments and Windows Azure Pack on prim as well.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="entityName">The fully qualified service bus entity name</param>
        /// <param name="entityType">The service bus entity type (e.g. Queue)</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        /// <param name="primaryKey">The SAS primary key. It'll be generated if empty</param>
        /// <param name="secondaryKey">The SAS secondary key</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Shared Access Signature authorization rule</returns>
        public ExtendedAuthorizationRule UpdateSharedAccessAuthorization(
            string namespaceName,
            string entityName,
            ServiceBusEntityType entityType,
            string ruleName,
            string primaryKey,
            string secondaryKey,
            params AccessRights[] permissions)
        {
            bool removed = false;
            ExtendedAuthorizationRule rule = GetAuthorizationRule(namespaceName, entityName, entityType, ruleName);

            if (null == rule)
            {
                throw new ArgumentException(Resources.ServiceBusAuthorizationRuleNotFound);
            }

            SharedAccessAuthorizationRule oldRule = (SharedAccessAuthorizationRule)rule.Rule;

            SharedAccessAuthorizationRule newRule = new SharedAccessAuthorizationRule(
                ruleName,
                string.IsNullOrEmpty(primaryKey) ? SharedAccessAuthorizationRule.GenerateRandomKey() : primaryKey,
                secondaryKey,
                permissions ?? oldRule.Rights);

            // Create namespace manager
            NamespaceManager namespaceManager = CreateNamespaceManager(namespaceName);

            // Add the SAS rule and update the entity
            switch (entityType)
            {
            case ServiceBusEntityType.Queue:
                QueueDescription queue = namespaceManager.GetQueue(entityName);
                removed = queue.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                queue.Authorization.Add(newRule);
                namespaceManager.UpdateQueue(queue);
                break;

            case ServiceBusEntityType.Topic:
                TopicDescription topic = namespaceManager.GetTopic(entityName);
                removed = topic.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                topic.Authorization.Add(newRule);
                namespaceManager.UpdateTopic(topic);
                break;

            case ServiceBusEntityType.Relay:
                RelayDescription relay = namespaceManager.GetRelayAsync(entityName).Result;
                removed = relay.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                relay.Authorization.Add(newRule);
                namespaceManager.UpdateRelayAsync(relay).Wait();
                break;

            case ServiceBusEntityType.NotificationHub:
                NotificationHubDescription notificationHub = namespaceManager.GetNotificationHub(entityName);
                removed = notificationHub.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                notificationHub.Authorization.Add(newRule);
                namespaceManager.UpdateNotificationHub(notificationHub);
                break;

            default:
                throw new Exception(string.Format(Resources.ServiceBusEntityTypeNotFound, entityType.ToString()));
            }

            return(CreateExtendedAuthorizationRule(newRule, namespaceName, entityName, entityType));
        }
 /// <summary>
 /// Creates a new relay in the service namespace with the given name.
 /// </summary>
 /// <param name="description">A RelayDescription object describing the attributes with which the new event hub will be created.</param>
 /// <returns>Returns a newly-created RelayDescription object.</returns>
 public RelayDescription CreateRelay(RelayDescription description)
 {
     if (description == null)
     {
         throw new ArgumentException(DescriptionCannotBeNull);
     }
     if (namespaceManager != null)
     {
         var relayService = RetryHelper.RetryFunc(() => namespaceManager.CreateRelayAsync(description).Result, writeToLog);
         WriteToLogIf(traceEnabled, string.Format(CultureInfo.CurrentCulture, RelayCreated, description.Path));
         if (OnCreate != null) OnCreate(new ServiceBusHelperEventArgs(relayService, EntityType.Relay));
         return relayService;
     }
     throw new ApplicationException(ServiceBusIsDisconnected);
 }
 /// <summary>
 /// Gets the uri of a relay.
 /// </summary>
 /// <param name="description">The description of a relay.</param>
 /// <returns>The absolute uri of the relay.</returns>
 public Uri GetRelayUri(RelayDescription description)
 {
     if (description == null)
     {
         throw new ArgumentException(DescriptionCannotBeNull);
     }
     if (namespaceManager != null)
     {
         var currentScheme = description.RelayType != RelayType.Http
             ? scheme
             : description.RequiresTransportSecurity ? "https" : "http";
         return ServiceBusEnvironment.CreateServiceUri(currentScheme, Namespace, string.Concat(ServicePath, description.Path));
     }
     return null;
 }
예제 #16
0
        /***********************************************************************
        * The code below is not specific to Role Based Access Control.
        * The code below can work with any Microsoft.ServiceBus.TokenProvider.
        ***********************************************************************/

        static async Task RunWcfSampleAsync(string hostAddress, string wcfRelayName, TokenProvider tokenProvider, Binding binding)
        {
            var              namespaceManager = new NamespaceManager(hostAddress, tokenProvider);
            ServiceHost      serviceHost      = null;
            RelayDescription relayDescription = null;
            bool             deleted          = false;

            UriBuilder uriBuilder = new UriBuilder(hostAddress);

            uriBuilder.Scheme = binding.Scheme;
            uriBuilder.Path   = wcfRelayName;
            Uri relayAddress = uriBuilder.Uri;

            try
            {
                // Cannot create NetOneWay and NetEvent (extends NetOneway) Relays, they must be created dynamically
                if (!(binding is NetOnewayRelayBinding))
                {
                    Console.WriteLine("Creating the WCF Relay...");
                    relayDescription = new RelayDescription(wcfRelayName, GetRelayType(binding));
                    namespaceManager.CreateRelay(relayDescription);
                    Console.WriteLine($"Created the WCF Relay: {wcfRelayName}");
                }

                Console.WriteLine("Creating and opening the listener for the WCF Relay...");
                ServiceEndpoint endpoint = null;
                if (binding is NetTcpRelayBinding || binding is BasicHttpRelayBinding || binding is WSHttpRelayBinding)
                {
                    serviceHost = new ServiceHost(typeof(MathService), relayAddress);
                    endpoint    = serviceHost.AddServiceEndpoint(typeof(IMathService), binding, string.Empty);
                }
                else if (binding is WebHttpRelayBinding)
                {
                    serviceHost = new WebServiceHost(typeof(WebHttpService), relayAddress);
                    endpoint    = serviceHost.AddServiceEndpoint(typeof(IWebRequestResponse), binding, string.Empty);
                    endpoint.Behaviors.Add(new WebHttpBehavior());
                }
                else if (binding is NetOnewayRelayBinding)
                {
                    serviceHost = new ServiceHost(new NotificationService(), relayAddress);
                    endpoint    = serviceHost.AddServiceEndpoint(typeof(INotificationService), binding, string.Empty);
                }

                endpoint.EndpointBehaviors.Add(new TransportClientEndpointBehavior(tokenProvider));
                DisableHttpHelpPage(serviceHost);
                serviceHost.Open();
                Console.WriteLine($"The listener to {wcfRelayName} was sucessfully opened");

                Console.WriteLine($"Creating and sending with a channel to WCF Relay...");
                CreateAndSendWithChannel(relayAddress, tokenProvider, binding);
                Console.WriteLine($"Created and sent with channel to WCF Relay {wcfRelayName}");

                if (!(binding is NetOnewayRelayBinding))
                {
                    Console.WriteLine("Getting the WCF Relay...");
                    await namespaceManager.GetRelayAsync(relayDescription.Path);

                    Console.WriteLine($"Got WCF Relay {relayDescription.Path}");

                    Console.WriteLine("Updating the WCF Relay...");
                    await namespaceManager.UpdateRelayAsync(relayDescription);

                    Console.WriteLine($"Updated the WCF Relay {relayDescription.Path}");

                    Console.WriteLine("Deleting the WCF Relay...");
                    await namespaceManager.DeleteRelayAsync(relayDescription.Path);

                    Console.WriteLine($"Deleted the WCF Relay {relayDescription.Path}");
                    deleted = true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception: {e}");
            }
            finally
            {
                SafeClose(serviceHost);
                if (!deleted && relayDescription != null)
                {
                    await namespaceManager.DeleteRelayAsync(relayDescription.Path);
                }
            }
        }
예제 #17
0
        private void TestRelay(RelayDescription relayDescription, bool sdi)
        {
            if (sdi)
            {
                TestRelayControl relayServiceControl = null;

                try
                {
                    panelMain.SuspendDrawing();
                    foreach (var userControl in panelMain.Controls.OfType<UserControl>())
                    {
                        userControl.Dispose();
                    }
                    panelMain.Controls.Clear();
                    panelMain.BackColor = SystemColors.GradientInactiveCaption;
                    relayServiceControl = new TestRelayControl(this,
                                                               WriteToLog,
                                                               StopLog,
                                                               StartLog,
                                                               relayDescription,
                                                               serviceBusHelper);
                    relayServiceControl.SuspendDrawing();
                    relayServiceControl.Location = new Point(1, panelLog.HeaderHeight + 1);
                    panelMain.Controls.Add(relayServiceControl);
                    SetControlSize(relayServiceControl);
                    relayServiceControl.OnCancel += MainForm_OnCancel;
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
                finally
                {
                    panelMain.ResumeDrawing();
                    if (relayServiceControl != null)
                    {
                        relayServiceControl.ResumeDrawing();
                    }
                }
            }
            else
            {
                var form = new ContainerForm(serviceBusHelper, this, relayDescription);
                form.Show();
            }
        }
        // ReSharper disable once FunctionComplexityOverflow
        private async void btnCreateDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceBusHelper == null)
                {
                    return;
                }
                if (btnCreateDelete.Text == DeleteText)
                {
                    using (var deleteForm = new DeleteForm(relayDescription.Path, RelayEntity.ToLower()))
                    {
                        if (deleteForm.ShowDialog() == DialogResult.OK)
                        {
                            await serviceBusHelper.NamespaceManager.DeleteRelayAsync(relayDescription.Path);
                            //serviceBusHelper.DeleteRelay(relayDescription.Path);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(txtPath.Text))
                    {
                        writeToLog(PathCannotBeNull);
                        return;
                    }
                    var description = new RelayDescription(txtPath.Text, (RelayType)Enum.Parse(typeof(RelayType), cboRelayType.Text, true))
                    {
                        UserMetadata = txtUserMetadata.Text,
                        RequiresClientAuthorization = checkedListBox.GetItemChecked(RequiresClientAuthorizationIndex),
                        RequiresTransportSecurity = checkedListBox.GetItemChecked(RequiresTransportSecurityIndex)
                    };

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList<AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List<AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rightList));
                                }
                                else
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rule.SecondaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                    rightList));
                                }
                            }
                            else
                            {
                                description.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                            rule.ClaimType,
                                                                            rule.ClaimValue,
                                                                            rightList));
                            }
                        }
                    }
                    relayDescription = serviceBusHelper.CreateRelay(description);
                    InitializeControls();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
        // ReSharper disable once FunctionComplexityOverflow
        private void btnCancelUpdate_Click(object sender, EventArgs e)
        {
            if (btnCancelUpdate.Text == CancelText)
            {
                if (OnCancel != null)
                {
                    OnCancel();
                }
            }
            else
            {
                try
                {
                    relayDescription.UserMetadata = txtUserMetadata.Text;

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList<AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];

                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List<AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.PrimaryKey) && string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rightList));
                                }
                                else if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rightList));
                                }
                                else
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rule.SecondaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rightList));
                                }
                            }
                            else
                            {
                                relayDescription.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                                 rule.ClaimType,
                                                                                 rule.ClaimValue,
                                                                                 rightList));
                            }
                        }
                    }
                    relayDescription = serviceBusHelper.UpdateRelay(relayDescription);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                    relayDescription = serviceBusHelper.GetRelay(relayDescription.Path);
                }
                finally
                {
                    InitializeControls();
                }
            }
        }
 public TestRelayControl(MainForm mainForm, 
                         WriteToLogDelegate writeToLog,
                         Func<Task> stopLog,
                         Action startLog,
                         RelayDescription relayDescription, 
                         ServiceBusHelper serviceBusHelper)
 {
     this.mainForm = mainForm;
     this.writeToLog = writeToLog;
     this.stopLog = stopLog;
     this.startLog = startLog;
     this.relayDescription = relayDescription;
     this.serviceBusHelper = serviceBusHelper;
     InitializeComponent();
     InitializeControls();
 } 
예제 #21
0
        private void ShowRelay(RelayDescription relayService, string path)
        {
            HandleRelayControl relayServiceControl = null;

            try
            {
                panelMain.SuspendDrawing();
                foreach (var userControl in panelMain.Controls.OfType<UserControl>())
                {
                    userControl.Dispose();
                }
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;
                relayServiceControl = new HandleRelayControl(WriteToLog, serviceBusHelper, relayService, path);
                relayServiceControl.SuspendDrawing();
                relayServiceControl.Location = new Point(1, panelLog.HeaderHeight + 1);
                panelMain.Controls.Add(relayServiceControl);
                SetControlSize(relayServiceControl);
                relayServiceControl.OnCancel += MainForm_OnCancel;
                relayServiceControl.OnRefresh += MainForm_OnRefresh;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                panelMain.ResumeDrawing();
                if (relayServiceControl != null)
                {
                    relayServiceControl.ResumeDrawing();
                }
            }
        }
예제 #22
0
        // ReSharper disable once FunctionComplexityOverflow
        private void btnCancelUpdate_Click(object sender, EventArgs e)
        {
            if (btnCancelUpdate.Text == CancelText)
            {
                if (OnCancel != null)
                {
                    OnCancel();
                }
            }
            else
            {
                try
                {
                    relayDescription.UserMetadata = txtUserMetadata.Text;

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList <AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];

                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List <AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.PrimaryKey) && string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rightList));
                                }
                                else if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rightList));
                                }
                                else
                                {
                                    relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rule.PrimaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rule.SecondaryKey ?? SharedAccessAuthorizationRule.GenerateRandomKey(),
                                                                                                         rightList));
                                }
                            }
                            else
                            {
                                relayDescription.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                                 rule.ClaimType,
                                                                                 rule.ClaimValue,
                                                                                 rightList));
                            }
                        }
                    }
                    relayDescription = serviceBusHelper.UpdateRelay(relayDescription);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                    relayDescription = serviceBusHelper.GetRelay(relayDescription.Path);
                }
                finally
                {
                    InitializeControls();
                }
            }
        }
예제 #23
0
        public ContainerForm(ServiceBusHelper serviceBusHelper, MainForm mainForm, RelayDescription relayDescription)
        {
            try
            {
                InitializeComponent();
                Task.Factory.StartNew(AsyncWriteToLog).ContinueWith(t =>
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        WriteToLog(t.Exception.Message);
                    }
                });
                this.mainForm = mainForm;
                mainSplitterDistance = mainSplitContainer.SplitterDistance;
                SuspendLayout();
                panelMain.SuspendDrawing();
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;

                testRelayControl = new TestRelayControl(mainForm, WriteToLog, StopLog, StartLog, relayDescription, new ServiceBusHelper(WriteToLog, serviceBusHelper))
                {
                    Location = new Point(1, panelMain.HeaderHeight + 1),
                    Size = new Size(panelMain.Size.Width - 3, panelMain.Size.Height - 26),
                    Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                };

                Text = string.Format(TestRelayFormat, relayDescription.Path);

                testRelayControl.btnCancel.Text = CloseLabel;
                testRelayControl.btnCancel.Click -= testRelayControl.btnCancel_Click;
                testRelayControl.btnCancel.Click += BtnCancelOnClick;
                testRelayControl.Focus();

                panelMain.HeaderText = string.Format(HeaderTextTestRelayFormat, relayDescription.Path);

                panelMain.Controls.Add(testRelayControl);
                SetStyle(ControlStyles.ResizeRedraw, true);
            }
            finally
            {
                panelMain.ResumeDrawing();
                ResumeLayout();
            }
        }
예제 #24
0
        private static void CreateRelayKeys()
        {
            NamespaceManager nsManager = NamespaceManager.CreateFromConnectionString(
                "Endpoint=sb://johnsonwangnz.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=fBLL/4/+rEsCOiTQPNPS6DJQybykqE2HdVBsILrzMLY=");
            var relayDescription = new RelayDescription("MyService", RelayType.Http)
            {
                RequiresClientAuthorization = true,
                RequiresTransportSecurity = true
            };

            try
            {

                Task.Run(() => nsManager.DeleteRelayAsync(relayDescription.Path)).Wait();
            }
            catch (AggregateException aex)
            {
                Console.WriteLine(aex.InnerException);
            }
            catch (MessagingException ex)
            {
                Console.WriteLine(ex);
            }

            var sendKeyMyService = SharedAccessAuthorizationRule.GenerateRandomKey();
            var sendKeyNameMyService = "SendAccessKeyMyService";
            var listenKeyMyService = SharedAccessAuthorizationRule.GenerateRandomKey();
            var listenKeyNameMyService = "ListenAccessKeyMyService";

            relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(listenKeyNameMyService, listenKeyMyService,
                    new List<AccessRights> { AccessRights.Listen }));
            relayDescription.Authorization.Add(new SharedAccessAuthorizationRule(sendKeyNameMyService, sendKeyMyService,
                    new List<AccessRights> { AccessRights.Send }));

            try
            {

                var relay = Task.Run(() => nsManager.CreateRelayAsync(relayDescription)).Result;
            }
            catch (AggregateException aex)
            {
                Console.WriteLine(aex.InnerException);
            }
            catch (MessagingException ex)
            {
                Console.WriteLine(ex);
            }

            // the relay is available from azure portal, but not the keys

            using (StreamWriter file =
            new StreamWriter(@"MyServiceKeys.txt", true))
            {
                file.WriteLine("Service Path:" + relayDescription.Path);
                file.WriteLine("Listen Key Name:" + listenKeyNameMyService);
                file.WriteLine("Listen Key:" + listenKeyMyService);
                file.WriteLine("Send Key Name:" + sendKeyNameMyService);
                file.WriteLine("Send Key:" + sendKeyMyService);

            }

            Console.WriteLine("Listen access rule created with key '{0}' and name {2} on entity '{1}'", listenKeyMyService, relayDescription.Path, listenKeyNameMyService);
            Console.WriteLine("Send access rule created with key '{0}' and name {2} on entity '{1}'", sendKeyMyService, relayDescription.Path, sendKeyNameMyService);

            Console.ReadKey();
        }