Continuous push message giving BadRequest from Azure - c#

My service is register with azzure notification hub. And using my .net server API it push notification to particular device within particular time frame.
Everything goes right except when I try to send multiple push in same code it stuck with "BadRequest" except first one.
Below is the code
public static async void SendAzzurePushNotification()
{
for (int i = 0; i < 10; i++)
{
HttpStatusCode pushNotificationStatus = await CreateAndPushAsync("user_37");
Console.WriteLine(pushNotificationStatus);
}
}
static async Task<HttpStatusCode> CreateAndPushAsync(string tag)
{
HttpStatusCode pushNotificationStatus = HttpStatusCode.NotImplemented;
try
{
HttpResponseMessage response = null;
string uri = "<HUBURI>";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("SharedAccessSignature", <SASTOKEN>);
client.DefaultRequestHeaders.Add("ServiceBusNotification-Format", "gcm");
client.DefaultRequestHeaders.Add("ServiceBusNotification-Tags", tag);
client.DefaultRequestHeaders.Add("x-ms-version", "2015-01");
response = await client.PostAsync(uri,
new StringContent("{\"data\":{\"message\":\"Notification Hub test notification\"}}", Encoding.UTF8, "application/json"));
pushNotificationStatus = response.StatusCode;
}
catch (Exception ex)
{
throw;
}
return pushNotificationStatus;
}
Above code give me Created status for first time and then BadRequest after that. If same api I call from client like postman. It work fine.
I also tried nuget package from azure notification hub, regarding which code is as below. Which solve my above issue but it won't return me any status code which I can have in my above code for success.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<CONNECTIONSTRING>", "<HUB>");
NotificationOutcome outcome = await hub.SendGcmNativeNotificationAsync("{\"data\":{\"message\":\"Notification Hub test notification\"}}", "user_37");

Call send method with your tags and your notification-data
private static readonly string Endpoint = #"Your End Point";
private static readonly string HubName = #"You Hub Name";
private static NotificationHubClient Hub { get { return NotificationHubClient.CreateClientFromConnectionString(Endpoint, HubName); } }
public static async Task Send(string[] tags, object data)
{
try
{
string payload = string.Empty;
string json_gcm = string.Empty;
if (data.GetType() != typeof(string))
{
//If your notification data is of type
payload = JsonConvert.SerializeObject(data);
json_gcm = "{ \"data\" : " + payload + "}";
}
else
{
//If your notification data is simply is in string
payload = Convert.ToString(data);
json_gcm = "{ \"data\" : {\"message\":\"" + payload + "\"}}";
}
// Android
NotificationOutcome gcmOutcome = null;
gcmOutcome = await Hub.SendGcmNativeNotificationAsync(json_gcm, tags);
if (gcmOutcome != null)
{
if (!((gcmOutcome.State == NotificationOutcomeState.Abandoned) || (gcmOutcome.State == NotificationOutcomeState.Unknown)))
{
//Do code when notification successfully send to Android
}
}
}
catch (Exception ex)
{
//Do code when any exception occurred while sending notification
}
}
NotificationOutcomeState: Gives you status code in the form of enum that represent your notification has been successfully sent or not.
You may ignore if-else block as your need.
Try once may it help you

Related

C# Twilio API: TwilioRestClient.GetFeedback has been deprecated. Need help finding an updated approach

Our c# application has been using an older version of Twilio for a while & now that Twilio version is scheduled to be deprecated next month. I updated our application to the latest version of Twilio.API and everything's working fine, with the exception of some code which returns the sms message response based on the message's sid.
Here's our old code. The line which reads: "var response = trc.GetFeedback(Sid);" is the problem.
This is deprecated & no longer viable in the updated version of twilio. Does anyone know of an updated approach to returning the sms message response based on the sid?:
public class SmsUtil
{
private readonly string twilioAuth = ConfigurationManager.AppSettings["Twilio_Auth"].ToString();
private readonly string twilioAuthToken = ConfigurationManager.AppSettings["Twilio_Auth_Token"].ToString();
private Twilio.TwilioRestClient trc;
public SmsUtil()
{
trc = new Twilio.TwilioRestClient(twilioAuth, twilioAuthToken);
}
public IAppResult GetStatus(String Sid)
{
IAppResult result = new AppResult();
try
{
var response = trc.GetFeedback(Sid);
result.Data = response;
result.Code = response.Issues.Count == 0 ? 0 : -1;
}
catch (Exception ex)
{
result.Code = -1;
result.Message = "Error - Sending Text";
result.Data = ex.Message;
}
return result;
}
}

