I have an azure notification hub built for Android. And I'm building for IOS.
These are the data I need to send in the notification, they are already sent to Android:
// Android payload
JObject data = new JObject();
data.Add("Id", notification.Id);
data.Add("Descricao", notification.Descricao);
data.Add("Tipo", notification.Tipo);
data.Add("Id_usuario", notification.Id_usuario);
//data.Add("Informacao", notification.Informacao);
data.Add("Informacao", notification.Informacao);
data.Add("Status", notification.Status);
How to put this data to push notifications for IOS?
var apnsNotification = "{\"aps\":{\"alert\":\"" + "Some Title"+": " + "\"}}";
This method works for me:
public static async void sendPushNotificationApns(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);
var apnsNotification = "{\"aps\":{\"alert\":\"" + notification.Descricao + "\"},\"Id\":\"" + notification.Id +
"\",\"Tipo\":\"" + notification.Tipo + "\",\"Id_usuario\":\"" + notification.Id_usuario +
"\",\"Informacao\":\"" + notification.Informacao +
"\",\"Status\":\"" + notification.Status + "\"}";
try
{
// Send the push notification and log the results.
String tag = "_UserId:" + notification.Id_usuario;
var result = await hub.SendAppleNativeNotificationAsync(apnsNotification, 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");
}
}
Related
I'm trying to send iOS push notifications, but the code I'm using is not working due to the events OnNotificationSucceeded and OnNotificationFailed are not triggered.
My code is:
string p12fileName = "path to my iOS push certificate";
string p12password = "my iOS push certificate password";
string deviceToken = "my device ID";
var appleCert = File.ReadAllBytes(p12fileName);
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, p12password);
config.ValidateServerCertificate = false;
var apnsBroker = new ApnsServiceBroker(config);
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle(ex => {
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Response.Write("Apple Notification Failed: ID={" + apnsNotification.Identifier + "}, Code={" + statusCode + "}");
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
Response.Write("Notification Failed for some unknown reason : {" + ex.InnerException + "}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) => {
LogDao.Info(deviceData.UserId, "Apple Notification Sent!");
};
SureAct.Helpers.LiteralsHelper literals = new SureAct.Helpers.LiteralsHelper(1, 0);
string message = "test";
apnsBroker.Start();
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse("{\"aps\":{\"alert\":\"" + message + "\",\"badge\":1,\"sound\":\"default\"}}")
});
apnsBroker.Stop();
I checked the certificate and password and they are correct. And If I try to send a push notification using the webpage pushtry.com I receive the push.
What I'm doing wrong? Why the events are not triggered?
Kind regards
I'm using EasyNetQ/RabbitMQ to connect a web application running in IIS to a Windows service. However, I don't seem to get the request/response to work. I pretty sure it's not a code problem but I'm running out of ideas where to look at next.
This is a test console application that works just perfectly:
static void Main()
{
var stopHandle = new ManualResetEventSlim();
var producer = new Thread(() =>
{
string cs = "host=localhost;virtualHost=/;username=demo;password=y4xHEyq3nQOd;timeout=120;persistentMessages=false;prefetchcount=1";
var bus = RabbitHutch.CreateBus(cs, x => x.Register<IEasyNetQLogger>(s => new EasyNetQ.Loggers.ConsoleLogger()));
while (!stopHandle.IsSet)
{
try
{
var result = bus.Request<AutomationRequest, AutomationResponse>(new AutomationRequest
{
taskId = "140061381555",
arguments = "type=pdf",
issueId = 97630548355,
});
Console.WriteLine("Result: " + result.status + ", " + result.status + ", " + result.downloadUrl);
}
catch (Exception)
{
Console.WriteLine("Failed");
}
if (!stopHandle.IsSet) Thread.Sleep(1000);
}
bus.Dispose();
});
producer.Start();
Console.ReadLine();
stopHandle.Set();
producer.Join();
}
}
This on the other hand is the same test code but as a web application:
namespace WebApplication2
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "host=localhost;virtualHost=/;username=demo;password=y4xHEyq3nQOd;timeout=120;persistentMessages=false;prefetchcount=1";
IBus bus = RabbitHutch.CreateBus(cs, x => x.Register<IEasyNetQLogger>(s => new EasyNetQ.Loggers.ConsoleLogger()));
try
{
var result = bus.Request<AutomationRequest, AutomationResponse>(new AutomationRequest
{
taskId = "140061381555",
arguments = "type=pdf",
issueId = 97630548355,
});
Console.WriteLine("Result: " + result.status + ", " + result.status + ", " + result.downloadUrl);
}
catch (Exception)
{
Console.WriteLine("Failed");
}
bus.Dispose();
}
}
}
Web application sends the message just fine, at queued and it's processed on the back end. Back-end provides the response with the correct correlationID and queues it. However, for some reason unknown to me, the Web application never gets the response.
The Web application eventually gets a timeout. However, the length of the timeout is not the problems, as the getting the response into the queue takes just about two seconds, and changing the timeout to two minutes on both sides does not make any difference.
Does somebody have a ready solution what to fix? Or any ideas where to look? I have googled everything I could figure out about EasyNetQ or RabbitMQ but I didn't even find anybody having reported about similar problems.
--karri
I have been using Azure Notification Hubs along with GCM to send notifications to the users of my app. This was all working great until I published the app to the Play Store.
Now it gives a 500 Server error whenever I try to post a notification. I have no idea why this error is happening. Perhaps the app is not picking up the RavenDB where the notifications are stored?
But it looks more like the service is not getting back users that are registered on the Hub. I really don't know... Any help would be so appreciated!
This is my stacktrace when run locally, it is the same but less detailed when published:
"Message": "An error has occurred.",
"ExceptionMessage": "Value cannot be null.\r\nParameter name: source",
"ExceptionType": "System.ArgumentNullException",
"StackTrace": " at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)\r\n
at AcademicAssistantService.Controllers.NotificationController.<GetRecipientNamesFromNotificationHub>d__8.MoveNext()
in C:\\Users\\Kenneth\\Documents\\College\\Semester 8\\AcademicAssistantService\\AcademicAssistantService\\Controllers\\NotificationController.cs:line 105
This is the Controller action:
// POST api/notification
public async Task<IHttpActionResult> Post([FromBody]Notification notification, String key)
{
var notificationToSave = new Notification
{
NotificationGuid = Guid.NewGuid().ToString(),
TimeStamp = DateTime.UtcNow,
Message = notification.Message,
SenderName = notification.SenderName
};
var recipientNames = await GetRecipientNamesFromNotificationHub(key);
var recipientNamesString = CreateCustomRecipientNamesString(recipientNames);
string notificationJsonPayload =
"{\"data\" : " +
" {" +
" \"message\": \"" + notificationToSave.Message + "\"," +
" \"senderName\": \"" + notificationToSave.SenderName + "\"," +
" \"recipientNames\": \"" + recipientNamesString + "\"" +
" }" +
"}";
if (key == null)
{
var result = await _hubClient.SendGcmNativeNotificationAsync(notificationJsonPayload);
notificationToSave.TrackingId = result.TrackingId;
notificationToSave.Recipients = recipientNames;
}
else
{
foreach (string r in recipientNames)
{
if ((r != notification.SenderName))
{
var result = await _hubClient.SendGcmNativeNotificationAsync(notificationJsonPayload, "user:" + r);
notificationToSave.TrackingId = result.TrackingId;
notificationToSave.Recipients = recipientNames;
}
}
}
await Session.StoreAsync(notificationToSave);
return Ok(notificationToSave);
}
To get names from hub:
public async Task<List<string>> GetRecipientNamesFromNotificationHub(String key)
{
var registrationDescriptions = await _hubClient.GetAllRegistrationsAsync(Int32.MaxValue);
var recipientNames = new List<String>();
foreach (var registration in registrationDescriptions)
{
if (registration is GcmRegistrationDescription)
{
var userName = registration.Tags
.Where(t => t.StartsWith("user"))
.Select(t => t.Split(':')[1].Replace("_", " "))
.FirstOrDefault();
userName = userName ?? "Unknown User";
Conversation convo = db.Conversations.Find(key);
foreach (User u in convo.Users)
{
if (u.Email == userName && !recipientNames.Contains(userName))
{
recipientNames.Add(userName);
}
}
}
}
return recipientNames;
}
Could you use Service Bus Explorer and verify indeed you have tags starts with "user". And I also see you are using GetAllRegistrationsAsync API, which is recommend to use only for debugging purpose. This is heavily throttled API.
Thanks,
Sateesh
I have created a simple Node.js Express service that basically uses child_process.exec to run a command (in this case, running the "nightwatch" command in the command prompt to run Nightwatch.js end to end tests), and then once the Nightwatch tests are done running, then reading the report results of the tests from a specific html file that Nightwatch outputs results to. The Express service then returns the html text to the .NET web app who made the request.
I'm running into an error where the Express service returns a 200 response prematurely after 120000 ms everytime the .net c# webapp makes a request to it.
Any idea why the express service returns a 200 response prematurely? I had thought it was a timeout issue, so I set a web request timeout in the .net web app, but still getting the same problem. Is it a problem with maybe having to set a timeout within the Express service itself?
Express service Code:
var exec = require('child_process').exec;
var fs = require('fs');
var Q = require('Q');
exports.runTests = function(req, res){
var environment = req.param('environment');
console.log('current environment to run nightwatch tests: ' + environment);
executeNightwatchCommand(environment)
return getReportResults(res).then(function(reportHtmlFormatted){
console.log('About to send back response of report html.');
res.send(reportHtmlFormatted);
});
};
var executeNightwatchCommand = function(environment){
//var nightwatchDirectory = 'C:/Nightwatch/Brightline.AcceptanceTesting';
var nightwatchDirectory = 'C:/code/project/brightline/tests/Brightline.AcceptanceTesting';
if(environment.toLowerCase() == 'local'){
environment = 'develop';
}
var cmd = 'cmd /c "cd /d ' + nightwatchDirectory + ' && nightwatch --env ' + environment + '"';
console.log("About to run Nightwatch tests.");
exec(cmd, function(error, stdout, stderr) {
if(error){
console.log("error: " + error);
}
// if(stdout){
// console.log("stdout: " + stdout);
// }
if(stderr){
console.log("stderr: " + stderr);
}
console.log("Finished running Nightwatch tests.");
});
}
var getReportResults = function(res, deferred){
var deferred = Q.defer();
//var reportPath = 'C:/Nightwatch/Brightline.AcceptanceTesting/reports_html/report.html';
var reportPath = 'C:/code/project/brightline/tests/Brightline.AcceptanceTesting/reports_html/report.html';
console.log('Setting up filesystem watch for report file: ' + reportPath);
fs.watch(reportPath, function(){
fs.readFile(reportPath, 'utf8', function (err,data) {
console.log('currently reading report file.');
if (err) {
console.log("error: " + err);
deferred.reject(new Error(err));
}
//remove style from report html so it doesn't override website styles
var reportHtml = data;
var reportHtmlFormatted = reportHtml.split('<style type="text/css">')[0] + reportHtml.split('</style>')[1];
console.log('About to resolve promise for reading report html.')
deferred.resolve(reportHtmlFormatted);
});
});
return deferred.promise;
}
.NET C# code that makes the request to the Express service:
string environment = null;
try
{
if (IoC.Settings.CurrentEnvironment == EnvironmentType.PRO)
environment = "production";
else if (IoC.Settings.CurrentEnvironment == EnvironmentType.UAT)
environment = "uat";
else if (IoC.Settings.CurrentEnvironment == EnvironmentType.DEV)
environment = "develop";
else
environment = "local";
var buildServerIp = ConfigurationManager.AppSettings["buildServerIp"];
var nightwatchServicePort = ConfigurationManager.AppSettings["nightwatchServicePort"];
//var requestUrl = string.Format("http://{0}:{1}/nightwatchTests?environment={2}", buildServerIp, nightwatchServicePort, environment);
var requestUrl = string.Format("http://{0}:{1}/nightwatchTests?environment={2}", "localhost", nightwatchServicePort, environment);
var request = WebRequest.Create(requestUrl);
request.Method = "GET";
request.Timeout = 1000000000;
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
var vm = new NightwatchTestsViewModel();
vm.html = text;
return JObject.FromObject(vm);
}
catch (Exception ex)
{
IoC.Log.Error("Could not retrieve Nightwatch test results.", ex);
FlashMessageExtensions.Debug(ex);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { ReasonPhrase = "Error processing request." });
}
From this post:
If you're using express, you can use the server.timeout functionality.
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000; //Timeout requests after 1 second
You should also consider not doing the long request and instead do a start/status pattern. This is much less likely to fail due to network issues.
I am android app developer .Now, I am developing app for windows phone . I am integrating push notification in windows phone first time by Azure notification Hub. I want help for notification Hub. How to integrate? How to send notification to selected device not to all?
I was integrated notification but after some time notification is stop. I have done with many notification hub credentials. Now notification is coming.
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
StorageFile MyDBFile = null;
try
{
// Read the db file from DB path
MyDBFile = await StorageFile.GetFileFromPathAsync(DB_PATH);
}
catch (FileNotFoundException)
{
if (MyDBFile == null)
{
// Copy file from installation folder to local folder.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri(DbConst.DATABASE, UriKind.Relative)).Stream)
{
// Create a stream for the new file in the local folder.
using (IsolatedStorageFileStream output = iso.CreateFile(DB_PATH))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to the local folder.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
}
var channel = HttpNotificationChannel.Find("MyPushChannel");
if (channel == null)
{
channel = new HttpNotificationChannel("MyPushChannel");
channel.Open();
channel.BindToShellToast();
}
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
{
//var hub = new NotificationHub("<hub name>", "<connection string>");
var hub = new NotificationHub("mnokhgjhjhjbohkjkl", "Endpoint=sb://connect-hub.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=RM6jjnbjnbjAnjhttD4yxqnknknklmkmnkkmkkkmmkbnl5rSk=");
Registration x= await hub.RegisterNativeAsync(args.ChannelUri.ToString());
//mChennelURI = x.ChannelUri;
Debug.WriteLine("Chennel URI: " + x.ChannelUri);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
System.Diagnostics.Debug.WriteLine(args.ChannelUri.ToString());
});
});
channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(async (o,args) =>
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Show the notification since toasts aren't
// displayed when the app is currently running.
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", args.ErrorType, args.Message, args.ErrorCode,args.ErrorAdditionalData));
});
});
// Handle the event that is raised when a toast is received.
channel.ShellToastNotificationReceived +=new EventHandler<NotificationEventArgs>((o, args) =>
{
string message = "";
foreach (string key in args.Collection.Keys)
{
message += args.Collection[key] + ": ";
}
//string[] separators = { "#"};
// string[] words = message.Split(separators, StringSplitOptions.RemoveEmptyEntries);
// string type = words[0];
// string title = words[1];
// string body = words[2];
// string attach = words[3];
//string date = words[4];
//string time = words[5];
//string msdId = words[6];
//string groupIDS = words[7];
//foreach (var word in words)
//Console.WriteLine(word);
Console.WriteLine("Push notification : " + message);
Debug.WriteLine("Push notification : " + message);
Debugger.Log(1, "Push", "Push notification : " + message);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Show the notification since toasts aren't
// displayed when the app is currently running.
MessageBox.Show(message);
//<Temp>
// DatabaseHelperClass dbHelper = new DatabaseHelperClass();
// dbHelper.Insert(new Msg(msdId, groupIDS, type, title, body, attach, date, time, Constants.NO));
//</Temp>
});
});
}