How to get data from push notification? - windows-phone-8

I'm sending push notification using azure notification hub by node js script. I can send and receive push notification. I don't know how to retrieve data. I'm sending push as follows:-
function sendNotifications(pushMessage) {
console.log('inside sendNotifications');
var hub = azure.createNotificationHubService('hubname','connection string');
hub.mpns.sendToast(
null,
{
text1: pushMessage,
text2: 'some data'
},
function (error)
{
if (!error)
{
//message send successfully
console.log("mpns.sendToast push success: "+error);
RESPONSE.send(statusCodes.OK, { ResponseMessage : 'mpns.sendToast message success' });
}
else
{
// msg failed to send
console.log("errro error.shouldDeleteChannel: "+error);
RESPONSE.send(statusCodes.OK, { ResponseMessage :'mpns.sendToast message error '+error });
}
});
}
I would like to receive the text1 and text2 in my receiving application. Could you inform me how to do it? Or do I need to send push notification differently if I want to push some data? How to push data together with push nitrification? Also how large data I can push?

If your app is already open when the toast notification is received, the following event handler can get the parameters of the notification (for example e.Collection[wp:Text1] will return the title of the toast) :
void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Keys)
{
message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);
if (string.Compare(
key,
"wp:Param",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{
relativeUri = e.Collection[key];
}
}
// Display a dialog of all the fields in the toast.
Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString()));
}
If your app is opened by clicking the toast notification, you can implement the following method in the page where your app is opened. You can access the parameters passed in the query string of the wp:Param parameter of the toast notification. I'm not sure how to get Text1 and Text2 in this method.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// If we navigated to this page
// from the MainPage, the DefaultTitle parameter will be "FromMain". If we navigated here
// when the secondary Tile was tapped, the parameter will be "FromTile".
textBlockFrom.Text = "Navigated here from " + this.NavigationContext.QueryString["NavigatedFrom"];
}
Code samples were taken from here.

Related

How to call a get REST API from a tvOS Application using Xamarin?