Connection reset issue in .net core api call (net::ERR_CONNECTION_RESET 200 (OK))

I have a .net core API service which is called from a angular client project.
When a user request a status of his payment, we will make call to this service api and this service will then call a payment gateway service to fetch the status of payment and the output result will return to the user.
When i try to integrate this i am facing this below error.
net::ERR_CONNECTION_RESET 200 (OK)
core.js:5967 ERROR Unknown Error
This above issue is not showing when i try to hit the service after putting one breakpoint. Its also returning the result.
This is how entire flow works
Client side call performs by user
this.dataservice.postFeed(method, JSON.stringify(this.initsearch)).subscribe(result => {
var response = result.body["data"];
console.log(response);
});
Server side code looks like
[HttpPost]
public async Task<IActionResult> Post([FromBody] ObjectModel searchValue)
{
ApiResponse<string> response = new ApiResponse<string>();
IBaseResult<string> result = await _adlerBo.GetPaymentStatus(searchValue);
response.Success = result.success;
response.Data = result.Data;
return Ok(response);
}
In BusinessObject.cs
public async Task<IBaseResult<string>> GetPaymentStatus(PaymentSearchModel requestModel){
string apiResponse = await PaymentStatusCheckUsingAPI(requestModel.orderid);
return apiResponse ;
}
private async Task<string> PaymentStatusCheckUsingAPI(string orderNumber)
{
string message = await PostPaymentRequestToGateway(statusApiUrl, authQueryUrlParam);
NameValueCollection param = await GetResponseMap(message);
string status = "";
string encResJson = "";
if (param != null && param.Count == 2)
{
for (int i = 0; i < param.Count; i++)
{
if ("status".Equals(param.Keys[i]))
{
status = param[i];
}
if ("enc_response".Equals(param.Keys[i]))
{
encResJson = param[i];
}
}
if (!"".Equals(status) && status.Equals("0"))
{
resJson = crypto.Decrypt(encResJson, workingKey);
}
else if (!"".Equals(status) && status.Equals("1"))
{
Console.WriteLine("failure response: " + encResJson);
}
}
return resJson;
}
private async Task<string> PostPaymentRequestToGateway(string queryUrl, string urlParam)
{
string message = "";
try
{
StreamWriter myWriter = null;// it will open a http connection with provided url
WebRequest objRequest = WebRequest.Create(queryUrl);//send data using objxmlhttp object
objRequest.Method = "POST";
//objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(urlParam);//send data
myWriter.Close();//closed the myWriter object
// Getting Response
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
message = await sr.ReadToEndAsync();
//Response.Write(message);
}
}
catch (Exception exception)
{
Console.Write("Exception occured while connection." + exception);
}
return message;
}
private async Task<NameValueCollection> GetResponseMap(string message)
{
//await Task.Delay(2000); I did this with no Luck
NameValueCollection Params = new NameValueCollection();
if (message != null || !"".Equals(message))
{
string[] segments = message.Split('&');
foreach (string seg in segments)
{
string[] parts = seg.Split('=');
if (parts.Length > 0)
{
string Key = parts[0].Trim();
string Value = parts[1].Trim();
Params.Add(Key, Value);
}
}
}
return await Task.FromResult(Params);
}
Any idea how to fix this? Why its working when i put breakpoint and not otherwise.
Am i doing correct asynchronous implimentsion in my api?

How to get the hub notification that is not full?

