Tile notification for windows phone - invalid XML payload - - windows

I send two push notifications a toast and a tile (just a count)
the toast gets received:
<?xml version="1.0" encoding="UTF-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Toast><wp:Text1></wp:Text1><wp:Text2>asdf</wp:Text2><wp:Param></wp:Param></wp:Toast></wp:Notification>
the tile does not:
<?xml version="1.0" encoding="UTF-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Tile><wp:BackgroundImage></wp:BackgroundImage><wp:Count>122</wp:Count><wp:Title></wp:Title><wp:BackBackgroundImage></wp:BackBackgroundImage><wp:BackTitle></wp:BackTitle><wp:BackContent></wp:BackContent></wp:Tile></wp:Notification>
This is the xml i provide and I keep getting format errors. Is there something wrong in the format?

Your tile format should be like
string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Tile>" +
"<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +
"<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +
"<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +
"<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +
"<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +
"<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
"</wp:Tile> " +
"</wp:Notification>";
Sending tile notification code.It will work for me. If any query than let me know
protected void ButtonSendTile_Click(object sender, EventArgs e)
{
try
{
// Get the Uri that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
// Normally, a web service would listen for Uri's coming from the web client and maintain a list of Uri's to send
// notifications out to.
string subscriptionUri = TextBoxUri.Text.ToString();
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// We will create a HTTPWebRequest that posts the tile notification to the Microsoft Push Notification Service.
// HTTP POST is the only allowed method to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the // same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the tile message.
string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Tile>" +
"<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +
"<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +
"<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +
"<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +
"<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +
"<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +
"</wp:Tile> " +
"</wp:Notification>";
// Sets the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage);
// Sets the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
sendNotificationRequest.Headers.Add("X-NotificationClass", "1");
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
}

Related

Use Exchange Web Service Managed API to retrieve max send mail size limit

I've been looking around for some way to use the EWS managed API to retrieve the maximum mail size limit for sending, but have not found any working solution...
So far, I've came across this link: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-get-service-configuration-information-by-using-ews-in-exchange#code-example-get-service-configuration-information-for-mail-tips-by-using-ews
Which basically retrieves the The maximum message size in the Mail Tips. But the thing is, when I tried out the code, I got an 500 internal server error. And there doesn't seem to be a way to do this directly using the Managed API itself.
Greatly appreciate any help.
Thanks!
There is a bug in the Microsoft Sample they have modified the SOAP namespaces from http to https. Probably some editor thought they where doing the correct thing without understanding how XML schema's work. But a working sample is
private static void GetServiceConfiguration()
{
// XML for the GetServiceConfiguration request SOAP envelope for mail tips configuration information.
const string getServiceConfigurationRequest =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\"\n" +
" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" \n" +
" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <soap:Header>\n" +
" <t:RequestServerVersion Version=\"Exchange2013\" />\n" +
" </soap:Header>\n" +
" <soap:Body>\n" +
" <m:GetServiceConfiguration>\n" +
" <m:ActingAs>\n" +
" <t:EmailAddress>user#domain.com</t:EmailAddress>\n" +
" <t:RoutingType>SMTP</t:RoutingType>\n" +
" </m:ActingAs>\n" +
" <m:RequestedConfiguration>\n" +
" <m:ConfigurationName>MailTips</m:ConfigurationName>\n" +
" </m:RequestedConfiguration>\n" +
" </m:GetServiceConfiguration>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
// Encoded GetServiceConfiguration operation request.
byte[] payload = System.Text.Encoding.UTF8.GetBytes(getServiceConfigurationRequest);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://outlook.office365.com/ews/exchange.asmx");
request.AllowAutoRedirect = false;
request.Credentials = new NetworkCredential("user#domain.com", "blah");
request.Method = "POST";
request.ContentType = "text/xml";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";
Stream requestStream = request.GetRequestStream();
requestStream.Write(payload, 0, payload.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine("You will need to parse this response to get the configuration information:\n\n" + responseFromServer);
reader.Close();
responseStream.Close();
}
else
throw new WebException(response.StatusDescription);
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
I've also added in a useragent as this can sometimes also cause the code to fail if useragent restriction have been set. But you should also switch to using OAuth if you are using this against Office365.

Java Fitbit by using FITBIT4j --approach through pin method

FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitAPIClientService<FitbitApiClientAgent> fitbit = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl,
credentialsCache), clientConsumerKey, clientSecret,
credentialsCache, entityCache, subscriptionStore);
final LocalUserDetail localUser = new LocalUserDetail("1");//user means my userid
String url = fitbit.getResourceOwnerAuthorizationURL(localUser, "");
System.out.println("Open " + url);
System.out.print("Enter PIN:");//What is this? Is this the userid?
String pin = readFromUser();
APIResourceCredentials creds = fitbit
.getResourceCredentialsByUser(localUser);
creds.setTempTokenVerifier(pin);
fitbit.getTokenCredentials(localUser);
// you can save the access_token here to reuse later
// System.out.println("Your access_token: " + creds.getAccessToken());
// System.out.println("Your access_token_secret: " + creds.getAccessTokenSecret());
UserInfo profile = fitbit.getClient().getUserInfo(localUser);
System.out.println(profile.getDisplayName() + ", member since "
+ profile.getMemberSince());
LocalDate date = FitbitApiService.getValidLocalDateOrNull("2012-06-01");
Sleep sleep = fitbit.getClient().getSleep(localUser,
FitbitUser.CURRENT_AUTHORIZED_USER, date);
System.out.println("Your sleep on " + date + ": inBed=" + sleep.getSummary().getTotalTimeInBed() + " asleep=" + sleep.getSummary().getTotalMinutesAsleep());
Error:
com.fitbit.api.FitbitAPIException: 500: Something is broken. Please
post to the group so the Fitbit team can investigate.
{"errors":[{"errorType":"request","fieldName":"500","message":"Oops!
An unexpected error occurred. If it continues please report it at
help.fitbit.com."}],"success":false}
How to proceed with pin based approach ? What is the pin ? How to get the pin for a fitbit user? (as Iam a fitbit user).

Using Soap Creating new Record in Dynamics crm 2013?

I'm trying to create a new record using soap call but its getting error at GenerateAuthenticattionHeader is undefined.could any references appreciated.
function new_record()
{
debugger;
var firstname = "srini";
var lastname = "hsk";
var donotbulkemail = "true";
var address1_stateorprovince = "CHD";
var address1_postalcode = "160036";
var address1_line1 = "#1429/2";
var address1_city = "Chandigarh";
var authenticationHeader = GenerateAuthenticationHeader();
// Prepare the SOAP message.
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
authenticationHeader +
"<soap:Body>" +
"<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
"<entity xsi:type='contact'>" +
"<address1_city>" + address1_city + "</address1_city>" +
"<address1_line1>" + address1_line1 + "</address1_line1>" +
"<address1_postalcode>" + address1_postalcode + "</address1_postalcode>" +
"<address1_stateorprovince>" + address1_stateorprovince + "</address1_stateorprovince>" +
"<donotbulkemail>" + donotbulkemail + "</donotbulkemail>" +
"<firstname>" + firstname + "</firstname>" +
"<lastname>" + lastname + "</lastname>" +
"</entity>" +
"</Create>" +
"</soap:Body>" +
"</soap:Envelope>";
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Create");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result
var resultXml = xHReq.responseXML;
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0) {
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
}
GetAuthenticationHeader undefined in dynamics crm 2013
Generally your code looks good with one exception. It is good for CRM 4.0. In case you use CRM 2013 your code would not work. Recheck following articles regarding Creation of records in CRM: http://msdn.microsoft.com/en-us/library/gg334427.aspx
Provided link demonstrates how to create records using REST. In case you anyway want to use SOAP recheck following article: http://mileyja.blogspot.com/2011/04/create-requests-in-net-and-jscript-in.html

Windows Phone 7.5 POST method return remote server not found

I'm trying to make a POST but every time returns an error saying
"The remote server returned an error: NotFound."
I'm using Firebug extension of Firefox to get all the necessary parameters of the POST method but firebug says
"... Firebug request size limit has been reached by Firebug. ..."
. Also wireshark says more or less the same thing.
I don't know if I need to specify (on windows phone 7 HttpWebRequest) some extra parameters on header because of the long POST method.
This is my code:
private void GetResponseCallbackAGCP(IAsyncResult asynchronousResult)
{
Uri url = new Uri("http://publico.agcp.ipleiria.pt/Paginas/ScheduleRptCursosSemanalPublico.aspx");
postData = "MSO_PageHashCode=" + _MSO_PageHashCode +
"&__SPSCEditMenu=" + ___SPSCEditMenu +
"&MSOWebPartPage_PostbackSource=" +
"&MSOTlPn_SelectedWpId=" +
"&MSOTlPn_View=0" +
"&MSOTlPn_ShowSettings=" + _MSOTlPn_ShowSettings +
"&MSOGallery_SelectedLibrary=" +
"&MSOGallery_FilterString=" +
"&MSOTlPn_Button=" + _MSOTlPn_Button +
"&MSOAuthoringConsole_FormContext=" +
"&MSOAC_EditDuringWorkflow=" +
"&MSOSPWebPartManager_DisplayModeName=" + _MSOSPWebPartManager_DisplayModeName +
"&__EVENTTARGET=" + _eventTarget +
"&__EVENTARGUMENT=" + _eventArg +
"&MSOWebPartPage_Shared=" +
"&MSOLayout_LayoutChanges=" +
"&MSOLayout_InDesignMode=" +
"&MSOSPWebPartManager_OldDisplayModeName=" + _MSOSPWebPartManager_OldDisplayModeName +
"&MSOSPWebPartManager_StartWebPartEditingName=" + _MSOSPWebPartManager_StartWebPartEditingName +
"&__LASTFOCUS=" +
"&__REQUESTDIGEST=" + ___REQUESTDIGEST +
"&__VIEWSTATE=" + _viewState +
"&__EVENTVALIDATION=" + _eventEval +
"&ctl00%24ctl12%24ctl00=http%3A%2F%2Fspserver%3A7250" +
"&ctl00%24PlaceHolderAGCPUO%24ddlUO=" + escolaSelected +
"&ctl00%24PlaceHolderAGCPUO%24ddlAnosLectivos=" + anoLectivoSelected +
"&ctl00%24PlaceHolderAGCPUO%24ddlPeriodos=" + periodoSelected +
"&ctl00%24PlaceHolderMain%24ddlCursos=" + cursoSelected +
"&ctl00%24PlaceHolderMain%24ddlAnosCurr=" + anoCurricularSelected +
"&ctl00%24PlaceHolderMain%24ddlPlanos=" + planoSelected +
"&ctl00%24PlaceHolderMain%24ddlRamos=" + troncoSelected +
"&ctl00%24PlaceHolderMain%24ddlTurmas=" + turmaSelected +
"&ctl00%24PlaceHolderMain%24txtObservacoesHor=" +
"&ctl00%24PlaceHolderMain%24ddlZoom=1250" +
"&ctl00%24PlaceHolderMain%24ddlSemanas=" + semanaSelected +
"&ctl00_PlaceHolderMain_DayPilotCalendar1_vsupdate=" +
"&ctl00_PlaceHolderMain_DayPilotCalendar1_scrollpos=" +
"&ctl00_PlaceHolderMain_DayPilotCalendar1_select=" +
"&__spDummyText1=__spDummyText1&__spDummyText2=__spDummyText2";
cc = new CookieContainer();
webRequest2 = (HttpWebRequest)WebRequest.Create(url);
webRequest2.Method = "POST";
webRequest2.ContentType = "application/x-www-form-urlencoded";
webRequest2.CookieContainer = cc;
webRequest2.BeginGetRequestStream(new AsyncCallback(GetRequestCallback), webRequest2);
}
private void GetRequestCallback(IAsyncResult asynchronousResult)
{
var request = asynchronousResult.AsyncState as HttpWebRequest;
StreamWriter stream = new StreamWriter(request.EndGetRequestStream(asynchronousResult));
stream.Write(postData);
stream.Flush();
stream.Close();
request.BeginGetResponse(AuthCallback, request);
}
private void AuthCallback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); //RETURNS an error saying "WebException was unhandle. The remote server returned an error: NotFound."
using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
{
//string resultString = streamReader1.ReadToEnd();
var info = streamReader1.ReadToEnd();
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
webView.NavigateToString(info);
});
}
}
Thanks in advance!
Try using RestSharp, it greatly simplifies the Http stuff. I have been using RestSharp in all my WP7 Projects.
http://restsharp.org/
This Exception also come due to Firewall just turn off firewall
Go Control Panel\All Control Panel Items\Windows Firewall\Customize Settings
and turn off firewall.