I am trying to call a get REST API from my tvOS application. Following is my code when tap the Button:
async void ButtonClicked(UIButton sender)
{
try
{
HttpClient client = new HttpClient();
var response = await client.GetAsync("rest api url");
if (response.IsSuccessStatusCode)
{
var Response = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
if (!string.IsNullOrWhiteSpace(Response.ToString()))
{
var category = JsonConvert.DeserializeObject<Videos>(Response.ToString());
Debug.WriteLine("count:>>" + category.webContentCategoryList.Count);
}
}
}
catch(Exception e)
{
Debug.WriteLine("Exception:>>"+e);
}
I have installed the system.net.http and newtonsoft.json nuget packages. But when I run the project the application showing Main.cs file like below screenshot:
Am I missing something in this?
UPDATE
I have added breakpoint for the first line inside ButtonClicked function. When I taps the Button, the application showing Main.cs file like above screenshot. It is not hitting the first line of ButtonClicked function.
So the issue is something else, I am not an expert in tvOS applications so I can't figure out. I have uploaded a sample project here.
I have fixed this issue by separating the service call on a new function like below, new function is the async method:
partial void ButtonClicked(UIButton sender)
{
LoadData();
}
async void LoadData()
{
HttpClient client = new HttpClient();
var response = await client.GetAsync("service url");
if (response.IsSuccessStatusCode)
{
var Response = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
if (!string.IsNullOrWhiteSpace(Response.ToString()))
{
var category = JsonConvert.DeserializeObject<Videos>(Response.ToString());
Debug.WriteLine("count:>>" + category.Count);
}
}
}
My XF Thread is here for more details.

ProgressEvent.load is always the same as ProgressEvent.Total which causes the progress to fake

I'm trying to implement progress bar on a website.
The Problem:
ProgressEvent.load is always the same as ProgressEvent.Total which prevent the progress to show the real state of the upload. At the first second the xhr request does sent it looks like it finished but actually the server is still getting parts of the file.
JS:
My js code(the part of the progress) looks like that:
xhr.upload.onprogress = function (event) {
var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
that._onProgressItem(item, progress);
};
the property lengthComputable is true.
the event.loaded is 4354707 as the event.total which is 4354707.
C# Server Side:
public async Task<FileResultViewModel> Upload(string type)
{
string ServerUploadFoler = "...";
// Verify that this is an HTML Form file upload request
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
// Create a stream provider for setting up output streams
var streamProvider = new MultipartFormDataStreamProvider(ServerUploadFolder);
// Read the MIME multipart asynchronously content using the stream provider we just created.
await Request.Content.ReadAsMultipartAsync(streamProvider);
string guid = String.Empty;
if (serverUploadMoveFolder != ServerUploadFolder)
{
foreach (MultipartFileData fileData in streamProvider.FileData)
{
guid = Guid.NewGuid().ToString();
string newFileName = serverUploadMoveFolder + guid + GetExtension(uploadType);
FileInfo fi = new FileInfo(fileData.LocalFileName);
fi.MoveTo(newFileName);
}
}
// Create response
return new FileResultViewModel
{
FileName = guid
};
}
Chrome debug after 1 second of upload with a file of 4.2MB:
In fiddler after the request has completed:
My questions are:
How does the browser knows the loaded size? How does it split the file to parts and based on what params?
How do the xhr.upload.onprogress function event get updated with the progress? Does it the server which report about his progress and if it is so where is it on the code because I didn't handle it.
Why doesn't the loaded property show the real size of part?

How catch (or know about) chrome.runtime.sendMessage Port Error?

When I try to send a message to another extension, occasionally I might have an invalid id (the extension may have been removed), but sendMessage does not ever notify me of this. As far as I can tell, it just prints to console.error:
This is miscellaneous_bindings Line 235 of Chrome's source code:
chromeHidden.Port.dispatchOnDisconnect = function( portId, errorMessage)
{
var port = ports[portId];
if (port) {
// Update the renderer's port bookkeeping, without notifying the browser.
CloseChannel(portId, false);
if (errorMessage) {
lastError.set(errorMessage, chrome);
//It prints: Port error: Could not establish connection. Receiving end does not exist.
console.error("Port error: " + errorMessage);
}
try {
port.onDisconnect.dispatch(port);
} finally {
port.destroy_();
lastError.clear(chrome);
}
}
};
As a result, my app is left trying over and over to send a message. The only hint I have is an empty response send back from sendResponse(), but any app can send an empty response object! How do I know it failed?
In the callback of sendResponse, look at the chrome.runtime.lastError property.
chrome.runtime.sendMessage("ID of extension", "message", function(response) {
var lastError = chrome.runtime.lastError;
if (lastError) {
console.log(lastError.message);
// 'Could not establish connection. Receiving end does not exist.'
return;
}
// Success, do something with response...
});

Message Dialog in Windows Store WITHOUT Async?

So, I'm porting an app over to Windows Store. At the start of the app, I have some code, that asks a question. I DO NOT WANT THE REST OF MY CODE TO FIRE UNTIL I GET A RESPONSE.
I have this:
string message = "Yadda Yadda Yadda";
MessageDialog msgBox = new MessageDialog(message, "Debug Trial");
msgBox.Commands.Add(new UICommand("OK",
(command) => { curSettings.IsTrial = true; }));
msgBox.Commands.Add(new UICommand("Cancel",
(command) => { curSettings.IsTrial = false; }));
await msgBox.ShowAsync();
//... more code that needs the IsTrial value set BEFORE it can run...
When I run the app, the code after the msgBox.ShowAsync() runs, without the correct value being set. It's only after the method finishes that the user sees the Dialog box.
I would like this to work more like a prompt, where the program WAITS for the user to click BEFORE continuing the method. How do I do that?
MessageDialog does not have a non-asynchronous method for "Show." If you want to wait for the response from the dialog before proceeding, you can simply use the await keyword.
Here also is a quickstart guide for asynchronous programming in Windows Store Apps.
I see that your code sample already uses "await". You must also mark the calling function as "async" in order for it to work properly.
Example:
private async void Button1_Click(object sender, RoutedEventArgs e)
{
MessageDialog md = new MessageDialog("This is a MessageDialog", "Title");
bool? result = null;
md.Commands.Add(
new UICommand("OK", new UICommandInvokedHandler((cmd) => result = true)));
md.Commands.Add(
new UICommand("Cancel", new UICommandInvokedHandler((cmd) => result = false)));
await md.ShowAsync();
if (result == true)
{
// do something
}
}

subscribeToPullNotifications doesn't detect new emails in inbox

i am trying to detect new emails in inbox using subscribeToPullNotifications as follows:
PullSubscription subscription = service.subscribeToPullNotifications(
folder, 1, null, EventType.NewMail);
GetEventsResults events = subscription.getEvents();
System.out.println("####### EVENTS: "
+ events.getItemEvents().toString());
for (ItemEvent itemEvent : events.getItemEvents()) {
if (itemEvent.getEventType() == EventType.NewMail) {
EmailMessage message = EmailMessage.bind(service,
itemEvent.getItemId());
System.out.println("######## NEW EMAIL MESSAGE IS: "
+ message.getSubject());
}
}
but the events.getItemEvents() is always empty, even i can see new emails in the inbox.
also how to make the above code is always repeated while the application is running, so that each minute it check for new emails.
Here it depends on when you are calling this, if suppose you are calling this as particular interval then you need to pass "WaterMark" of previous response in new request, else all events which occurred in between would be lost.
method : subscription.getWaterMark()
need to pass this as thrid argument to method subscribeToPullNotifications()
else you can continously pull on the same service by placing that in loop :
while (true) {
GetEventsResults events = null;
try {
events = subscription.getEvents();
} catch (Exception e1) {
e1.printStackTrace();
}
for (ItemEvent itemEvent : events.getItemEvents()) {
// do something...
}
}
But this would continuously pull from server increasing load, so rather use first approach by subscribing at regular interval, and passing previous water-mark in request.