I have a notification hub, and it, have a hub-namespace and it is almost full.
I'll create another hub, how do I programmatically know (Android), which one should I enter the user?
Android source code:
public class NotificationSettings {
public static String SenderId = "MyFirebaseSenderId";
public static String HubName = "myhub-hub";
public static String HubListenConnectionString = "Endpoint=sb://myapp.serv.../;SharedAccessKeyName=D..ure;SharedAccessKey=K..t/n8I/X..=";
}
RegistrationIntent:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private NotificationHub hub;
public RegistrationIntentService() {
super(TAG);
}
public ApplicationUtils getApplicationUtils() {
return (ApplicationUtils) getApplication();
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String resultString = null;
String regID = null;
String storedToken = null;
String tag = null;
try {
tag ="_UserId:" + getApplicationUtils().getUsuario().Id;
} catch (Exception e){
return;
}
try {
if(FirebaseInstanceId.getInstance() == null){
FirebaseApp.initializeApp(this);
}
String FCM_token = FirebaseInstanceId.getInstance().getToken();
SaveSharedPreferences.setFCM(getApplicationContext(),FCM_token);
Log.d(TAG, "FCM Registration Token: " + FCM_token);
// Storing the registration id that indicates whether the generated token has been
// sent to your server. If it is not stored, send the token to your server,
// otherwise your server should have already received the token.
if (((regID=sharedPreferences.getString("registrationID", null)) == null)){
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, this);
Log.d(TAG, "Attempting a new registration with NH using FCM token : " + FCM_token);
regID = hub.register(FCM_token, tag).getRegistrationId();
// If you want to use tags...
// Refer to : https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-routing-tag-expressions/
// regID = hub.register(token, "tag1,tag2").getRegistrationId();
resultString = "New NH Registration Successfully - RegId : " + regID;
Log.d(TAG, resultString);
sharedPreferences.edit().putString("registrationID", regID ).apply();
sharedPreferences.edit().putString("FCMtoken", FCM_token ).apply();
}
// Check if the token may have been compromised and needs refreshing.
else if (!((storedToken=sharedPreferences.getString("FCMtoken", "")).equals(FCM_token))) {
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, this);
Log.d(TAG, "NH Registration refreshing with token : " + FCM_token);
regID = hub.register(FCM_token, tag).getRegistrationId();
// If you want to use tags...
// Refer to : https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-routing-tag-expressions/
// regID = hub.register(token, "tag1,tag2").getRegistrationId();
resultString = "New NH Registration Successfully - RegId : " + regID;
Log.d(TAG, resultString);
sharedPreferences.edit().putString("registrationID", regID ).apply();
sharedPreferences.edit().putString("FCMtoken", FCM_token ).apply();
}
else {
resultString = "Previously Registered Successfully - RegId : " + regID;
}
} .............................................
Now, it follows my downend code below, I do not know if it would be important in this case. But, it is developed in C # .Net:
public static async void sendPushNotification(ApiController controller, DataObjects.Notification notification)
{
// Get the settings for the server project.
HttpConfiguration config = controller.Configuration;
MobileAppSettingsDictionary settings =
controller.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
// Get the Notification Hubs credentials for the Mobile App.
string notificationHubName = settings.NotificationHubName;
string notificationHubConnection = settings
.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
// Create a new Notification Hub client.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
// Android payload
JObject data = new JObject();
data.Add("Id", notification.Id);
data.Add("Descricao", notification.Descricao);
...
//alteração com a colocação da tag priority em caso de erro teste sem
var androidNotificationPayload = "{ \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
try
{
// Send the push notification and log the results.
String tag = "_UserId:"+notification.Id_usuario;
//var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload);
var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload, tag);
// Write the success result to the logs.
config.Services.GetTraceWriter().Info(result.State.ToString());
}
catch (System.Exception ex)
{
// Write the failure result to the logs.
config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
}
}
I need a lot of help on this issue.
Thank you so much for this.
According to your description, I suggest you could write a api method which will insert new user to the notification hub(not on the client side) after checking the registrations is full or not.
We could use NotificationHubClient.GetAllRegistrationsAsync Method to get all AllRegistrations to local. Then we could count its number.
After checking successfully, then we will check enter user to which hub.
The workflow is:
New user registered:
Client: Send the user information to server web api method
Server: Check the notification hub is full(By calling NotificationHubClient.GetAllRegistrationsAsync or directly registered user if it failed registered into new hub)
Besides, notification hub provides different pricing tier.
I suggest you could consider scaling up your pricing tier to support multiple active devices.

Authorization for Microsoft App ID xxx failed with status code Forbidden and reason phrase 'Forbidden'