How can I get the Exchange Server programmatically from my App(C#)

Currently I can send email successfully through WebDAV with C#, but there is a shortage in my App that I have hard-code the Exchange Server of my outlook, so it might only works for me, if it were moved to another PC and use another outlook account, it might not work because the Exchange Server for this outlook account might not the same as mine(that's beacuse our company for different email account might assign different Exchange server), so my question is that how can I get the Exchange Server for the current Email accout dynamically. In fact I can get this Exchange Server from the outlook client when I clicked the menu item to add a new Outlook Account, but dose there exist any API for me to get this Exchange Server programmatically such as with C#?
In fact I use the following code to send Email:
using System;
using System.Net;
using System.IO;
namespace WebDavNET
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
try
{
// TODO: Replace with the name of the computer that is running Exchange 2000.
string strServer = "ExchServe";
// TODO: Replace with the sender's alias.
string strSenderAlias = "sender";
// TODO: Replace with the sender's e-mail address.
string strFrom = "sender#example.com";
// TODO: Replace with the recipient's e-mail address.
string strTo = "recipient#example.com";
string strSubject = "Send Using HttpWebRequest";
string strBody = "Hello World";
string sUri;
sUri = "http://" + strServer + "/Exchange/" + strSenderAlias;
sUri = sUri + "/%23%23DavMailSubmissionURI%23%23/";
System.Uri myUri = new System.Uri(sUri);
HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(myUri);
string sQuery;
DateTime mySentTime = new DateTime();
sQuery = "From: " + strFrom + "\n" +
"To: " + strTo + "\n" +
"Subject: " + strSubject + "\n" +
"Date: " + DateTime.Now.ToString() + "\n" +
"X-Mailer: My DAV mailer" + "\n" +
"MIME-Version: 1.0" + "\n" +
"Content-Type: text/plain;" + "\n" +
"Charset = \"iso-8859-1\"" + "\n" +
"Content-Transfer-Encoding: 7bit" + "\n" + "\n" +
strBody;
// Set the credentials.
// TODO: Replace with the appropriate user credential.
NetworkCredential myCred = new NetworkCredential(#"DomainName\User", "Password");
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myCred);
HttpWRequest.Credentials = myCredentialCache;
// Set the headers.
HttpWRequest.Headers.Set("Translate", "f");
HttpWRequest.ContentType = "message/rfc822";
HttpWRequest.ContentLength = sQuery.Length;
//Set the request timeout to 5 minutes.
HttpWRequest.Timeout = 300000;
// Set the request method.
HttpWRequest.Method = "PUT";
// Store the data in a byte array.
byte[] ByteQuery = System.Text.Encoding.ASCII.GetBytes(sQuery);
HttpWRequest.ContentLength = ByteQuery.Length;
Stream QueryStream = HttpWRequest.GetRequestStream();
// write the data to be posted to the Request Stream
QueryStream.Write(ByteQuery,0,ByteQuery.Length);
QueryStream.Close();
// Send the request and get the response.
HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();
// Get the Status code.
int iStatCode = (int)HttpWResponse.StatusCode;
string sStatus = iStatCode.ToString();
Console.WriteLine("Status Code: {0}", sStatus);
// Get the request headers.
string sReqHeaders = HttpWRequest.Headers.ToString();
Console.WriteLine(sReqHeaders);
// Read the response stream.
Stream strm = HttpWResponse.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string sText = sr.ReadToEnd();
Console.WriteLine("Response: {0}", sText);
// Close the stream.
strm.Close();
// Clean up.
myCred = null;
myCredentialCache = null;
HttpWRequest = null;
HttpWResponse = null;
QueryStream = null;
strm = null;
sr = null;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
}
As you can see in the code there is a variable named "strServer", In my App I just hard-code my Exchange Server for this variable, so my question is that dose there exist any API for me to get the Exchange Server dynamically for the specific outlook account?
Thanks!
You can use EWS(exchange Web Services) too. here is the link
You can use XML creator for creating items or requests required for operations in the link. Just go through the operations given on the link.

Resources