How can I set the type of azure service bus to notification hub programmatically - c#-4.0

Using methods below, I previously (until last week) could create a service bus with a "mixed" type and then could add a notification hub. However, it suddenly stopped working. It creates a service bus with "Messaging" type and when it tries to create the notification hub, I get the error below:
Enity xxxxxx, create notification hub failed with error forbidden
public ServiceBusNamespaceResponse CreateServiceBus(SubscriptionCloudCredentials credentials, string regoin)
{
var serviceBushubClient = CloudContext.Clients.CreateServiceBusManagementClient(credentials);
var checkserviceBusResponse = serviceBushubClient.Namespaces.CheckAvailability(_deploymentName);
if (checkserviceBusResponse.IsAvailable)
{
try
{
var serviceBusClientResponse = serviceBushubClient.Namespaces.Create(_deploymentName, regoin);
_serviceBusEndpoint = serviceBusClientResponse.Namespace.ServiceBusEndpoint.ToString();
return serviceBusClientResponse;
}
catch (CloudException ex)
{
Console.WriteLine(ex.ErrorMessage);
return null;
}
}
return null;
}
and
public bool CreateNotificationHub(SubscriptionCloudCredentials credentials)
{
SBNotificationHubManager notificationHub;
EntityDescription servesBus = new EntityDescription();
servesBus.Name =_deploymentID;
var des = new MyNotificationHubDescription("push-hub-" + TenantID, servesBus);
notificationHub =
ResourceFactory.Get( _subscriptionID,
new X509Certificate2(Convert.FromBase64String(RowData._base64EncodedCert)),
SBRestResourceType.NHub, des) as SBNotificationHubManager;
if (notificationHub != null)
{
// Console.WriteLine("Created Notification Hub: {0}{1}", Environment.NewLine, notificationHub.LookUp().ToString());
if (notificationHub.Create())
{
Console.WriteLine("Created Notification Hub: {0}{1}", Environment.NewLine, notificationHub.LookUp().ToString());
notificationHub.WaitUntillActive();
return true;
}
}
return false;
}
I was wondering if something recently changed in azure? Can anyone please advise how to define the type of service bus (messaging/notification hub) when creating it in c#. The default with the above method is messaging. I need mixed, but notification hub type also works fine in my case.
Thank you

