WP8 - Scheduled Task Agent for push notifications - windows-phone-8

I'm trying to interface my app with push notifications and the backend developer choose Pusher as notifications provider.
.NET SDK is very messy, untidy and synchronous, which it does not work on WP8, so I rewrote its and it works fine now.
The question is: is a Scheduled Task required for fetch the push notifications and update the tile/toast? Or there are any best method?
I can't change push provider sadly.

You can simply send Tile and Toast push notifications to the phone and they will work even if your app is not running. You do not need background task for that.
Here is sample code that I use in a desktop application to send push notifications to a Windows Phone 8.0:
const String toastTemplate =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>{0}</wp:Text1>" +
"<wp:Text2>{1}</wp:Text2>" +
"<wp:Param>{2}</wp:Param>" +
"</wp:Toast>" +
"</wp:Notification>";
String message = String.Format(toastTemplate, "Test", "updated: " + DateTime.Now.ToString(), "/Pages/SyncPage.xaml");
Status = await PushNotifiactionsManager.SendNotification(cfg.PushNotificationUri, message, 2);
public static async Task<string> SendNotification(string pushNotificationUri, string message, short notificationClass)
{
String responseText;
if (message.Length > 3072)
{
responseText = String.Format("The message must be <= 3072 bytes: {0}", message);
}
else
{
HttpClient request = new HttpClient();
// Add message headers.
request.DefaultRequestHeaders.Add("X-MessageID", Guid.NewGuid().ToString());
request.DefaultRequestHeaders.Add("X-NotificationClass", notificationClass.ToString());
if (notificationClass == 1)
{
request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "token");
}
else if (notificationClass == 2)
{
request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "toast");
}
try
{
// Send the message, and wait for the response.
HttpResponseMessage response = await request.PostAsync(pushNotificationUri, new StringContent(message));
IEnumerable<string> values;
String connectionStatus = String.Empty;
if (response.Headers.TryGetValues("X-DeviceConnectionStatus", out values))
{
connectionStatus = values.First();
}
String subscriptionStatus = String.Empty;
if (response.Headers.TryGetValues("X-SubscriptionStatus", out values))
{
subscriptionStatus = values.First();
}
String notificationStatus = String.Empty;
if (response.Headers.TryGetValues("X-NotificationStatus", out values))
{
notificationStatus = values.First();
}
responseText = String.Format("{0}: {1}, {2}, {3}, {4}",
notificationClass == 1 ? "Tile" :
notificationClass == 2 ? "Toast" : "Raw",
response.StatusCode,
connectionStatus, subscriptionStatus, notificationStatus);
}
catch (WebException ex)
{
responseText = ex.Message;
}
}
return "Notification response: " + responseText;
}

Related

Azure Stream Analytics Error : Could not deserialize the input event(s) from IOT hub

I have created the Stream Analytics job to read data from IOT hub as input and and to store data to SQL DB.
Here are the some important input details configured for Steam Analytics job are
Event Serialization format: JSON
Encoding :utf-8
The message is sent to IOT Hub from Dotnet simulated code.
When I am running my job I am getting the following error:
Could not deserialize the input event as Json. Some possible reasons:
1) Malformed events
2) Input source configured with incorrect serialization format
And here is the my dotnet code.
private static async void ReceiveC2dAsync()
{
Console.WriteLine("\nReceiving cloud to device messages from service");
while (true)
{
Message receivedMessage = await deviceClient.ReceiveAsync();
if (receivedMessage == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received message: {0}", Encoding.ASCII.GetString(receivedMessage.GetBytes()));
Console.ResetColor();
await deviceClient.CompleteAsync(receivedMessage);
}
}
private static async void SendDeviceToCloudMessagesAsync()
{
double minTemperature = 20;
double minHumidity = 60;
int messageId = 1;
Random rand = new Random();
while (true)
{
double currentTemperature = minTemperature + rand.NextDouble() * 15;
double currentHumidity = minHumidity + rand.NextDouble() * 20;
var telemetryDataPoint = new
{
messageId = messageId++,
deviceId = "myFirstDevice",
temperature = currentTemperature,
humidity = currentHumidity
};
var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
string levelValue;
string temperatureAlert = "false";
if (rand.NextDouble() > 0.7)
{
if (rand.NextDouble() > 0.5)
{
messageString = "This is a critical message";
levelValue = "critical";
}
else
{
messageString = "This is a storage message";
levelValue = "storage";
}
}
else
{
levelValue = "normal";
}
if(currentTemperature > 30)
{
temperatureAlert = "true";
}
var message = new Message(Encoding.UTF8.GetBytes(messageString));
message.Properties.Add("level", levelValue);
message.Properties.Add("temperatureAlert", temperatureAlert);
await deviceClient.SendEventAsync(message);
Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
await Task.Delay(1000);
}
}
it looks like your simulated device generated non-json formatted messages such as "This is a critical message" and "This is a storage message".
Basically, you have two choices to fix this issue:
1. comment this part in the simulated code or
2. add the filter in the Azure IoT Hub Routes for these messages

POST data to web service HttpWebRequest Windows Phone 8

I've been trying without success today to adapt this example to POST data instead of the example GET that is provided.
http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx
I've replaced the line:
request.Method = HttpMethod.Get;
With
request.Method = HttpMethod.Post;
But can find no Method that will allow me to stream in the content I wish to POST.
This HttpWebRequest seems a lot cleaner than other ways e.g. sending delegate functions to handle the response.
In Mr Wigley's example code I can see POST so it must be possible
public static class HttpMethod
{
public static string Head { get { return "HEAD"; } }
public static string Post { get { return "POST"; } }
I wrote this class some time ago
public class JsonSend<I, O>
{
bool _parseOutput;
bool _throwExceptionOnFailure;
public JsonSend()
: this(true,true)
{
}
public JsonSend(bool parseOutput, bool throwExceptionOnFailure)
{
_parseOutput = parseOutput;
_throwExceptionOnFailure = throwExceptionOnFailure;
}
public async Task<O> DoPostRequest(string url, I input)
{
var client = new HttpClient();
CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName);
var uri = new Uri(string.Format(
url,
"action",
"post",
DateTime.Now.Ticks
));
string serialized = JsonConvert.SerializeObject(input);
StringContent stringContent = new StringContent(
serialized,
Encoding.UTF8,
"application/json");
var response = client.PostAsync(uri, stringContent);
HttpResponseMessage x = await response;
HttpContent requestContent = x.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure)
{
throw new Exception(url + " with POST ends with status code " + x.StatusCode + " and content " + jsonContent);
}
if (_parseOutput == false){
return default(O);
}
return JsonConvert.DeserializeObject<O>(jsonContent);
}
public async Task<O> DoPutRequest(string url, I input)
{
var client = new HttpClient();
CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName);
var uri = new Uri(string.Format(
url,
"action",
"put",
DateTime.Now.Ticks
));
string serializedObject = JsonConvert.SerializeObject(input);
var response = client.PutAsync(uri,
new StringContent(
serializedObject,
Encoding.UTF8,
"application/json"));
HttpResponseMessage x = await response;
HttpContent requestContent = x.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure)
{
throw new Exception(url + " with PUT ends with status code " + x.StatusCode + " and content " + jsonContent);
}
if (_parseOutput == false){
return default(O);
}
return JsonConvert.DeserializeObject<O>(jsonContent);
}
}
Then when I want to call it, I can use it as following :
JsonSend<User, RegistrationReceived> register = new JsonSend<User, RegistrationReceived>();
RegistrationReceived responseUser = await register.DoPostRequest("http://myurl", user);

