SharedAccessAuthorizationRule

We found 10 examples in language CSharp for this search. You will see 43 fragments of code.

        /// <summary>Returns the hash code for this instance.</summary>
        public override int GetHashCode()
        {
            int hash = 13;
            unchecked
            {
                hash = (hash * 7) + this.KeyName?.GetHashCode() ?? 0;
                hash = (hash * 7) + this.PrimaryKey?.GetHashCode() ?? 0;
                hash = (hash * 7) + this.SecondaryKey?.GetHashCode() ?? 0;
                hash = (hash * 7) + this.Rights.GetHashCode(); 
            }

            return hash;
        }

        public override bool Equals(object obj)
        {
            var other = obj as AuthorizationRule;
            return this.Equals(other);
        }

        /// <summary>Determines whether the specified object is equal to the current object.</summary>
        /// <param name="other">The object to compare with the current object.</param>
        /// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
        public override bool Equals(AuthorizationRule other)
        {
            if (!(other is SharedAccessAuthorizationRule))
            {
                return false;
            }

            SharedAccessAuthorizationRule comparand = (SharedAccessAuthorizationRule)other;
            if (!string.Equals(this.KeyName, comparand.KeyName, StringComparison.OrdinalIgnoreCase) ||
                !string.Equals(this.PrimaryKey, comparand.PrimaryKey, StringComparison.Ordinal) ||
                !string.Equals(this.SecondaryKey, comparand.SecondaryKey, StringComparison.Ordinal))
            {
                return false;
            }

            if ((this.Rights != null && comparand.Rights == null) ||
                (this.Rights == null && comparand.Rights != null))
            {
                return false;
            }

            if (this.Rights != null && comparand.Rights != null)
            {
                HashSet<AccessRights> thisRights = new HashSet<AccessRights>(this.Rights);
                if (comparand.Rights.Count != thisRights.Count)
                {
                    return false;
                }

                return thisRights.SetEquals(comparand.Rights);
            }

            return true;
        }

        /// <summary>Generates the random key for the authorization rule.</summary>        
        private static string GenerateRandomKey()
        {
            byte[] key256 = new byte[32];
            using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                rngCryptoServiceProvider.GetBytes(key256);
            }

            return Convert.ToBase64String(key256);
        }

        private static bool CheckBase64(string base64EncodedString)
        {
            try
            {
                Convert.FromBase64String(base64EncodedString);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        internal static new SharedAccessAuthorizationRule ParseFromXElement(XElement xElement)
        {
            var rule = new SharedAccessAuthorizationRule();
            foreach (var element in xElement.Elements())
            {
                switch (element.Name.LocalName)
                {
                    case "CreatedTime":
                        rule.CreatedTime = XmlConvert.ToDateTime(element.Value, XmlDateTimeSerializationMode.Utc);
                        break;
                    case "ModifiedTime":
                        rule.ModifiedTime = XmlConvert.ToDateTime(element.Value, XmlDateTimeSerializationMode.Utc);
                        break;
                    case "KeyName":
                        rule.KeyName = element.Value;
                        break;
                    case "PrimaryKey":
                        rule.PrimaryKey = element.Value;
                        break;
                    case "SecondaryKey":
                        rule.SecondaryKey = element.Value;
                        break;
                    case "Rights":
                        var rights = new List<AccessRights>();
                        var xRights = element.Elements(XName.Get("AccessRights", ManagementClientConstants.ServiceBusNamespace));
                        foreach (var xRight in xRights)
                        {
                            rights.Add((AccessRights)Enum.Parse(typeof(AccessRights), xRight.Value));
                        }
                        rule.Rights = rights;
                        break;
                }
            }

            return rule;
        }


		private static bool CheckBase64(string base64EncodedString)
		{
			bool flag;
			try
			{
				Convert.FromBase64String(base64EncodedString);
				flag = true;
			}
			catch (Exception exception)
			{
				flag = false;
			}
			return flag;
		}

		public override bool Equals(object obj)
		{
			if (!base.Equals(obj))
			{
				return false;
			}
			SharedAccessAuthorizationRule sharedAccessAuthorizationRule = (SharedAccessAuthorizationRule)obj;
			if (!string.Equals(this.KeyName, sharedAccessAuthorizationRule.KeyName, StringComparison.OrdinalIgnoreCase) || !string.Equals(this.PrimaryKey, sharedAccessAuthorizationRule.PrimaryKey, StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			return string.Equals(this.SecondaryKey, sharedAccessAuthorizationRule.SecondaryKey, StringComparison.OrdinalIgnoreCase);
		}

		public static string GenerateRandomKey()
		{
			byte[] numArray = new byte[32];
			using (RNGCryptoServiceProvider rNGCryptoServiceProvider = new RNGCryptoServiceProvider())
			{
				rNGCryptoServiceProvider.GetBytes(numArray);
			}
			return Convert.ToBase64String(numArray);
		}

		public override int GetHashCode()
		{
			int hashCode = base.GetHashCode();
			string[] keyName = new string[] { this.KeyName, this.PrimaryKey, this.SecondaryKey };
			string[] strArrays = keyName;
			for (int i = 0; i < (int)strArrays.Length; i++)
			{
				string str = strArrays[i];
				if (!string.IsNullOrEmpty(str))
				{
					hashCode = hashCode + str.GetHashCode();
				}
			}
			return hashCode;
		}

		private static bool IsValidCombinationOfRights(IEnumerable<AccessRights> rights)
		{
			if (!rights.Contains<AccessRights>(AccessRights.Manage))
			{
				return true;
			}
			return rights.Count<AccessRights>() == 3;
		}

		protected override void OnValidate()
		{
			if (string.IsNullOrEmpty(this.InternalKeyName) || !string.Equals(this.InternalKeyName, HttpUtility.UrlEncode(this.InternalKeyName)))
			{
				throw new InvalidDataContractException(SRCore.SharedAccessAuthorizationRuleKeyContainsInvalidCharacters);
			}
			if (this.InternalKeyName.Length > 256)
			{
				throw new InvalidDataContractException(SRCore.SharedAccessAuthorizationRuleKeyNameTooBig(256));
			}
			if (string.IsNullOrEmpty(this.InternalPrimaryKey))
			{
				throw new InvalidDataContractException(SRCore.SharedAccessAuthorizationRuleRequiresPrimaryKey);
			}
			if (Encoding.ASCII.GetByteCount(this.InternalPrimaryKey) != 44)
			{
				throw new InvalidDataContractException(SRCore.SharedAccessRuleAllowsFixedLengthKeys(44));
			}
			if (!SharedAccessAuthorizationRule.CheckBase64(this.InternalPrimaryKey))
			{
				throw new InvalidDataContractException(SRCore.SharedAccessKeyShouldbeBase64);
			}
			if (!string.IsNullOrEmpty(this.InternalSecondaryKey))
			{
				if (Encoding.ASCII.GetByteCount(this.InternalSecondaryKey) != 44)
				{
					throw new InvalidDataContractException(SRCore.SharedAccessRuleAllowsFixedLengthKeys(44));
				}
				if (!SharedAccessAuthorizationRule.CheckBase64(this.InternalSecondaryKey))
				{
					throw new InvalidDataContractException(SRCore.SharedAccessKeyShouldbeBase64);
				}
			}
			if (!SharedAccessAuthorizationRule.IsValidCombinationOfRights(base.Rights))
			{
				throw new InvalidDataContractException(SRClient.InvalidCombinationOfManageRight);
			}
		}


		public void Add(AuthorizationRule item)
		{
			SharedAccessAuthorizationRule sharedAccessAuthorizationRule;
			if (item is SharedAccessAuthorizationRule)
			{
				SharedAccessAuthorizationRule sharedAccessAuthorizationRule1 = item as SharedAccessAuthorizationRule;
				if (this.nameToSharedAccessAuthorizationRuleMap.TryGetValue(sharedAccessAuthorizationRule1.KeyName, out sharedAccessAuthorizationRule))
				{
					this.nameToSharedAccessAuthorizationRuleMap.Remove(sharedAccessAuthorizationRule1.KeyName);
					this.innerCollection.Remove(sharedAccessAuthorizationRule);
					this.duplicateAddForSharedAccessAuthorizationRule = true;
				}
				this.nameToSharedAccessAuthorizationRuleMap.Add(sharedAccessAuthorizationRule1.KeyName, sharedAccessAuthorizationRule1);
			}
			this.innerCollection.Add(item);
		}

		public void Clear()
		{
			this.nameToSharedAccessAuthorizationRuleMap.Clear();
			this.innerCollection.Clear();
		}

		public bool Contains(AuthorizationRule item)
		{
			return this.innerCollection.Contains(item);
		}

		public void CopyTo(AuthorizationRule[] array, int arrayIndex)
		{
			this.innerCollection.CopyTo(array, arrayIndex);
		}

		public IEnumerator<AuthorizationRule> GetEnumerator()
		{
			return this.innerCollection.GetEnumerator();
		}

		public List<AuthorizationRule> GetRules(Predicate<AuthorizationRule> match)
		{
			return ((List<AuthorizationRule>)this.innerCollection).FindAll(match);
		}

        static void Main(string[] args)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
                
            if (!namespaceManager.TopicExists(topicName))
            {
               var topicDescription= namespaceManager.CreateTopic(topicName);
                var sharedAccessSign = "RootManage";
                var authRule = topicDescription.Authorization.OfType<SharedAccessAuthorizationRule>().FirstOrDefault(c => c.KeyName == sharedAccessSign);
                if(authRule==null)
                {
                    authRule = new SharedAccessAuthorizationRule(sharedAccessSign, SharedAccessAuthorizationRule.GenerateRandomKey(), new[] { AccessRights.Manage,AccessRights.Send,AccessRights.Listen });
                    topicDescription.Authorization.Add(authRule);
                    namespaceManager.UpdateTopic(topicDescription);
                }
            }
            
            //Create the subscription if not exist to send the message 
            if (!namespaceManager.SubscriptionExists(topicName, subscriptionName))
            {
                namespaceManager.CreateSubscription(topicName, subscriptionName);
            }
            
            for (int i = 0; i < 5; i++)
            {
                // Create message, passing a string message for the body.
                BrokeredMessage message = new BrokeredMessage("Test message " + i);

                // Set additional custom app-specific property.
                message.Properties["MessageId"] = i;
                TopicClient Client = TopicClient.CreateFromConnectionString(connectionString, topicName);

                // Send message to the topic.
                Client.Send(message);
            }

            Console.ReadKey();
        }


        /// <summary>Returns the hash code for this instance.</summary>
        public override int GetHashCode()
        {
            int hash = 13;
            unchecked
            {
                hash = (hash * 7) + this.KeyName?.GetHashCode() ?? 0;
                hash = (hash * 7) + this.PrimaryKey?.GetHashCode() ?? 0;
                hash = (hash * 7) + this.SecondaryKey?.GetHashCode() ?? 0;
                hash = (hash * 7) + this.Rights.GetHashCode(); 
            }

            return hash;
        }

        public override bool Equals(object obj)
        {
            var other = obj as AuthorizationRule;
            return this.Equals(other);
        }

        /// <summary>Determines whether the specified object is equal to the current object.</summary>
        /// <param name="other">The object to compare with the current object.</param>
        /// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
        public override bool Equals(AuthorizationRule other)
        {
            if (!(other is SharedAccessAuthorizationRule))
            {
                return false;
            }

            SharedAccessAuthorizationRule comparand = (SharedAccessAuthorizationRule)other;
            if (!string.Equals(this.KeyName, comparand.KeyName, StringComparison.OrdinalIgnoreCase) ||
                !string.Equals(this.PrimaryKey, comparand.PrimaryKey, StringComparison.Ordinal) ||
                !string.Equals(this.SecondaryKey, comparand.SecondaryKey, StringComparison.Ordinal))
            {
                return false;
            }

            if ((this.Rights != null && comparand.Rights == null) ||
                (this.Rights == null && comparand.Rights != null))
            {
                return false;
            }

            if (this.Rights != null && comparand.Rights != null)
            {
                HashSet<AccessRights> thisRights = new HashSet<AccessRights>(this.Rights);
                if (comparand.Rights.Count != thisRights.Count)
                {
                    return false;
                }

                return thisRights.SetEquals(comparand.Rights);
            }

            return true;
        }

        /// <summary>Generates the random key for the authorization rule.</summary>        
        private static string GenerateRandomKey()
        {
            byte[] key256 = new byte[32];
            using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                rngCryptoServiceProvider.GetBytes(key256);
            }

            return Convert.ToBase64String(key256);
        }

        private static bool CheckBase64(string base64EncodedString)
        {
            try
            {
                Convert.FromBase64String(base64EncodedString);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        internal static new SharedAccessAuthorizationRule ParseFromXElement(XElement xElement)
        {
            var rule = new SharedAccessAuthorizationRule();
            foreach (var element in xElement.Elements())
            {
                switch (element.Name.LocalName)
                {
                    case "CreatedTime":
                        rule.CreatedTime = XmlConvert.ToDateTime(element.Value, XmlDateTimeSerializationMode.Utc);
                        break;
                    case "ModifiedTime":
                        rule.ModifiedTime = XmlConvert.ToDateTime(element.Value, XmlDateTimeSerializationMode.Utc);
                        break;
                    case "KeyName":
                        rule.KeyName = element.Value;
                        break;
                    case "PrimaryKey":
                        rule.PrimaryKey = element.Value;
                        break;
                    case "SecondaryKey":
                        rule.SecondaryKey = element.Value;
                        break;
                    case "Rights":
                        var rights = new List<AccessRights>();
                        var xRights = element.Elements(XName.Get("AccessRights", ManagementClientConstants.ServiceBusNamespace));
                        foreach (var xRight in xRights)
                        {
                            rights.Add((AccessRights)Enum.Parse(typeof(AccessRights), xRight.Value));
                        }
                        rule.Rights = rights;
                        break;
                }
            }

            return rule;
        }


        public static void CreateSASRuleOnNamespaceRoot(string subscriptionID, string managementCertSN, string serviceNamespace)
        {
            // The endpoint for creating a SAS rule on a namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                    serviceNamespace + @"/AuthorizationRules/";

            // The SAS rule we'll create has keyName as "contosoSendAll, a base64 encoded 256-bit key and the Send right
            var sendRule = new SharedAccessAuthorizationRule("contosoSendAll",
                SharedAccessAuthorizationRule.GenerateRandomKey(),
                new[] { AccessRights.Send });

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };
            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            // Do a POST on the baseAddress above to create an auth rule
            var postResult = httpClient.PostAsJsonAsync("", sendRule).Result;
        }

        public static List<SharedAccessAuthorizationRule> ReadSASRulesOnNamespaceRoot(string subscriptionID, string managementCertSN, string serviceNamespace)
        {
            // The endpoint for retrieving the SAS rules on the namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                    serviceNamespace + @"/AuthorizationRules/";

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };
            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            // Doing a GET on the base address above returns all the auth rules configured.
            var getResult = httpClient.GetAsync("").Result;
            List<SharedAccessAuthorizationRule> rules = new List<SharedAccessAuthorizationRule>();
            rules = getResult.Content.ReadAsAsync<List<SharedAccessAuthorizationRule>>().Result;
            return rules;
        }

        public static void RollSharedAccessKeyOnNamespaceRoot(string subscriptionID, string managementCertSN, string serviceNamespace, List<SharedAccessAuthorizationRule> rules)
        {
            // The endpoint for a SAS rules on the namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                    serviceNamespace + @"/AuthorizationRules/";

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };
            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            rules.ForEach(delegate(SharedAccessAuthorizationRule rule)
            {
                // Roll keys on all rules except the "RootManageSharedAccessKey"
                if (!String.Equals(rule.KeyName, "RootManageSharedAccessKey", StringComparison.Ordinal))
                {
                    rule.SecondaryKey = rule.PrimaryKey;
                    rule.PrimaryKey = SharedAccessAuthorizationRule.GenerateRandomKey();

                    // Update the rule
                    var putResult = httpClient.PutAsJsonAsync(rule.KeyName, rule).Result;
                }
            });
        }

        public static void DeleteSASRuleOnNamespaceRootByKeyName(string subscriptionID, string managementCertSN, string serviceNamespace, string keyName)
        {
            // The endpoint for a SAS rules on the namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                    serviceNamespace + @"/AuthorizationRules/";

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };
            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            // Do a DELETE on the "baseAddress/KeyName" to delete the auth rule
            var deleteResult = httpClient.DeleteAsync(keyName).Result;

        }

        private static X509Certificate2 GetCertificate(string subjectName)
        {
            X509Certificate2 certificate = null;
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly);
            X509Certificate2Collection collection = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false);
            store.Close();
            if (collection.Count > 0)
            {
                certificate = collection[0];
            }

            return certificate;
        }


        public static void CreateSASRuleOnNamespaceRoot(string subscriptionID, string managementCertSN, string serviceNamespace)
        {
            // The endpoint for creating a SAS rule on a namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                    serviceNamespace + @"/AuthorizationRules/";

            // The SAS rule we'll create has keyName as "contosoSendAll, a base64 encoded 256-bit key and the Send right
            var sendRule = new SharedAccessAuthorizationRule("contosoSendAll",
                SharedAccessAuthorizationRule.GenerateRandomKey(),
                new[] { AccessRights.Send });

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };
            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            // Do a POST on the baseAddress above to create an auth rule
            var postResult = httpClient.PostAsJsonAsync("", sendRule).Result;
        }

        public static List<SharedAccessAuthorizationRule> ReadSASRulesOnNamespaceRoot(string subscriptionID, string managementCertSN, string serviceNamespace)
        {
            // The endpoint for retrieving the SAS rules on the namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                    serviceNamespace + @"/AuthorizationRules/";

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };
            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            // Doing a GET on the base address above returns all the auth rules configured.
            var getResult = httpClient.GetAsync("").Result;
            List<SharedAccessAuthorizationRule> rules = new List<SharedAccessAuthorizationRule>();
            rules = getResult.Content.ReadAsAsync<List<SharedAccessAuthorizationRule>>().Result;
            return rules;
        }

        public static void RollSharedAccessKeyOnNamespaceRoot(string subscriptionID, string managementCertSN, string serviceNamespace, List<SharedAccessAuthorizationRule> rules)
        {
            // The endpoint for a SAS rules on the namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                    serviceNamespace + @"/AuthorizationRules/";

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };
            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            rules.ForEach(delegate(SharedAccessAuthorizationRule rule)
            {
                // Roll keys on all rules except the "RootManageSharedAccessKey"
                if (!String.Equals(rule.KeyName, "RootManageSharedAccessKey", StringComparison.Ordinal))
                {
                    rule.SecondaryKey = rule.PrimaryKey;
                    rule.PrimaryKey = SharedAccessAuthorizationRule.GenerateRandomKey();

                    // Update the rule
                    var putResult = httpClient.PutAsJsonAsync(rule.KeyName, rule).Result;
                }
            });
        }

        public static void DeleteSASRuleOnNamespaceRootByKeyName(string subscriptionID, string managementCertSN, string serviceNamespace, string keyName)
        {
            // The endpoint for a SAS rules on the namespace is:
            //     "https://management.core.windows.net/{subscriptionId}/services/ServiceBus/namespaces/{namespace}/AuthorizationRules/"
            string baseAddress = @"https://" + managementEndpoint + subscriptionID + @"/services/ServiceBus/namespaces/" +
                    serviceNamespace + @"/AuthorizationRules/";

            // Operations on the Service Bus namespace root require certificate authentication.
            WebRequestHandler handler = new WebRequestHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual
            };
            handler.ClientCertificates.Add(GetCertificate(managementCertSN));

            HttpClient httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");

            // Do a DELETE on the "baseAddress/KeyName" to delete the auth rule
            var deleteResult = httpClient.DeleteAsync(keyName).Result;

        }

        private static X509Certificate2 GetCertificate(string subjectName)
        {
            X509Certificate2 certificate = null;
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly);
            X509Certificate2Collection collection = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false);
            store.Close();
            if (collection.Count > 0)
            {
                certificate = collection[0];
            }

            return certificate;
        }

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
// 
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.

