Notification Hub RegistrationAuthorizationException - azure

I followed this link yesterday to receive notification from azure notification hub on my windows 8.1 phone app and it was working but
But today it is throwing me this error
An exception of type 'Microsoft.WindowsAzure.Messaging.RegistrationAuthorizationException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: HTTP request failed.
HTTP Details:
Status: 401
Reason: Unauthorized
Full content: <Error><Code>401</Code><Detail>ExpiredToken: .TrackingId:e27f22fb-5c9c-4028-8594-eacb71e5a35e_G1,TimeStamp:4/14/2016 10:29:33 AM</Detail></Error>
It is throwing this exception in the InitNotificationsAsync method in my App.xaml.cs when my app is trying to register
private async void InitNotificationsAsync()
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
var hub = new NotificationHub("nameofhub", "myconnectionstring");
var result = await hub.RegisterNativeAsync(channel.Uri);
//Displays the registration ID so you know it was successful
if (result.RegistrationId != null)
{
var dialog = new MessageDialog("Registration successful: " + result.RegistrationId);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
}
}

Do you try it in the emulator or..?
It can be the time syncronization.
If that is the emulator, can you check the time and set it up manually?

Related

MSFT Echo Bot modified for proactive messages throws exception non-existent Teams Connector v1.0.0

I have a simple Microsoft Bot where their EchoBot was modified to send proactive messages.
The problem I face is that the Bot depends on the Teams Connector v0.9.0 (latest stable), but when the Bot gets a POST request to its API endpoint, it throws a FileNotFoundException complaining that Teams Connector v1.0.0 is not found.
One problem is that MSFT does not have a v1.0.0 teams connector and furthermore the project was configured for a v0.9.0 dependency.
Does anyone know how I can fix this? I tried publishing from both VS2019 Community on Windows and Mac and get the same result.
Here's the POST endpoint I added to the basic MSFT EchoBot template
[Route("api")]
[HttpPost]
public async Task<IActionResult> Post([FromBody] WebServicePrompt prompt)
{
var message = Activity.CreateMessageActivity();
message.Text = "Hello!";
var conversationParameters = new ConversationParameters
{
IsGroup = true,
ChannelData = new TeamsChannelData
{
Channel = new ChannelInfo(prompt.ChannelId),
},
Activity = (Activity)message
};
var serviceUrl = "https://smba.trafficmanager.net/amer/";
MicrosoftAppCredentials.TrustServiceUrl(serviceUrl, DateTime.Now.AddDays(7));
var account = new MicrosoftAppCredentials("X", "Y");
var connectorClient = new ConnectorClient(new Uri(serviceUrl), account);
var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);
// Let the caller know proactive messages have been sent
return new ContentResult()
{
Content = $"Channel ID {prompt.ChannelId}, Response: {response.ToString()}",
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
};
}
Expected Behavior: MSFT Azure should have identified and found the v0.9.0 dependency. No exception should be thrown and the response should be HTTP 200.
Project Dependencies
Exception Message

Microsoft Bot Framework - Call from Azure app service to external Web API

I had a Microsoft Bot Framework project that connect to Web API(that not hosted in azure).
in local host everything was work fine. but when i was deployed the Bot to an Azure app service. it's seem that the call is failed(and the Bot not return any response).
this is my post request:
public static string Post(List<ActionInputParams> data, string url)
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json;charset=utf-8";
try
{
var res = wc.UploadString(url, "POST", JsonConvert.SerializeObject(data));
return res;
}
catch (Exception ex)
{
return "error " + ex.Message;
}
}
}
my question: there is a problem to call to external Web API from Azure app service? or i just missing something?
in the "log stream" i getting a 500 error:
HTTP Error 500.0 - Internal Server Error
The page cannot be displayed because an internal server error has occurred.

Azure service bus message delivery count is not increasing or is reset when topic subscription disabling/enabling

