how send Push Notification to Kindle Fire from WCF rest service - push-notification

I want to send push notifications to Kindle Fire from WCF rest service.
I used PushSharp library, but it is not working properly. Can you please suggest any other way without using PushSharp library?
I am using below code to send notification on kindle it is give error 400,
private void sendNotification(String registrationID)
{
String message = "{data\": {\"NTY\":\"-1\",\"NOTY\": \"2\"}}";
String title="title";
String accessToken = "";
accessToken = UpdateAccessToken();
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("https://api.amazon.com/messaging/registrations/" + registrationID + "/messages");
Encoding encoding = new UTF8Encoding();
string postData = "{\"data\":{\"message\":\"" + message + "\",\"title\":\"" + title + "\"},\"consolidationKey\":\"Some Key\",\"expiresAfter\":86400}";
byte[] data = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json";//charset=UTF-8";
httpWReq.Headers.Add("X-Amzn-Type-Version",
"com.amazon.device.messaging.ADMMessage#1.0");
httpWReq.Headers.Add("X-Amzn-Accept-Type",
"com.amazon.device.messaging.ADMSendResult#1.0");
httpWReq.Headers.Add(HttpRequestHeader.Authorization,
"Bearer " + accessToken);
httpWReq.ContentLength = data.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
String jsonresponse = "";
String temp = null;
while ((temp = reader.ReadLine()) != null)
{
jsonresponse += temp;
}
}

PushSharp relies on Google Cloud Messaging for Android, which is not supported on Kindle. You would need to either implement an Amazon Device Messaging (ADM) version (https://developer.amazon.com/public/apis/engage/device-messaging) or take advantage of Amazon's Simple Notification Service (SNS) to target Kindle and other platforms (https://aws.amazon.com/sns/)

Related

Getting Sharepoint-hosted app current user from within ASP.NET Web API

i have an ASP.NET Web API which i'm using in my SharePoint-hosted app to do CRUD operations via REST. I want to get the current user's credentials (O365 account) from within my web api controllers? Is it possible? Any suggestions or referenced would be much appreciated. TIA
I was able to accomplish this by using the below code in my controller:
Uri targetWeb = new Uri(HttpContext.Request.QueryString["SPHostUrl"]);
string targetRealm = TokenHelper.GetRealmFromTargetUrl(spContext.SPHostUrl);
var responseToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, targetWeb.Authority, targetRealm);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(spContext.SPHostUrl + "_api/Web/SiteUserInfoList/Items("+ spUser.Id + ")"); // spUser.Id from spContext
request.Method = "GET";
request.Accept = "application/json;odata=verbose";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + spContext.UserAccessTokenForSPHost);
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
if (dataStream == null)
{
ViewBag.res = "nothing";
}else
{
StreamReader reader = new StreamReader(dataStream);
var result = reader.ReadToEnd();
var resData = Json(result);
ViewBag.res= resData.Data; // res must be parse when using js
}
return View();
...not sure if it's the best practice but it did the job.

Facebook notification post data asp.net

