Posting score to Facebook app - c#

I've been trawling the answers in SO concerning posting a score to a Facebook app, and I still can't get it to work. The code I'm using is here -
private const string FACEBOOK_POST_SCORE_URL = "https://graph.facebook.com/me/scores?access_token={0}";
public void PostScoreAsync(Action<FacebookResponse> response, FacebookScore score)
{
try
{
// Append the user's access token to the URL
Uri fullUri = new Uri(string.Format(FACEBOOK_POST_SCORE_URL, AccessToken));
string json = JsonConvert.SerializeObject(score);
var request = (HttpWebRequest)WebRequest.Create(fullUri);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
request.BeginGetResponse(WebRequestCallback, new FacebookResult
{
Request = request,
Response = response
});
}
catch (ThreadAbortException)
{
throw;
}
catch (WebException ex)
{
if (response != null)
response(FacebookResponse.NetworkError);
}
catch (Exception ex)
{
if (response != null)
response(FacebookResponse.OtherError);
}
}
We're using webViews rather than iOS / Android Facebook SDKs, as we're building a cross-platform app in Mono.
Obviously I have the access token & the app appears to have full permissions to do what I want to do, which I allowed after login. Any thoughts appreciated!

I eventually found out (from a colleague) that the Facebook graph api won't take json encoded parameters, so we sorted it like so -
string parameters = "score=" + score.Score;
var request = (HttpWebRequest)WebRequest.Create(fullUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(parameters);
}
Now it works fine - hopefully this'll help someone else not have the same problem.

Related

How can I change the default icon brings OneSignal making a post from Xamarin.Forms?