My bot keeps failing on the following line of code with the error in Skype, WebChat, and FB chat. I've tried entering the MS App ID and password via the app settings and the web.config. This works fine in the emulator without any errors. When I ran remote debugging I found that this fails on Webchat, Skype, and FB messenger at this line of code:
await connector.Conversations.ReplyToActivityAsync(reply1);
My bot is integrated with SmartThings so the smart accessories are turning on and off as expected but the response back that should be returned in the chat seems to be failing. I've tried creating a new bot service app but it fails as well.
Update including all code:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Connector;
using System.Net.Http.Headers;
using System.Threading;
using Microsoft.IdentityModel.Protocols;
using System.Configuration;
namespace FirstBotApp
{
[BotAuthentication]
public class Switches
{
public string name { get; set; }
public string value { get; set; }
}
public class MessagesController : ApiController
{
static HttpClient client = new HttpClient();
static HttpResponseMessage responsemain = null;
static int j = 0;
static void ShowSwitches(Switches[] switches)
{
for (int i = switches.Length - 1; i >= 0; i--)
{
Console.WriteLine($"Name: {switches[i].name}\tPrice: {switches[i].value}\t");
}
return;
}
static async Task<Switches[]> GetSwitchesAsync(string path)
{
Switches[] switches = null;
responsemain = await client.GetAsync(path);
//Console.WriteLine(client.GetAsync(path));
//Console.WriteLine(response);
if (responsemain.IsSuccessStatusCode)
{
//Console.WriteLine($"Successful response: {response.StatusCode}");
var response1 = await client.GetStringAsync("");
Console.WriteLine($"{response1}");
switches = await responsemain.Content.ReadAsAsync<Switches[]>();
//JObject j = JObject.Parse(response1);
}
else Console.WriteLine($"Error in response: {responsemain.StatusCode}");
return switches;
}
static async Task<Switches> UpdateSwitchesAsync(Switches switches)
{
Console.WriteLine("Turning off the light");
HttpResponseMessage response = await client.PutAsJsonAsync($"switches/off?room=LivingRoom", switches);
response.EnsureSuccessStatusCode();
Console.WriteLine($"The response from the server was: {response.StatusCode}");
// Deserialize the updated switches from the response body.
switches = await response.Content.ReadAsAsync<Switches>();
Thread.Sleep(10000);
Console.WriteLine($"Turning on the light");
response = await client.PutAsJsonAsync($"switches/on?room=LivingRoom", switches);
Console.WriteLine($"The response from the server was: {response.StatusCode}");
Thread.Sleep(10000);
return switches;
}
static async Task<HttpStatusCode> DeleteSwitchesAsync(string id)
{
HttpResponseMessage response = await client.DeleteAsync($"api/switchess/{id}");
return response.StatusCode;
}
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
Switches[] switches = null;
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
//string appdId = AppSettings.Settings["MicrosoftAppId"];
//string appPassword = ConfigurationManager.AppSettings["MicrosoftAppPassword"];
if (j == 0)
{
//client.Timeout = TimeSpan.FromSeconds(4);
//Declaration of client and Switches variable
string accessToken = "xxxxx";
client.BaseAddress = new Uri("xxxxx");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
j++;
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Authorization", "Bearer " + accessToken);
}
if (activity.Type == ActivityTypes.Message)
{
//, appdId, appPassword);
//Switches switches = new Switches;
Activity reply1;// = activity.CreateReply($"breakpoint1");
//await connector.Conversations.ReplyToActivityAsync(reply1);
switch (activity.Text.ToLower())
{
case"turn on livingroom":
try
{
Console.WriteLine("Turning on the light");
responsemain = await client.PutAsJsonAsync($"switches/on?room=LivingRoom", switches);
responsemain.EnsureSuccessStatusCode();
//Console.WriteLine($"The response from the server was: {responsemain.StatusCode}");
// Deserialize the updated product from the response body.
switches = await responsemain.Content.ReadAsAsync<Switches[]>();
reply1 = activity.CreateReply($"Successfully turned on LivingRoom Light");
await connector.Conversations.ReplyToActivityAsync(reply1);
}
catch
{
reply1 = activity.CreateReply($"Error");
await connector.Conversations.ReplyToActivityAsync(reply1);
}
break;
case "turn off livingroom":
try
{
Console.WriteLine("Turning off the light");
responsemain = await client.PutAsJsonAsync($"switches/off?room=LivingRoom", switches);
responsemain.EnsureSuccessStatusCode();
Console.WriteLine($"The response from the server was: {responsemain.StatusCode}");
// Deserialize the updated product from the response body.
switches = await responsemain.Content.ReadAsAsync<Switches[]>();
reply1 = activity.CreateReply($"Successfully turned off LivingRoom Light");
await connector.Conversations.ReplyToActivityAsync(reply1);
}
catch
{
reply1 = activity.CreateReply($"Error");
await connector.Conversations.ReplyToActivityAsync(reply1);
}
break;
default: //"What lights are on?":
try
{
switches = await GetSwitchesAsync("");
//Console.WriteLine($"About to show the product");
ShowSwitches(switches);
//await connector.Conversations.ReplyToActivityAsync(switches[].ToString);
for (int i = switches.Length - 1; i >= 0; i--)
{
reply1 = activity.CreateReply($"Room: ");//{switches[i].name}\tStatus: {switches[i].value}\t");
responsemain.EnsureSuccessStatusCode();
await connector.Conversations.ReplyToActivityAsync(reply1);
}
break;
}
catch
{
}
break;
}
// calculate something for us to return
//int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
//Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
//await connector.Conversations.ReplyToActivityAsync(reply);
}
else
{
HandleSystemMessage(activity);
}
// var response = Request.CreateResponse(HttpStatusCode.OK);
return responsemain;
}
static Activity HandleSystemMessage(Activity message)
{
if (message.Type == ActivityTypes.DeleteUserData)
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
}
else if (message.Type == ActivityTypes.ContactRelationUpdate)
{
// Handle add/remove from contact lists
// Activity.From + Activity.Action represent what happened
}
else if (message.Type == ActivityTypes.Typing)
{
// Handle knowing tha the user is typing
}
else if (message.Type == ActivityTypes.Ping)
{
}
return null;
}``
//client.dispose();
}
}
I found the error after some additional troubleshooting with remote debugging. Based on #JimLewallen's response I looked closer at the "Credentials" portion of the connector object. The OAuthScope for version 3.0 of the Botframework (connector-> Credentials->OAuthScope in the locals of the remote debugger) was pointing to api.botframework.com/.default when it should have been pointing at "graph.microsoft.com/.default". When I created a new bot service application in Visual Studios using the bot template the OAuthScope showed the correct endpoint.
Incorrect Value:
OAuthScope "api.botframework.com/.default"
Correct Value: Image from the Remote Debugger showing the correct OAuthScope