namespace Microsoft.Azure.Management.IotHub.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// The properties of the provisioned event hub used by the Iot Hub.
    /// </summary>
    public partial class EventHubProperties
    {
        /// <summary>
        /// Initializes a new instance of the EventHubProperties class.
        /// </summary>
        public EventHubProperties() { }

        /// <summary>
        /// Initializes a new instance of the EventHubProperties class.
        /// </summary>
        public EventHubProperties(long? retentionTimeInDays = default(long?), int? partitionCount = default(int?), IList<string> partitionIds = default(IList<string>), string path = default(string), string endpoint = default(string), IList<SharedAccessAuthorizationRule> internalAuthorizationPolicies = default(IList<SharedAccessAuthorizationRule>), IList<SharedAccessAuthorizationRule> authorizationPolicies = default(IList<SharedAccessAuthorizationRule>))
        {
            RetentionTimeInDays = retentionTimeInDays;
            PartitionCount = partitionCount;
            PartitionIds = partitionIds;
            Path = path;
            Endpoint = endpoint;
            InternalAuthorizationPolicies = internalAuthorizationPolicies;
            AuthorizationPolicies = authorizationPolicies;
        }

        /// <summary>
        /// The retention time in days. Range of values [For F1: 1-1, S1: 1-7,
        /// S2: 1-7, S3: 1-7].
        /// </summary>
        [JsonProperty(PropertyName = "retentionTimeInDays")]
        public long? RetentionTimeInDays { get; set; }

        /// <summary>
        /// The partition count. Range of values [For F1: 2-2, S1: 2-128, S2:
        /// 2-128, S3: 2-128].
        /// </summary>
        [JsonProperty(PropertyName = "partitionCount")]
        public int? PartitionCount { get; set; }

        /// <summary>
        /// The partition ids.
        /// </summary>
        [JsonProperty(PropertyName = "partitionIds")]
        public IList<string> PartitionIds { get; set; }

        /// <summary>
        /// The eventhub path.
        /// </summary>
        [JsonProperty(PropertyName = "path")]
        public string Path { get; set; }

        /// <summary>
        /// The endpoint.
        /// </summary>
        [JsonProperty(PropertyName = "endpoint")]
        public string Endpoint { get; set; }

        /// <summary>
        /// The internal authorization rules.
        /// </summary>
        [JsonProperty(PropertyName = "internalAuthorizationPolicies")]
        public IList<SharedAccessAuthorizationRule> InternalAuthorizationPolicies { get; set; }

        /// <summary>
        /// The authorization rules.
        /// </summary>
        [JsonProperty(PropertyName = "authorizationPolicies")]
        public IList<SharedAccessAuthorizationRule> AuthorizationPolicies { get; set; }

    }
}


        private ServiceBusNamespace TryGetNamespace(string name)
        {
            try
            {
                return ServiceBusClient.Namespaces.Get(name).Namespace;
            }
            catch (CloudException)
            {
                // The namespace does not exist.
                return null;
            }
        }

        private ExtendedServiceBusNamespace GetExtendedServiceBusNamespace(string name)
        {
            ServiceBusNamespace sbNamespace = TryGetNamespace(name);

            if (sbNamespace != null &&
                sbNamespace.Status.Equals("Active", StringComparison.OrdinalIgnoreCase))
            {
                IList<ServiceBusNamespaceDescription> descriptions = ServiceBusClient.Namespaces
                    .GetNamespaceDescription(name)
                    .NamespaceDescriptions;

                return new ExtendedServiceBusNamespace(sbNamespace, descriptions);
            }

            return null;
        }

        private NamespaceManager CreateNamespaceManager(string namespaceName)
        {
            return NamespaceManager.CreateFromConnectionString(GetConnectionString(
                namespaceName,
                NamespaceACSConnectionStringKeyName));
        }

        private ExtendedAuthorizationRule CreateExtendedAuthorizationRule(
            AuthorizationRule rule,
            string namespaceName)
        {
            string connectionString = string.Empty;

            if (IsActiveNamespace(namespaceName))
            {
                connectionString = GetConnectionString(namespaceName, rule.KeyName);
            }

            return new ExtendedAuthorizationRule()
            {
                Rule = rule,
                Name = rule.KeyName,
                Namespace = namespaceName,
                Permission = rule.Rights.ToList(),
                ConnectionString = connectionString
            };
        }

        private bool IsActiveNamespace(string name)
        {
            return ServiceBusClient.Namespaces.Get(name).Namespace.Status
                .Equals("Active", StringComparison.OrdinalIgnoreCase);
        }

        private ExtendedAuthorizationRule CreateExtendedAuthorizationRule(
            AuthorizationRule rule,
            string namespaceName,
            string entityName,
            ServiceBusEntityType entityType)
        {
            return new ExtendedAuthorizationRule()
            {
                Rule = rule,
                Name = rule.KeyName,
                Permission = rule.Rights.ToList(),
                ConnectionString = GetConnectionString(namespaceName, entityName, entityType, rule.KeyName),
                Namespace = namespaceName,
                EntityName = entityName,
                EntityType = entityType
            };
        }

	string queuePolicyName = "SendPolicy";
	string queuePrimaryKey = SharedAccessAuthorizationRule.GenerateRandomKey();
    QueueDescription queueDescription = new QueueDescription(queueName);
	SharedAccessAuthorizationRule queueSharedAccessPolicy = new SharedAccessAuthorizationRule(queuePolicyName, queuePrimaryKey, new[] { AccessRights.Send });
	queueDescription.Authorization.Add(queueSharedAccessPolicy);
	await _namespaceManager.CreateQueueAsync(queueDescription);