I have done a post method to consult the OneSignal API Rest, that when an order has been accepted a notification is sent to the user from the device that placed the order and this is the code line that does not work, and it worked without the small_icon, large_icon and android_accent_color
CODE:
public static void PostNotification(string idPush)
{
var request = WebRequest.Create(AppSettings.OneSignalApi) as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", AppSettings.KeyPush);
byte[] byteArray = Encoding.UTF8.GetBytes("{"
+ $"\"app_id\": \"{AppSettings.PushIDApp}\","
+ "\"small_icon\": \"ic_stat_onesignal_default\","
+ "\"large_icon\": \"ic_onesignal_large_icon_default\","
+ "\"android_accent_color\": \"FFba3870\","
+ "\"contents\": {\"en\": \"Pedido Aceptado\"},"
+ $"\"include_player_ids\": [\"{idPush}\"]" +
"}");
string responseContent = null;
try
{
using (var writer = request.GetRequestStream())
{
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
}
I have the icons but it does not show them, it does not send me the notification with it, just removing the following 3 properties, small_icon, large_icon and android_accent_color I do not know if the way I am doing it will be wrong, and I have followed the documentation of the Create Notification.

Posting Json data to console

I'm trying to post Json data to my Console. I have the code that is requesting it. I think I either have my Parameters or something else that is wrong. I know I get to the site, but then I get a 500 Server Error. I'm stuck and any help would be appreciated. I took out the URL and USER and Pass. I left the other stuff. I have no idea what I'm doing as I usually work with SQL, but I was told to try this and see if I can get it to work. We are using a Console app with the .NET framework to try and get this to work. Please help as I'm out of ideas. Something might be wrong with the headers.Accept code as well.
I've tried changing the code where my params are, I've tried even google and looking at other stack over flow methods.
public static void Main(string[] args)
{
try
{
string webAddr ="MYURL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Accept = "application/Json";
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
USER_ID = "MyUser",
PASSWORD = "MyPass",
Query_ID = "4444",
Parameters = ""Key" ("Original"),"Value" ("1.1323")
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine("Here is your Json Data.....");
Console.WriteLine(responseText);
Console.ReadLine();
//Response success above and error below
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
For the Json data to show up in the Console.

How to add a specific user to a segment in OneSignal

I'm developing a C#.NET MVC Web Api for an Android application. At the moment I am using OneSignal to send push notifications to the users by calling the OneSignal Api and passing the notification content. I need to know how to add a user to a specific segment so that i can send notifications to individual users as well as users of that segment collectively. I have searched in on their documentation but I didn't understand how to do it using OneSignal.SendTag method. So basically how to do it in Visual Studio? So far i have done this:
string api_key = "dsabjd";
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
if (user != null)
{
string message = "This job is posted by: \n" + user.Name + "\n" + user.Contact + "\n" +user.City;
if (request != null)
{
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("authorization", "Basic "+api_key);
var serializer = new JavaScriptSerializer();
var obj = new
{
app_id = "1651",
contents = new { en = message },
//data = new { image = "http://dsadasdasd.png" },
data = new { image = imageUrl },
included_segments = new string[] { "All" }
};
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
try
{
using (var writer = request.GetRequestStream())
{
writer.Write(byteArray, 0, byteArray.Length);
}
string responseContent=null;
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
}
}
if (responseContent != null)
{
// parsing the json returned by OneSignal Push API
dynamic json = JObject.Parse(responseContent);
int noOfRecipients = json.recipients;
if (noOfRecipients > 0)
{
flag = true;
}
}
}
catch (WebException ex)
{
flag = false;
}
}
}
To set tags it is recommend you use sendTags from the OneSignal Android SDK in your app it's supported offline and handles retries for you.
If you need to target individual users it is recommend to call idsAvailable in your app and send this to your server. You can later use the include_player_ids field on the create notification REST API POST call to send a notification to a list of users.

How to connect EWS (Problematically) through windows phone 8.1?

I have been trying since last 3 days to connect EWS from windows phone 8.1. But I'm unable to connect with EWS.
I'm following this blog..
https://social.msdn.microsoft.com/Forums/en-US/78396950-7549-4f4f-92a6-bdf48c35300d/error-integrating-ews-22-with-windows-phone-81-app?forum=exchangesvrdevelopment
As per above site, the code which they did if we will implement that code in windows phone 8.1, the code give us exception "Method is not supported".
If we try to connect edmx url of EWS by using HttpClient from windows phone 8.1.. It will give us unauthorized ERROR.
I have checked iphone and android code for connect EWS. Its working fine.
Can any one help me for this?
Hi Jason,
I tried using HTTPWebRequest, in a sample command line project and it works fine. Below is the code -
public bool Request(string URL, string RequestXML, NetworkCredential UserCredentials)
{
HttpWebRequest SoapRequest = (HttpWebRequest)WebRequest.Create(URL);
StreamWriter RequestWriter=null;
Stream ResponseStream=null;
HttpWebResponse SoapResponse=null;
try
{
SoapRequest.AllowAutoRedirect = false;
SoapRequest.Credentials = UserCredentials;
SoapRequest.Method = "POST";
SoapRequest.ContentType = "text/xml";
RequestWriter = new StreamWriter(SoapRequest.GetRequestStream());
RequestWriter.Write(RequestXML);
RequestWriter.Close();
SoapResponse = (HttpWebResponse)SoapRequest.GetResponse();
if (SoapResponse.StatusCode == HttpStatusCode.OK)
{
ResponseStream = SoapResponse.GetResponseStream();
ResponseEnvelop = XElement.Load(ResponseStream);
return true;
}
else
{
return false;
}
}
catch(Exception ex)
{
ResponseEnvelop = null;
return false;
throw ex;
}
finally
{
SoapRequest = null;
RequestWriter.Dispose();
RequestWriter = null;
ResponseStream.Dispose();
ResponseStream = null;
SoapResponse.Dispose();
SoapResponse = null;
}
}
-------------
However some methods are not available in Windows App, so tried below code. There are no compile errors but I receive error "Method not supported". I am trying from weeks but no luck, wondering is some help is available
public async Task<bool> Request(string URL, string RequestXML, NetworkCredential UserCredentials)
{
HttpWebRequest SoapRequest = (HttpWebRequest)WebRequest.Create(URL);
StreamWriter RequestWriter = null;
Stream ResponseStream = null;
WebResponse SoapResponse = null;
try
{
SoapRequest.Credentials = UserCredentials;
SoapRequest.Method = "POST";
SoapRequest.ContentType = "text/xml";
RequestWriter = new StreamWriter(await System.Threading.Tasks.Task<Stream>.Run(() => SoapRequest.GetRequestStreamAsync()));
RequestWriter.AutoFlush = true;
RequestWriter.Write(RequestXML);
SoapResponse = await System.Threading.Tasks.Task<Stream>.Run(() => SoapRequest.GetResponseAsync());
ResponseStream = SoapResponse.GetResponseStream();
ResponseEnvelop = XElement.Load(ResponseStream);
return true;
}
Appreciate some quick help
Thanks,
Nasir

Google Translate V2 cannot hanlde large text translations from C#

I've implemented C# code using the Google Translation V2 api with the GET Method.
It successfully translates small texts but when increasing the text length and it takes 1,800 characters long ( including URI parameters ) I'm getting the "URI too large" error.
Ok, I burned down all the paths and investigated the issue across multiple pages posted on Internet. All of them clearly says the GET method should be overriden to simulate a POST method ( which is meant to provide support to 5,000 character URIs ) but there is no way to find out a code example to of it.
Does anyone has any example or can provide some information?
[EDIT] Here is the code I'm using:
String apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
String url = String.Format(apiUrl, Constants.apiKey, sourceLanguage, targetLanguage, text);
Stream outputStream = null;
byte[] bytes = Encoding.ASCII.GetBytes(url);
// create the http web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.KeepAlive = true;
webRequest.Method = "POST";
// Overrride the GET method as documented on Google's docu.
webRequest.Headers.Add("X-HTTP-Method-Override: GET");
webRequest.ContentType = "application/x-www-form-urlencoded";
// send POST
try
{
webRequest.ContentLength = bytes.Length;
outputStream = webRequest.GetRequestStream();
outputStream.Write(bytes, 0, bytes.Length);
outputStream.Close();
}
catch (HttpException e)
{
/*...*/
}
try
{
// get the response
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK && webRequest != null)
{
// read response stream
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string lista = sr.ReadToEnd();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TranslationRootObject));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(lista));
TranslationRootObject tRootObject = (TranslationRootObject)serializer.ReadObject(stream);
string previousTranslation = string.Empty;
//deserialize
for (int i = 0; i < tRootObject.Data.Detections.Count; i++)
{
string translatedText = tRootObject.Data.Detections[i].TranslatedText.ToString();
if (i == 0)
{
text = translatedText;
}
else
{
if (!text.Contains(translatedText))
{
text = text + " " + translatedText;
}
}
}
return text;
}
}
}
catch (HttpException e)
{
/*...*/
}
return text;
}
Apparently using WebClient won't work as you cannot alter the headers as needed, per the documentation:
Note: You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).
You can use WebRequest, but you'll need to add the X-HTTP-Method-Override header:
var request = WebRequest.Create (uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-HTTP-Method-Override", "GET");
var body = new StringBuilder();
body.Append("key=SECRET");
body.AppendFormat("&source={0}", HttpUtility.UrlEncode(source));
body.AppendFormat("&target={0}", HttpUtility.UrlEncode(target));
//--
body.AppendFormat("&q={0}", HttpUtility.UrlEncode(text));
var bytes = Encoding.ASCII.GetBytes(body.ToString());
if (bytes.Length > 5120) throw new ArgumentOutOfRangeException("text");
request.ContentLength = bytes.Length;
using (var output = request.GetRequestStream())
{
output.Write(bytes, 0, bytes.Length);
}
The accepted answer appears to be out of date. You can now use the WebClient (.net 4.5) successfully to POST to the google translate API making sure to set the X-HTTP-Method-Override header.
Here is some code to show you how.
using (var webClient = new WebClient())
{
webClient.Headers.Add("X-HTTP-Method-Override", "GET");
var data = new NameValueCollection()
{
{ "key", GoogleTranslateApiKey },
{ "source", "en" },
{ "target", "fr"},
{ "q", "<p>Hello World</p>" }
};
try
{
var responseBytes = webClient.UploadValues(GoogleTranslateApiUrl, "POST", data);
var json = Encoding.UTF8.GetString(responseBytes);
var result = JsonConvert.DeserializeObject<dynamic>(json);
var translation = result.data.translations[0].translatedText;
}
catch (Exception ex)
{
loggingService.Error(ex.Message);
}
}
? What? it is trivial to post using C# - it is right there in the documentation.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
{
// Set type to POST
request.Method = "POST";
From there on you bascially put the data into fom fields into the content stream.
This is not "simulate a post meethod", it is fully doing a post request as per specifications.
Btw. hwhere does json enter here? You say "in C#". There is no need to use json?

Categories

Resources