https://stackoverflow.com/a/50267687/2063755 provides the following code to get the queue status:
string connectionString = "connection string";
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
var queueDescription = namespaceManager.GetQueue("queue name");
var status = queueDescription.Status;
How can I do that using NServiceBus?
I was hoping to use IEndpointInstance but it doesn't have many methods.
NServiceBus doesn't provide queue status. If you need the status of the queue, you will have to use the native Azure Service Bus SDK and NamespaceManager or ServiceBusAdministrativeClient, depending on what SDK you're using.
The latest version of NServiceBus uses the Azure.Messaging.ServiceBus SDK. To read the status of a queue queue the following would be needed:
var admin = new ServiceBusAdministrationClient(connectionString);
QueueProperties props = await admin.GetQueueAsync("queue");
var status = props.Status
Related
Currently, I have to switch our messaging system to use AmazonSQS and due to pricing policy, we are obliged to put tags. But I do not found any method to add tags.
Below the method which won't work due to fact that this approach is expecting that the queues already exist and I can get URL of the queue:
public static EndpointConfiguration CreateEndpointConfiguration(BusConfig config)
{
var endpointConfiguration = new EndpointConfiguration(config.QueueName);
endpointConfiguration.LicensePath("license.xml");
endpointConfiguration.SendFailedMessagesTo($"{config.QueueName}.Errors");
endpointConfiguration.EnableInstallers();
endpointConfiguration.UseSerialization<NewtonsoftSerializer>();
endpointConfiguration.LimitMessageProcessingConcurrencyTo(10);
endpointConfiguration.Conventions()
.DefiningEventsAs(type => typeof(IMessage).IsAssignableFrom(type))
.DefiningCommandsAs(type => typeof(ICommand).IsAssignableFrom(type));
var transport = endpointConfiguration.UseTransport<SqsTransport>();
transport.ClientFactory(() =>
{
var amazonSQSConfig = new AmazonSQSConfig()
{
RegionEndpoint = RegionEndpoint.USWest2
};
var client = new AmazonSQSClient(amazonSQSConfig);
var addedTags = new Dictionary<string, string>();
addedTags.Add("Team", "Development");
addedTags.Add("Accounting ID", "number");
var tagQueueRequest = new TagQueueRequest()
{
Tags = addedTags
};
client.TagQueueAsync(tagQueueRequest);
return client;
});
transport.QueueNamePrefix("some-prefix");
endpointConfiguration.Recoverability()
.AddUnrecoverableException<CustomException>();
return endpointConfiguration;
}
Can you provide solution for adding automatically tags during configuring endpoints?
Thank you for any help
The NServiceBus integration with SQS doesn't seem to support configuration of tags at the moment. You'd have to manually create your queues upfront with the appropriate tags or manually add tags to existing queues.
You can raise feature requests for tag support on Particular Software's SQS transport repository here: https://github.com/Particular/NServiceBus.AmazonSQS
I am currently working out the Microsoft Graph tutorial with C# .Net Core, and in the process I came across the following C#-method for Subscription:
[HttpGet]
public async Task<ActionResult<string>> Get()
{
var graphServiceClient = GetGraphClient();
var sub = new Microsoft.Graph.Subscription();
sub.ChangeType = "updated";
sub.NotificationUrl = config.Ngrok + "/api/notifications";
sub.Resource = "/users";
sub.ExpirationDateTime = DateTime.UtcNow.AddMinutes(15);
sub.ClientState = "SecretClientState";
var newSubscription = await graphServiceClient
.Subscriptions
.Request()
.AddAsync(sub);
Subscriptions[newSubscription.Id] = newSubscription;
if (subscriptionTimer == null)
{
subscriptionTimer = new Timer(CheckSubscriptions, null, 5000, 15000);
}
return $"Subscribed. Id: {newSubscription.Id}, Expiration: {newSubscription.ExpirationDateTime}";
}
and wanted to know how I can change it for sharepoint lists instead of users.
If I change it to /sites/{site-id} or similar it does not work. (see sub.Resource)
Github-Link: MS Repo
Microsoft Graph API uses a webhook mechanism to deliver change notifications to clients. Using the Microsoft Graph API, an app can subscribe to changes for list under a SharePoint site.
Resource Path - Changes to content within the list:
/sites/{id}/lists/{id}
For details round how to subscribe to and handle incoming notifications, see Set up notifications for changes in user data
Also make sure you check necessary permissions needed here.
I found the solution myself with the sub.Resource: /sites/{site-id}/lists/{list-id}
For the Microsoft Bot framework chatbot application that I am working on, I have configured the "Bot Channel Registration" and have hosted it on Azure.
One of the scenarios expects the user to record a video on skype and send it as an answer. I have an Azure function that saves the recorded video from skype to the Azure Storage account.
The issue I am encountering is, When I record a video on skype ()via Video Messaging option.
To gain access to the uploaded video from skype, I am providing appropriate bearer token along with the above mentioned URL but failing to get access to it.
Though the file that is uploaded from skype to the Queue (Azure function Queue triggers), the accessibility to this file is denied.
Assuming the latest patches would help, I updated all the references to .NET core 3.0.1 as of today. Looking forward to the desired approach to resolve this.
Note: This issue is only happening in "Skype for Desktop" version.
Below is the code block for your reference.
private static async Task<HttpResponseMessage> RequestFile(string contentUrl, ILogger logger, string serviceUrl)
{
var credentials = DIContainer.Instance.GetService<MicrosoftAppCredentials>();
var token = await credentials.GetTokenAsync();
using (var connectorClient = new ConnectorClient(new Uri(serviceUrl), credentials.MicrosoftAppId, credentials.MicrosoftAppPassword))
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
var test = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseContentRead);
return test;
}
}
}
Adding more code snippets:
private async Task<(string, string)> TrySaveAndGetContentUrl(IMessageActivity activity, string user)
{
var attachments = activity.Attachments;
if (attachments?.Any() ?? false)
{
var video = attachments.First();
return (await _attachmentsService.Save(video, user), video.ContentUrl);
}
return (null, null);
}
///_attachmentsService.Save method implementation
public async Task<string> Save(Attachment attachment, string user)
{
_logger.LogInformation("Enqueue save command. {#Attachment}", attachment);
var blobName = $"{user}/{Guid.NewGuid().ToString()}-{attachment.Name}";
var blob = _cloudBlobContainer.GetBlockBlobReference(blobName);
await EnqueueSaveCommand(attachment.ContentUrl, blobName, user);
return blob.Uri.ToString();
}
Please refer the below code block to save the attachments to Azure blob.
private async Task EnqueueSaveCommand(string contentUrl, string blobName, string user)
{
var queue = _queueClient.GetQueueReference(RouteNames.MediaAttachmentQueue); //RouteNames.MediaAttachmentQueue is "media-attachment-queue"
await queue.CreateIfNotExistsAsync();
var serializedMessage = JsonConvert.SerializeObject(new SaveMediaAttachmentCommand
{
FromUrl = contentUrl,
AttachmentName = blobName,
UserName = "userid#gmail.com",
});
var queueMessage = new CloudQueueMessage(serializedMessage);
await queue.AddMessageAsync(queueMessage);
}
Please suggest.
The Skype channel configuration contains the following message:
As of October 31, 2019 the Skype channel no longer accepts new Bot publishing requests. This means that you can continue to develop bots using the Skype channel, but your bot will be limited to 100 users. You will not be able to publish your bot to a larger audience. Current Skype bots will continue to run uninterrupted. Learn more
Many Skype features have been deprecated. If it was ever possible to send a video to a bot over Skype, it may not be possible any longer. It's recommended that you switch to other channels like Direct Line and Microsoft Teams.
I'm trying to integrate SendGrid to a .Net 4.5 application using WebJobs.
I made the basic configurations required to send a basic email. I'm trying to run and test it in my local machine. I can't figure out how to push messages to the queue. I can't upgrade the .Net version of the application as of now. If it is possible to do this without using webjobs that is also fine.
Program.cs
static void Main()
{
var config = new JobHostConfiguration();
config.UseTimers();
config.Queues.MaxDequeueCount = 2;
config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(4);
config.Queues.BatchSize = 2;
if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
config.UseSendGrid();
var host = new JobHost(config);
host.RunAndBlock();
}
Functions.cs
public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log, [SendGrid(From = "no-reply#company.com", To = "employee#company.com")] out Mail mail)
{
log.WriteLine(message);
mail = new Mail();
var personalization = new Personalization();
personalization.AddBcc(new Email("employee#company.com"));
mail.AddPersonalization(personalization);
mail.Subject = "Test Email Subject";
mail.AddContent(new Content("text/html", $"The message '{message}' was successfully processed."));
}
Found the following functions:
SendGrid_Test_002.Functions.ProcessQueueMessage
ServicePointManager.DefaultConnectionLimit is set to the default value of 2. This can limit the connection throughput to services like Azure Storage. For more information, see https://aka.ms/webjobs-connections.
Job host started
I get this on the console.
Thanks in advance :)
I just had to feed the messages into the webjob queue using the following code.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a container.
CloudQueue queue = queueClient.GetQueueReference("email-queue-name");
// Create the queue if it doesn't already exist
queue.CreateIfNotExists();
// Create message to be sent to the queue
CloudQueueMessage message = new CloudQueueMessage(JsonConvert.SerializeObject(new
{
From = emailContent.From,
To = emailContent.To,
Cc = emailContent.Cc,
Bcc = emailContent.Bcc,
Subject = emailContent.Subject,
Message = emailContent.Message
}).ToString());
queue.AddMessage(message);
I've been working with Azure Notification Hubs for awhile. However, I created a new Notification Hub for a new project and I've noticed some very odd behavior. Whenever I create a registration its ExpirationDate is set to 12/31/9999 7:59:59.
So, for some, I suppose this may be a benefit, but I'd like to expire mine after a certain period of inactivity. I looked through the RegistrationDescription object and found an ExpirationTime but it's read only...
How do I set this? Is this just a bug in Azure? Maybe a flag I'm missing from Azure configuration?
You can do that, but on hub level, not on registration level. Check out Improved Per Message Telemetry and device expiry for Notification Hubs blog post:
To take advantage of this expiry change, simply update your
notification hub’s Time To Live property. This can be done through
REST or our .NET SDK:
var namespaceManager = NamespaceManager.CreateFromConnectionString("connectionstring");
NotificationHubDescription hub = namespaceManager.GetNotificationHub("foo");
hub.RegistrationTtl = TimeSpan.MaxValue;
namespaceManager.UpdateNotificationHub(hub);
To do that via the REST API, check out Update Notification Hub method, which takes NotificationHubDescription body, which has a RegistrationTtl node in it. That should be a REST equivalent of the SDK code snippet above.
The documentation is outdated, I had to open a ticket with Microsoft to be able to do this in 2020.
I created a console app and added the following nuget packages -
https://www.nuget.org/packages/Microsoft.Azure.Management.NotificationHubs
https://www.nuget.org/packages/Microsoft.Azure.Management.ResourceManager.Fluent/
Install-Package Microsoft.Azure.Management.NotificationHubs -Version 2.3.2-preview
Install-Package Microsoft.Azure.Management.ResourceManager.Fluent -Version 1.34.0
Then I wrote this method -
private async Task SetNotificationHubRegistrationTimeToLive()
{
// Login to Azure using az login
// az account set -s <name or ID of subscription> to set the proper subscription
// Get credentials: "az ad sp create-for-rbac --sdk-auth"
// See https://learn.microsoft.com/en-us/cli/azure/get-started-with-azure-cli?view=azure-cli-latest and https://learn.microsoft.com/en-us/azure/cloud-shell/quickstart
var clientId = "ec1b...";
var clientSecret = "oJJ6...";
var tenantId = "2b86...";
var credentials =
SdkContext
.AzureCredentialsFactory
.FromServicePrincipal(
clientId,
clientSecret,
tenantId,
AzureEnvironment.AzureGlobalCloud);
var client = new NotificationHubsManagementClient(credentials)
{
SubscriptionId = "yoursubscriptionid"
};
var resourceGroupName = "yourgroup";
var namespaceName = "yournamespace"; // this should NOT be the namespace full name beam-dev-notification-hub-namespace-free.servicebus.windows.net
var notificationHubName = "yournotificationhub";
var timeSpan = new TimeSpan(days: 90, hours: 0, minutes: 0, seconds: 0);
var registrationTtlTimeSpanString = timeSpan.ToString();
var notificationHub = await client.NotificationHubs.GetAsync(resourceGroupName, namespaceName, notificationHubName);
await client
.NotificationHubs
.CreateOrUpdateAsync(
resourceGroupName,
namespaceName,
notificationHubName,
new NotificationHubCreateOrUpdateParameters(notificationHub.Location)
{
RegistrationTtl = registrationTtlTimeSpanString
});
}
You will then see in https://portal.azure.com/ in your notification hub properties -