Dafna
Dafna

Reputation: 181

Update azure service bus queue shared access policy programmatically

I would like to change the primary and secondary keys of an access rule of a queue (service bus in our case) programmatically (We would like to regenerate the primary key once a day). I would like to do this to an existing queue after it was already created. I know this can be done from the Azure portal (by clicking on the "Regen prim key" and "Regen sec key" of the policy windows) but I didn't manage to do it from my .Net code.

My code looks as follow:

SharedAccessAuthorizationRule rule;
            if (!queueDescription.Authorization.TryGetSharedAccessAuthorizationRule(ruleName, out rule))
            {
                // error
            }

            rule.SecondaryKey = rule.PrimaryKey;
            rule.PrimaryKey = SharedAccessAuthorizationRule.GenerateRandomKey();

After this code, the rule is not changed.....

Is there another way to do it...?

Thanks

Upvotes: 0

Views: 558

Answers (1)

Fei Han
Fei Han

Reputation: 27803

I know this can be done from the Azure portal (by clicking on the "Regen prim key" and "Regen sec key" of the policy windows) but I didn't manage to do it from my .Net code.

Please try to call UpdateQueue(QueueDescription) method to update the queue after you regenerate/reset the PrimaryKey for your authorization rule. And you could refer to the following sample code.

string connectionString = "Endpoint=sb://fehanservicebustest.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey={accesskey}";
string queueName = "{queuename}";

var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);


QueueDescription queueDescription = namespaceManager.GetQueue(queueName);

SharedAccessAuthorizationRule rule;

queueDescription.Authorization.TryGetSharedAccessAuthorizationRule("fehanlistenpolicy", out rule);

string newkey = SharedAccessAuthorizationRule.GenerateRandomKey();
rule.PrimaryKey = newkey;

namespaceManager.UpdateQueue(queueDescription);

Upvotes: 1

Related Questions