Http post call in windows phone 8

I'm new to windows phone 8 development.
Could you please help me how to send the xml data to the server through http post calls in windows phone 8?
Thanks
This is a sample code I used in my project. Modify according to your needs
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url to submit to");
req.Method = "POST";
//Add a Header something like this
//req.Headers["SOAPAction"] = "http://asp.net/ApplicationServices/v200/AuthenticationService/Login";
req.ContentType = "text/xml; charset=utf-8";
//req.UserAgent = "PHP-SOAP/5.2.6";
string xmlData = #"<?xml version=""1.0"" encoding=""UTF-8""?>Your xml data";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(xmlData);
req.Headers[HttpRequestHeader.ContentLength] = byteArray.Length.ToString();
req.BeginGetRequestStream(ar =>
{
using (var requestStream = req.EndGetRequestStream(ar))
{
// Write the body of your request here
requestStream.Write(byteArray, 0, xmlData.Length);
}
req.BeginGetResponse(a =>
{
try
{
var response = req.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var streamRead = new StreamReader(responseStream))
{
// Parse the response message here
string responseString = streamRead.ReadToEnd();
//If response is also XML document, parse it like this
XDocument xdoc = XDocument.Parse(responseString);
string result = xdoc.Root.Value;
if (result == "true")
{
//Do something here
}
else
Dispatcher.BeginInvoke(() =>
{
//result failed
MessageBox.Show("Some error msg");
});
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
//if any unexpected exception occurs, show the exception message
MessageBox.Show(ex.Message);
});
}
}, null);
}, null);

Fetch raw e-mail text with EWS (headers, body and encoded attachments)

Is there a way to fetch the raw email text using EWS?
I would like to get the whole text including headers, body, and encoded attachments.
Is this possible?
I don't know if this is what you are looking for, but it should help.
It downloads the entire message file, including encoded attachments, header, subject, sender, receiver, etc...
try this:
static void Main(string[] args)
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new NetworkCredential("USR", "PWD", "Domain");
service.AutodiscoverUrl("someone#example.com");
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
Console.WriteLine("Found : " + findResults.TotalCount + " messages");
foreach (EmailMessage message in findResults.Items)
{
try
{
message.Load(new PropertySet(ItemSchema.MimeContent));
MimeContent mc = message.MimeContent;
// I use this format to rename messages files, you can do whatever you want
string n = string.Format("-{0:yyyy-MM-dd_HH-mm-ss-ffff}.eml", DateTime.Now);
string path = #"C:\folder\message" + n;
FileStream fs = new FileStream(path, FileMode.Create);
fs.Write(mc.Content, 0, mc.Content.Length);
fs.Flush();
fs.Close();
//message.Delete(DeleteMode.HardDelete); // It deletes the messages permanently
//message.Delete(DeleteMode.MoveToDeletedItems); // It moves the processed messages to "Deleted Items" folder
}
catch (Exception exp)
{
Console.WriteLine("Error : " + exp);
}
}
}
catch (Exception exp2)
{
Console.WriteLine("Error : " + exp2);
}
}
Hope it helps, cheers.

badrequest error while requesting bing microsofttranslate api?

The following code returns bad request exception.Not sure what's wrong here .
string appId = "956vaQc49TdepGpsywiM+BRqfxfgOTeCr/514=";
//go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "translate this";
string language = "en";
System.Uri uri = new Uri("http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId + "&text=" + text + "&language=" + language);
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
Stream responseBody = await response.Content.ReadAsStreamAsync();
// meTextToSpeeach.Source = uri;
string strResponse;
using (Stream responseStream = responseBody)
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.Unicode))
{
strResponse = sr.ReadToEnd();
}
}
}
catch (Exception)
{
}
You are not encoding the parameters (appId, text, language). You should be doing "..." + WebUtility.UrlEncode(appId) + "..." ...