I have the following workflow:
Service bus receives messages.
Azure function triggers and tries to deliver this messages via HTTP to some service.
If delivery failed - function throws exception (custom) and disables topic subscription via code below:
The other function in parallel pings special health check endpoint of the service, and if it gets 200 - it tries to enable subscription and make the flow work again.
The steps could be reproduced N times, cause health check will return 200, thus the delivery url of point 2 - 4xx code.
After the next attempt to enable subscription and deliver the message, I expect that delivery count will be increased and in the end (after 10 deliveries attempt) it will get to dead-letter.
Actual - it equals 1.
I assume, that it may reset when I call CreateOrUpdate with status changed.
If yes - what is the other way to manage subscription status instead of Microsoft.Azure.Management package so that the messages delivery count will not be reset?
UPDATE: Function code
public static class ESBTESTSubscriptionTrigger
{
private static readonly HttpClient Client = new HttpClient();
private static IDatabase redisCache;
[FunctionName("ESBTESTSubscriptionTrigger")]
[Singleton]
public static async Task Run([ServiceBusTrigger("Notifications", "ESBTEST", AccessRights.Listen, Connection = "NotificationsBusConnectionString")]BrokeredMessage serviceBusMessage, TraceWriter log, [Inject]IKeyVaultSecretsManager keyVaultSecretsManager)
{
var logicAppUrl = await keyVaultSecretsManager.GetSecretAsync("NotificationsLogicAppUrl");
if (redisCache == null)
{
redisCache = RedisCacheConnectionManager.GetRedisCacheConnection(
keyVaultSecretsManager.GetSecretAsync("RedisCacheConnectionString").GetAwaiter().GetResult());
}
if (string.IsNullOrWhiteSpace(logicAppUrl))
{
log.Error("Logic App URL should be provided in Application settings of function App.");
throw new ParameterIsMissingException("Logic App URL should be provided in Application settings of function App.");
}
var applicaitonId = serviceBusMessage.Properties["applicationId"].ToString();
var eventName = serviceBusMessage.Properties.ContainsKey("Event-Name") ? serviceBusMessage.Properties["Event-Name"].ToString() : string.Empty;
if (string.IsNullOrWhiteSpace(applicaitonId))
{
log.Error("ApplicationId should be present in service bus message properties.");
throw new ParameterIsMissingException("Application id is missing in service bus message.");
}
Stream stream = serviceBusMessage.GetBody<Stream>();
StreamReader reader = new StreamReader(stream);
string s = reader.ReadToEnd();
var content = new StringContent(s, Encoding.UTF8, "application/json");
content.Headers.Add("ApplicationId", applicaitonId);
HttpResponseMessage response;
try
{
response = await Client.PostAsync(logicAppUrl, content);
}
catch (HttpRequestException e)
{
log.Error($"Logic App responded with {e.Message}");
throw new LogicAppBadRequestException($"Logic App responded with {e.Message}", e);
}
if (!response.IsSuccessStatusCode)
{
log.Error($"Logic App responded with {response.StatusCode}");
var serviceBusSubscriptionsSwitcherUrl = await keyVaultSecretsManager.GetSecretAsync("ServiceBusTopicSubscriptionSwitcherUri");
var sbSubscriptionSwitcherResponse = await Client.SendAsync(
new HttpRequestMessage(HttpMethod.Post, serviceBusSubscriptionsSwitcherUrl)
{
Content =
new
StringContent(
$"{{\"Action\":\"Disable\",\"SubscriptionName\":\"{applicaitonId}\"}}",
Encoding.UTF8,
"application/json")
});
if (sbSubscriptionSwitcherResponse.IsSuccessStatusCode == false)
{
throw new FunctionNotAvailableException($"ServiceBusTopicSubscriptionSwitcher responded with {sbSubscriptionSwitcherResponse.StatusCode}");
}
throw new LogicAppBadRequestException($"Logic App responded with {response.StatusCode}");
}
if (!string.IsNullOrWhiteSpace(eventName))
{
redisCache.KeyDelete($"{applicaitonId}{eventName}DeliveryErrorEmailSent");
}
}
}

IOT hub not recieving or sending messages

Iam trying to make a simple app for my raspberry pi that will send a message to the IOThub and then try to receive a response however nothing is happening.
I copied the connectionstring from the device controller. Ofcource I hidden it for this question.
I see it printing out that the message was succesfully sended to the iothub but when I check the iothub I see 0 received messages.
Iam using the free tier of the iothub is this a limitation?
public sealed partial class MainPage : Page
{
private const string DeviceConnectionString = "Hidden";
private readonly DeviceClient _deviceClient;
public MainPage()
{
this.InitializeComponent();
_deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Amqp); //Already tried using different transport types but no succes.
}
public async Task SendEvent()
{
Debug.WriteLine("\t{0}> Sending message", DateTime.Now.ToLocalTime());
var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message."));
await _deviceClient.SendEventAsync(commandMessage);
Debug.WriteLine("Succesfully sended message to IotHub");
}
public async Task ReceiveCommands()
{
Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n");
while (true)
{
var receivedMessage = await _deviceClient.ReceiveAsync();
if (receivedMessage != null)
{
var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);
var propCount = 0;
foreach (var prop in receivedMessage.Properties)
{
Debug.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value);
}
await _deviceClient.CompleteAsync(receivedMessage);
Debug.WriteLine("Finishing recieving message");
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
private async void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Debug.WriteLine("Sending event");
await SendEvent();
await ReceiveCommands();
Debug.WriteLine("Received commands");
}
}
It is nothing to do with free tier of the iothub. There is no such limitation.
You can't receive Device-To-Cloud(D2C) messages using DeviceClient that you used in ReceiveCommands(). It is by designed. You look like having some misunderstanding of Azure IoT Hub message types and SDKs.
There are two kinds of message types: Device-To-Cloud(D2C) message and Cloud-To-Device(C2D) message.
And two kinds of SDKs: device SDK and service SDK.
Device SDK is used to connect to and send D2C messages to Azure IoT Hub.
While service SDK is used to manage and send C2D messages to devices.
So, if you send C2D messages to device in Device Explorer you will receive these messages in your ReceiveCommands method.
If you want to receive D2C message you can utilize Event Hub-compatible endpoint(messages/events). Here is a console sample you can reference. But this is can't be done in UWP due to service bus not supported in UWP.

An error occurred creating push for user scripts: azure.notificationHubService could not be created

In Azure Mobile Service javascript backend ,trying to send a notification by calling notification hub through custom api. Its giving me a notification , but everytime giving a time out error too. I observed my logs and its showing "An error occurred creating push for user scripts: azure.notificationHubService could not be created" .
Instead of using azure.createNotificationHubService method , is there any way to import already created notification hub service ?How to get rid of the time out error. I am pasting function below.
function sendnotification() {
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('disapphub','Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=my_key_here=;');
var payload = {
data: {
"type":"newthread",
}
};
var mytags ='admin';
notificationHubService.gcm.send(mytags, payload, function(error){
if(!error){
//notification sent
}
});
}

Resources