Azure.Messaging.ServiceBus.Administration.SharedAccessAuthorizationRule : IEquatable

Constructors :

public SharedAccessAuthorizationRule(String keyName = , IEnumerable<AccessRights> rights = )
public SharedAccessAuthorizationRule(String keyName = , String primaryKey = , IEnumerable<AccessRights> rights = )
public SharedAccessAuthorizationRule(String keyName = , String primaryKey = , String secondaryKey = , IEnumerable<AccessRights> rights = )

Methods :

public String get_ClaimType()
public String get_KeyName()
public Void set_KeyName(String value = )
public String get_PrimaryKey()
public Void set_PrimaryKey(String value = )
public String get_SecondaryKey()
public Void set_SecondaryKey(String value = )
public List<AccessRights> get_Rights()
public Void set_Rights(List<AccessRights> value = )
public Int32 GetHashCode()
public Boolean Equals(Object obj = )
public Boolean Equals(AuthorizationRule other = )
public static Boolean op_Equality(SharedAccessAuthorizationRule left = , SharedAccessAuthorizationRule right = )
public static Boolean op_Inequality(SharedAccessAuthorizationRule left = , SharedAccessAuthorizationRule right = )
public DateTimeOffset get_CreatedTime()
public DateTimeOffset get_ModifiedTime()
public Type GetType()
public String ToString()