I created a facebook app. A small game in asp.net mvc. It is a real time turn based game and i want the first player to choose his opponent, send him a facebook notification and go to the page of tthe game.
The second player then clicks on this notification and also go the the page of the game.
My problem is about the href parameter of the post data.
In asp.net i create a webhttprequest object. But my data i have to post is like that :
But when second player click on notification the last two parameters are lost. I think it is because symbol & is used with facebook graph address and with my address. How can i write the correct postdata with all the parameters ??
Here is my code :
public string sendnotificationtoplay(string monid, string prenomMoi, string codetokenjeu)
{
try
{
// variables to store parameter values
string url = "https://graph.facebook.com/" + monid + "/notifications";
string autrePrenom = "#[" + monid + "]";
string texte = "#[" + monid + "] ! " + prenomMoi + " wants to play with you ! \n Click here !";
// creates the post data for the POST request
string postData = ("access_token=MYACCESSTOKEN&template=" + texte + "&href=mywebsite.org/Index?ordredemandejeugame=2&codejeuadeux=ds&prenom1=dfdf&prenom2=fdgdfg");
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
// POST the data
using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter2.Write(postData);
}
// This actually does the request and gets the response back
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
string responseData = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
// dumps the HTML from the response into a string variable
responseData = responseReader.ReadToEnd();
}
return responseData;`
please help me :)
Thank you in advance !

Embed DocuSign Signing Experience in a .NET Application

I am working in a .NET Web Application(Web Forms).I need to embed the document signing experience into my web application,preferably by means of an Iframe.
Is is possible to authenticate to docusign from the web application and then bring the signing experience in an Iframe?
Also is it possible to re-direct to a custom URL on signing complete,signing declined,window closed..etc?
This is a copy of the API walkthrough on how to do embedded signing in C#. You can find other walkthroughs here: http://iodocs.docusign.com/APIWalkthroughs.
The code below should do exactly what you are looking for - give you an authenticated IFRAME ready for signing. Before using this you should create a template with your document and place the signature tabs in the places where you want someone to sign.
// DocuSign API Walkthrough 08 in C# - Embedded Signing
// To run this sample:
// 1) Create a new .NET project.
// 2) Add 3 assembly references to the project: System, System.Net, and System.XML
// 3) Update the username, password, integrator key, and templateId in the code
// 4) Compile and Run
//
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
namespace APIWalkthrough08
{
public class EmbeddedSigning
{
// Enter your info:
static string username = "***";
static string password = "***";
static string integratorKey = "***";
static string templateId = "***";
static string roleName = "***";
public static void Main ()
{
string url = "https://demo.docusign.net/restapi/v2/login_information";
string baseURL = ""; // we will retrieve this
string accountId = ""; // will retrieve
string envelopeId = ""; // will retrieve
string uri = ""; // will retrieve
string authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + username + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
//
// STEP 1 - Login
//
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.Headers.Add ("X-DocuSign-Authentication", authenticateStr);
request.Accept = "application/xml";
request.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse ();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string responseText = sr.ReadToEnd();
using (XmlReader reader = XmlReader.Create(new StringReader(responseText))) {
while (reader.Read()) { // Parse the xml response body
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "accountId"))
accountId = reader.ReadString();
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "baseUrl"))
baseURL = reader.ReadString();
}
}
//--- display results
Console.WriteLine("accountId = " + accountId + "\nbaseUrl = " + baseURL);
//
// STEP 2 - Request Envelope Result
//
// Construct an outgoing XML request body
string requestBody = "<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<accountId>" + accountId + "</accountId>" +
"<status>sent</status>" +
"<emailSubject>API Call for Embedded Sending</emailSubject>" +
"<emailBlurb>This comes from C#</emailBlurb>" +
"<templateId>" + templateId + "</templateId>" +
"<templateRoles>" +
"<templateRole>" +
"<email>" + username + "</email>" + // NOTE: Use different email address if username provided in non-email format!
"<name>Name</name>" + // username can be in email format or an actual ID string
"<roleName>" + roleName + "</roleName>" +
"<clientUserId>1</clientUserId>" +
"</templateRole>" +
"</templateRoles>" +
"</envelopeDefinition>";
// append "/envelopes" to baseUrl and use in the request
request = (HttpWebRequest)WebRequest.Create (baseURL + "/envelopes");
request.Headers.Add ("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = requestBody.Length;
request.Method = "POST";
// write the body of the request
byte[] body = System.Text.Encoding.UTF8.GetBytes (requestBody);
Stream dataStream = request.GetRequestStream ();
dataStream.Write (body, 0, requestBody.Length);
dataStream.Close ();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd();
using (XmlReader reader = XmlReader.Create(new StringReader(responseText))) {
while (reader.Read()) { // Parse the xml response body
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopeId"))
envelopeId = reader.ReadString();
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "uri"))
uri = reader.ReadString();
}
}
//--- display results
Console.WriteLine("Envelope sent!. EnvelopeId is --> " + envelopeId);
//
// STEP 3 - Get the Embedded Console Sign View
//
// construct another outgoing XML request body
string reqBody = "<recipientViewRequest xmlns=\"http://www.docusign.com/restapi\">" +
"<authenticationMethod>email</authenticationMethod>" +
"<email>" + username + "</email>" + // NOTE: Use different email address if username provided in non-email format!
"<returnUrl>http://www.docusign.com</returnUrl>" + // username can be in email format or an actual ID string
"<clientUserId>1</clientUserId>" +
"<userName>Name</userName>" +
"</recipientViewRequest>";
// append uri + "/views/recipient" to baseUrl and use in the request
request = (HttpWebRequest)WebRequest.Create (baseURL + uri + "/views/recipient");
request.Headers.Add ("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = reqBody.Length;
request.Method = "POST";
// write the body of the request
byte[] body2 = System.Text.Encoding.UTF8.GetBytes (reqBody);
Stream dataStream2 = request.GetRequestStream ();
dataStream2.Write (body2, 0, reqBody.Length);
dataStream2.Close ();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();
sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd();
using (XmlReader reader = XmlReader.Create(new StringReader(responseText))) {
while (reader.Read()) { // Parse the xml response body
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "url"))
url = reader.ReadString();
}
}
Console.WriteLine("Embeded View Result --> " + responseText);
System.Diagnostics.Process.Start(url);
}
catch (WebException e) {
using (WebResponse response = e.Response) {
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
Console.WriteLine(text);
}
}
}
} // end main()
} // end class
} // end namespace
If you haven't already done so, I'd suggest that you review the DocuSign REST API Guide: http://www.docusign.com/sites/default/files/REST_API_Guide_v2.pdf -- as it contains all the information you need to accomplish your goals (in greater detail than I'll describe here).
To create/send an Envelope via the REST API, you'll use POST /accounts/{accountId}/envelopes, as described in the "Send an Envelope or Create a Draft Envelope" section of the API guide. For each recipient whom you'll want to sign embedded/captive within your application, be sure to set the clientUserId property for the recipient -- the presence of this property for a recipient in the Create Envelope request is what tells DocuSign that your application will be initiating/facilitating the signing experience for the Recipient (so DocuSign won't send a signing invitation email to the Recipient).
When it's time for the Recipient to view/sign the Envelope within your application, you'll use POST /accounts/{accountId}/envelopes/{envelopeId}/views/recipient, as described in the "POST Recipient View" section of the API guide -- to retrieve a URL that can be used to launch/initiate the Recipient's DocuSign signing session. Using this URL as the target of an iFrame will present the DocuSign signing session within the frame. In the POST Recipient View request, you set the returnUrl property to indicate where DocuSign should redirect the signer when their embedded/captive signing session is complete. DocuSign will append a querystring parameter ("event") when redirecting to this URL, and the value of that parameter will indicate the outcome of the Signing session. The returnUrl parameter description on page 167 of the API guide lists the possible values of this parameter. Your application (i.e., the redirect page you specify) can interrogate this parameter value to know the outcome of the signing session, and take whatever action is necessary.
Regarding authentication -- the information used to authenticate the Sender of the Envelope is supplied via the X-DocuSign-Authentication header of each API request. Additionally, a specific form of authentication can be specified for each Recipient -- for example, Access Code, Phone Authentication, ID Check, SMS Auth -- you can specify authentication method for each Recipient by setting the appropriate properties for each Recipient in the "Create Envelope" request. (The API Guide contains info about these properties.)

Serializing using protobuf-net and sending as postdata in http

I'm using Protobuf-net to try and send a serialized object to a webapplication that I'm running in another project. The Serializer.Serialize<T>() method takes a Stream (to write to) and and instance of T (in this case, a list of a few objects that I set up to work with protobuf-net)
How do I go about doing this? Do I need to write to a file or can I send the stream as postdata somehow? Below you can see I'm using a string as the postdata.
My execute post method
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}
You can just serialize to the request:
Serializer.Serialize(dataStream, obj);
And equally, you can deserialize from receiveStream, if you choose.
Note, however, that protobuf data is not text, and should not be treated as such - very bad things happen if you try that.

Consuming REST Service pb

I'm having some problem consuming REST Service and want to figure out what I'm missing in implementation.
https://<server-name-or-address>/api/sessions
if I call this rest api using cURL, it works just fine by following script
curl -i -k -H "Accept:application/*+xml;version=1.5" -u username:password -X POST https://<server-name-or-address>/api/sessions
However, it isn't working at all with C# asp.net. I'm not sure what I'm missing here. Here are my attempts:
1) Using HTTP Web Request
Uri address = new Uri(url);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/*+xml;version=1.5";
request.Credentials = new NetworkCredential(username,password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// following exception fires on calling aforementioned statement
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
2) Using Hammock.net
Hammock.RestClient client = new Hammock.RestClient();
string encodedAPIKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
client.AddHeader("Accept", "application/*+xml;version=1.5");
client.AddHeader("Authorization", "Basic " + username + ":" + password);
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content; // exception
3) Using RestSharp
string _loginInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
RestSharp.RestClient client = new RestSharp.RestClient();
client.AddDefaultHeader("Accept", "application/*+xml;version=1.5");
client.AddDefaultHeader("Authorization", "Basic " + _loginInfo);
client.BaseUrl = url;
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.AddUrlSegment("method", "POST");
request.AddUrlSegment("uri", url);
string result = client.Execute(request).Content;
I also have tried with HttpClient, WebRequest, WebClient though nothing appears to work.
Try manually setting the Authorization header yourself in the HTTP request.
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
request.Headers.Add("Authorization", authorization);
EDIT:
It looks as though it may be due to a self-signed, expired, or otherwise invalid cert. Try the following
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Gleaned from this SO: https://stackoverflow.com/questions/5595049/servicepointmanager-servercertificatevalidationcallback-question

Resources