Microsoft.Azure.NotificationHub - Async call in sync method

I currently have to provide a sync as async method in my API: Please find the code below. The only problem is that I don’t have a
sync method in the backend. I use Azure.NotificationHub client. That client has only *Async methods. Is my way reasonable?
public PushHubNotificationResult SendPushMessage(string userId, string message)
{
PushHubNotificationResult result = new PushHubNotificationResult();
try
{
result = SendPushMessageAsync(userId, message).GetAwaiter().GetResult();
} catch (Exception ex)
{
result.Status = PushHubNotificationResultType.Error;
result.Error = ex.Message;
result.Exception = ex;
}
return result;
}
public async Task<PushHubNotificationResult> SendPushMessageAsync(string userId, string message)
{
PushHubNotificationResult result = new PushHubNotificationResult();
// EnableTestSend see: https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-push-notification-fixer/#self-diagnose-tips
// Create a new Notification Hub client.
Microsoft.Azure.NotificationHubs.NotificationHubClient hub =
Microsoft.Azure.NotificationHubs.NotificationHubClient.CreateClientFromConnectionString(NotificationHub, NotificationHubName);
// Sending the message so that all template registrations that contain "messageParam"
// will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
Dictionary<string, string> templateParams = new Dictionary<string, string>();
templateParams["messageParam"] = message;
string userTag = "_UserId:" + userId; // That line sets the IMEI or SerialNo (WLAN only device) == userId to which the push message is sent
try
{
// Send the push notification and log the results.
NotificationOutcome outcome = await hub.SendTemplateNotificationAsync(templateParams, userTag);
result.Status = PushHubNotificationResultType.Success;
foreach (RegistrationResult hubResult in outcome.Results)
{
result.PushNotificationHub = hubResult.ApplicationPlatform;
result.RegistrationId = hubResult.RegistrationId;
result.Outcome = hubResult.Outcome;
}
}
catch (System.Exception ex)
{
result.Status = PushHubNotificationResultType.Error;
result.Error = ex.Message;
result.Exception = ex;
}
return result;
}
thanks for any advice,
Eric
If you want to use sync-over-async, it's very important that you use ConfigureAwait(false) in your async code, otherwise you are very likely to get a deadlock.
NotificationOutcome outcome =
await hub.SendTemplateNotificationAsync(templateParams, userTag).ConfigureAwait(false);
The async method already converts exceptions to PushHubNotificationResultType.Error, why does the sync version do it too?

Categories