Now you must explicitly select Messaging (for topics/queues/event hubs) or NotificationHub (for notification hubs). That is idea.
About implementation. Observing source codes I can see overload which accepts ServiceBusNamespaceCreateParameters argument:
Task<ServiceBusNamespaceResponse> CreateNamespaceAsync(string namespaceName, ServiceBusNamespaceCreateParameters namespaceEntity, CancellationToken cancellationToken);
That class has public property of NamespaceType
public NamespaceType NamespaceType{...
So you probably could set it to NamespaceType.NotificationHub and then go ahead to create namespace.

Related

Application Insights + Azure Service Bus - Capture message from the bus in dependency tracking

I am looking into how the app insights work with different types of dependencies. I have a question on using the AppInsights ASP Net Core sdk with Messaging Service Bus sdk.
How can I capture messages to service bus while sending or receiving using this sdk in dependency? I understand that this is not something we would like to log all the time and I will make it configurable.
Thanks
You can create your own sender and implement the desired logic inside the SendMessageAsync method:
public class TelemetryEnabledServiceBusSender : ServiceBusSender
{
private readonly TelemetryClient telemetryClient;
internal TelemetryEnabledServiceBusSender(ServiceBusClient client, string topic, TelemetryClient telemetryClient) : base(client, topic)
{
this.telemetryClient = telemetryClient;
}
public override async Task SendMessageAsync(ServiceBusMessage message, CancellationToken cancellationToken = default)
{
telemetryClient.TrackTrace(message.Body.ToString());
await base.SendMessageAsync(message, cancellationToken);
}
}
use it like this:
var serviceBusSender = new TelemetryEnabledServiceBusSender(serviceBusClient, serviceBusData.Topic, telemetryClient);
await serviceBusSender.SendMessageAsync(message);
Logging processed messages is even simpler and can be done using the ServiceBusProcessor
serviceBusProcessor.ProcessMessageAsync += ProcessMessageAsync;
...
private async Task ProcessMessageAsync(ProcessMessageEventArgs arg)
{
telemetryClient.TrackTrace(arg.Message.Body.ToString());
...
}
Adding my approach as an answer here as it is too long to comment.
var telemetry = new DependencyTelemetry(
"Azure Service Bus",
_serviceBusClient.FullyQualifiedNamespace,
"ServiceBusReceiver.Receive",
string.Empty
);
using var operation =
_telemetryClient.StartOperation(telemetry);
try
{
var receivedMessage = await _serviceBusReceiver.ReceiveMessageAsync();
if (receivedMessage?.Body is not null)
{
message = receivedMessage.Body.ToString();
telemetry.Data = message;
// do something
}
telemetry.Success = true;
//Consider set telemetry duration
}
catch (Exception e)
{
// log exception
_telemetryClient.TrackException(e);
telemetry.Success = false;
throw;
}
finally
{
_telemetryClient.TrackTrace("Done");
_telemetryClient.StopOperation(operation);
}
Thanks to #Peter Bons

How to show event message in Azure Service Fabric Explorer

I'm new to Azure Service Fabric. I follow the tutorial to create hello demo service for Stateless.
It's simple service and I can find the Event Message in local VS IDE Diagnostic Events to show the message that I print
ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0}", ++iterations);
Like below picture:
But I can't see any log for cluster manager explorer.
Is it possible to show the event log in this explorer? How to do it?
There are my demo event source class code;
[NonEvent]
public void Message(string message, params object[] args)
{
if (this.IsEnabled())
{
string finalMessage = string.Format(message, args);
Message(finalMessage);
}
}
private const int MessageEventId = 1;
[Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")]
public void Message(string message)
{
if (this.IsEnabled())
{
WriteEvent(MessageEventId, message);
}
}
Pretty sure that currently the Service Fabric Explorer (SFX) only shows node level events and not application specific events.
According to the resent 7.0 release announcement (https://techcommunity.microsoft.com/t5/Azure-Service-Fabric/Service-Fabric-7-0-Release/ba-p/1015482) work is ongoing to display application specific events in SFX

How to solve Unhandle Exception:System.Net Socket.SocketException in azure iot readmessage device?

Hi i have the following code, that reads the message to the device. I have azure portal running. But i get the following exception when running on a command prompt;
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.Azure.EventHubs;
using System.Threading.Tasks;
using System.Threading;
using System.Text;
using System.Collections.Generic;
namespace read_d2c_messages
{
class ReadDeviceToCloudMessages
{
// Event Hub-compatible endpoint
// az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {your IoT Hub name}
private readonly static string s_eventHubsCompatibleEndpoint ="sb://iothub-ns-mydeviceco......";
// Event Hub-compatible name
// az iot hub show --query properties.eventHubEndpoints.events.path --name {your IoT Hub name}
private readonly static string s_eventHubsCompatiblePath = "mydeviceconnection";
// az iot hub policy show --name service --query primaryKey --hub-name {your IoT Hub name}
private readonly static string s_iotHubSasKey = "";
private readonly static string s_iotHubSasKeyName = "service";
private static EventHubClient s_eventHubClient;
// Asynchronously create a PartitionReceiver for a partition and then start
// reading any messages sent from the simulated client.
private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
{
// Create the receiver using the default consumer group.
// For the purposes of this sample, read only messages sent since
// the time the receiver is created. Typically, you don't want to skip any messages.
var eventHubReceiver = s_eventHubClient.CreateReceiver("$Default", partition, EventPosition.FromEnqueuedTime(DateTime.Now));
Console.WriteLine("Create receiver on partition: " + partition);
while (true)
{
if (ct.IsCancellationRequested) break;
Console.WriteLine("Listening for messages on: " + partition);
// Check for EventData - this methods times out if there is nothing to retrieve.
var events = await eventHubReceiver.ReceiveAsync(100);
// If there is data in the batch, process it.
if (events == null) continue;
foreach(EventData eventData in events)
{
string data = Encoding.UTF8.GetString(eventData.Body.Array);
Console.WriteLine("Message received on partition {0}:", partition);
Console.WriteLine(" {0}:", data);
Console.WriteLine("Application properties (set by device):");
foreach (var prop in eventData.Properties)
{
Console.WriteLine(" {0}: {1}", prop.Key, prop.Value);
}
Console.WriteLine("System properties (set by IoT Hub):");
foreach (var prop in eventData.SystemProperties)
{
Console.WriteLine(" {0}: {1}", prop.Key, prop.Value);
}
}
}
}
private static async Task Main(string[] args)
{
Console.WriteLine("IoT Hub Quickstarts - Read device to cloud messages. Ctrl-C to exit.\n");
// Create an EventHubClient instance to connect to the
// IoT Hub Event Hubs-compatible endpoint.
var connectionString = new EventHubsConnectionStringBuilder(new Uri(s_eventHubsCompatibleEndpoint), s_eventHubsCompatiblePath, s_iotHubSasKeyName, s_iotHubSasKey);
s_eventHubClient = EventHubClient.CreateFromConnectionString(connectionString.ToString());
// Create a PartitionReciever for each partition on the hub.
var runtimeInfo = await s_eventHubClient.GetRuntimeInformationAsync();
var d2cPartitions = runtimeInfo.PartitionIds;
CancellationTokenSource cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
cts.Cancel();
Console.WriteLine("Exiting...");
};
var tasks = new List<Task>();
foreach (string partition in d2cPartitions)
{
tasks.Add(ReceiveMessagesFromDeviceAsync(partition, cts.Token));
}
// Wait for all the PartitionReceivers to finsih.
Task.WaitAll(tasks.ToArray());
}
}
}
On my command prompt, the exception is System.Net.Sockets.SocketException:A connection attempt failed because the connected party did not properly respond after a period of time, or established failed because host has failed to respond at Microsoft.Azure.EventHub.Amqp.AmqpHubClient.CreateConnectionAsync(TimeSpan, Timeout); What kind of error is this? Is had to do with firewall connectivity issue on my connection string not to receive message? Or hence i am using Free Trail cant be able to create Service-Bus-Messsage on my EndPoint?
I think the way you construct your connection string is not quite correct. When you copy the connection string from your IoT Hub in the full format, this should already work:
s_eventHubClient = EventHubClient.CreateFromConnectionString("Endpoint=sb://iothub-xxxxxx-1180347-e18a7c8824.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=qya62bOiN0********gIyEQ=;EntityPath=myiothubname");

Azure Notification HUB with FCM - NullPointerException

I am trying to register my FCM service with Azure Notification hub.
I am getting a valid FCM token using my Instance Id Service which extends FirebaseMessagingService().
Below is my InstanceIdService which is returning a valid token and starts my registrationIntentService
class FCMInstanceIdService : FirebaseMessagingService() {
companion object {
private const val TAG = "FCMInstanceIDService"
}
init {
Log.i(TAG, "init")
}
override fun onNewToken(refreshedToken: String?) {
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener { instanceIdResult ->
instanceIdResult.token
// Log the event
Log.i(TAG, "Refreshing GCM Registration Token")
// Declare our intent to start the service
val intent = Intent(this, FCMRegistrationIntentService::class.java)
// Start the service!
startService(intent)
}
}
}
Below is the portion of code where-in I try to register this token with my notification hub.
// Declare the azure notification hub
val notificationHub = NotificationHub(
// Provide our notification hub name
CentreMK.FCM_NOTIFICATION_HUB_NAME,
// Provide our notification hub connection string
CentreMK.FCM_NOTIFICATION_HUB_LISTEN_CONNECTION_STRING,
// The context of this service
this)
// Log the event
Log.i(TAG, "Attempting to register with NH using token : $token")
// Update the registration id by registering our token with the notification hub
// This provides us with the registration id
regID = notificationHub.register(token).registrationId
This is the exception I get :
Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
Any help is appreciated cause I dont know how I could possibly get a null pointer exception when I've configured everything correctly.
In your initialisation of the String HubListenConnectionStringin class:
public class NotificationSettings {
public static String SenderId = "<Your project number>";
public static String HubName = "<Your HubName>";
public static String HubListenConnectionString = "<Enter your DefaultListenSharedAccessSignature connection string>";
}
you did not add "Endpoint=sb://"to the beginning of the string (i.e: public static String HubListenConnectionString ="Endpoint=sb://......". After which you might encounter a "Resource not found" exception error. That's where I am stuck at now.

Getting notified of a new subscription in NServiceBus

Does anyone know of a way that I can get notified of a new subscription occurring for a publisher in NServiceBus? I'd like to run some code every time a new subscription occurs.
Technique 1
Implementing your own subscription storage would give you access to the client address and messages types they are interested in.
Technique 2
public void Init()
{
IBus bus = NServiceBus.Configure.With()
.DefaultBuilder()
.Log4Net()
.XmlSerializer()
.MsmqTransport()
.DisableRavenInstall()
.UnicastBus()
.CreateBus()
.Start();
IUnicastBus ubus = bus as IUnicastBus;
if (null != ubus)
{
ubus.ClientSubscribed += (s, e) => { Console.WriteLine("Client Subscribed {0}:{1}", e.SubscriberReturnAddress.Machine, e.SubscriberReturnAddress.Queue); };
}
}

Resources